diff options
Diffstat (limited to 'gnu/llvm/lldb/packages/Python/lldbsuite/test')
2587 files changed, 140692 insertions, 0 deletions
diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/README-TestSuite b/gnu/llvm/lldb/packages/Python/lldbsuite/test/README-TestSuite new file mode 100644 index 00000000000..8ea64c0aa3d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/README-TestSuite @@ -0,0 +1,182 @@ +This README file describes the files and directories related -*- rst -*- +to the Python test suite under the current 'test' directory. + +- dotest.py + + Provides the test driver for the test suite. To invoke it, cd to the 'test' + directory and issue the './dotest.py' command or './dotest.py -v' for more + verbose output. '.dotest.py -h' prints out the help messge. + + A specific naming pattern is followed by the .py script under the 'test' + directory in order to be recognized by 'dotest.py' test driver as a module + which implements a test case, namely, Test*.py. + + Some example usages: + + 1. ./dotest.py -v . 2> ~/Developer/Log/lldbtest.log0 + This runs the test suite and directs the run log to a file. + + 2. LLDB_LOG=/tmp/lldb.log GDB_REMOTE_LOG=/tmp/gdb-remote.log ./dotest.py -v . 2> ~/Developer/Log/lldbtest.log + This runs the test suite, with logging turned on for the lldb as well as + the process.gdb-remote channels and directs the run log to a file. + +- lldbtest.py + + Provides an abstract base class of lldb test case named 'TestBase', which in + turn inherits from Python's unittest.TestCase. The concrete subclass can + override lldbtest.TestBase in order to inherit the common behavior for + unittest.TestCase.setUp/tearDown implemented in this file. + + To provide a test case, the concrete subclass provides methods whose names + start with the letters test. For more details about the Python's unittest + framework, go to http://docs.python.org/library/unittest.html. + + ./command_source/TestCommandSource.py provides a simple example of test case + which overrides lldbtest.TestBase to exercise the lldb's 'command source' + command. The subclass should override the attribute 'mydir' in order for the + runtime to locate the individual test cases when running as part of a large + test suite or when running each test case as a separate Python invocation. + + The doc string provides more details about the setup required for running a + test case on its own. To run the whole test suite, 'dotest.py' is all you + need to do. + +- subdirectories of 'test' + + Most of them predate the introduction of the python test suite and contain + example C/C++/ObjC source files which get compiled into executables which are + to be exercised by the debugger. + + For such subdirectory which has an associated Test*.py file, it was added as + part of the Python-based test suite to test lldb functionality. + + Some of the subdirectories, for example, the 'help' subdirectory, do not have + C/C++/ObjC source files; they were created to house the Python test case which + does not involve lldb reading in an executable file at all. + + The sample_test directory contains examples of both a full and an "inline" + testcase that run a process to a breakpoint and check a local variable. These + are convenient starting points for adding new tests. + +- make directory + + Contains Makefile.rules, which can be utilized by test cases to write Makefile + based rules to build binaries for the inferiors. + + By default, the built executable name is a.out, which can be overwritten by + specifying your EXE make variable, via the Makefile under the specific test + directory or via supplying a Python dictionary to the build method in your + Python test script. An example of the latter can be found in + test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py, where: + + def test_method_ret_BOOL_with_dsym(self): + """Test that objective-c method returning BOOL works correctly.""" + d = {'EXE': self.exe_name} + self.buildDsym(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.objc_method_ret_BOOL(self.exe_name) + + def test_method_ret_BOOL_with_dwarf(self): + """Test that objective-c method returning BOOL works correctly.""" + d = {'EXE': self.exe_name} + self.buildDwarf(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.objc_method_ret_BOOL(self.exe_name) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to break inside main(). + self.main_source = "main.m" + self.line = line_number(self.main_source, '// Set breakpoint here.') + + The exe names for the two test methods are equal to the test method names and + are therefore guaranteed different. + +- plugins directory + + Contains platform specific plugin to build binaries with dsym/dwarf debugging + info. Other platform specific functionalities may be added in the future. + +- unittest2 directory + + Many new features were added to unittest in Python 2.7, including test + discovery. unittest2 allows you to use these features with earlier versions of + Python. + + It currently has unittest2 0.5.1 from http://pypi.python.org/pypi/unittest2. + Version 0.5.1 of unittest2 has feature parity with unittest in Python 2.7 + final. If you want to ensure that your tests run identically under unittest2 + and unittest in Python 2.7 you should use unittest2 0.5.1. + + Later versions of unittest2 include changes in unittest made in Python 3.2 and + onwards after the release of Python 2.7. + +- dotest.pl + + In case you wonder, there is also a 'dotest.pl' perl script file. It was + created to visit each Python test case under the specified directory and + invoke Python's builtin unittest.main() on each test case. + + It does not take advantage of the test runner and test suite functionality + provided by Python's unitest framework. Its existence is because we want a + different way of running the whole test suite. As lldb and the Python test + suite become more reliable, we don't expect to be using 'dotest.pl' anymore. + + Note: dotest.pl has been moved to the attic directory. + +- Profiling dotest.py runs + + I used the following command line thingy to do the profiling on a SnowLeopard + machine: + + $ DOTEST_PROFILE=YES DOTEST_SCRIPT_DIR=/Volumes/data/lldb/svn/trunk/test /System/Library/Frameworks/Python.framework/Versions/Current/lib/python2.6/cProfile.py -o my.profile ./dotest.py -v -w 2> ~/Developer/Log/lldbtest.log + + After that, I used the pstats.py module to browse the statistics: + + $ python /System/Library/Frameworks/Python.framework/Versions/Current/lib/python2.6/pstats.py my.profile + +- Writing test cases: + + We strongly prefer writing test cases using the SB API's rather than + the runCmd & expect. Unless you are actually testing some feature + of the command line, please don't write command based tests. For + historical reasons there are plenty of examples of tests in the test + suite that use runCmd where they shouldn't, but don't copy them, + copy the plenty that do use the SB API's instead. + + The reason for this is that our policy is that we will maintain + compatibility with the SB API's. But we don't make any similar + guarantee about the details of command result format. If your test + is using the command line, it is going to have to check against the + command result text, and you either end up writing your check + pattern by checking as little as possible so you won't be exposed to + random changes in the text; in which case you can end up missing + some failure, or you test too much and it means irrelevant changes + break your tests. + + However, if you use the Python API's it is possible to check all the + results you want to check in a very explicit way, which makes the + tests much more robust. + + Even if you are testing that a command-line command does some + specific thing, it is still better in general to use the SB API's to + drive to the point where you want to run the test, then use + SBInterpreter::HandleCommand to run the command. You get the full + result text from the command in the command return object, and all + the part where you are driving the debugger to the point you want to + test will be more robust. + + The sample_test directory contains a standard and an "inline" test + that are good starting points for writing a new test. + +- Attaching in test cases: + + If you need to attach to inferiors in your tests, you must make sure + the inferior calls lldb_enable_attach(), before the debugger + attempts to attach. This function performs any platform-specific + processing needed to enable attaching to this process (e.g., on + Linux, we execute prctl(PR_SET_TRACER) syscall to disable + protections present in some Linux systems). diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/__init__.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/__init__.py new file mode 100644 index 00000000000..93971c2f236 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/__init__.py @@ -0,0 +1,7 @@ +# Module level initialization for the `lldbsuite.test` module. + +from __future__ import absolute_import + +from . import dotest + +run_suite = dotest.run_suite diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/android/platform/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/android/platform/Makefile new file mode 100644 index 00000000000..3d0b98f13f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/android/platform/Makefile @@ -0,0 +1,2 @@ +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py new file mode 100644 index 00000000000..0a5475c6749 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py @@ -0,0 +1,45 @@ +""" +Verify the default cache line size for android targets +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DefaultCacheLineSizeTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessTargetAndroid + def test_cache_line_size(self): + self.build(dictionary=self.getBuildFlags()) + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target and target.IsValid(), "Target is valid") + + breakpoint = target.BreakpointCreateByName("main") + self.assertTrue( + breakpoint and breakpoint.IsValid(), + "Breakpoint is valid") + + # Run the program. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + + # check the setting value + self.expect( + "settings show target.process.memory-cache-line-size", + patterns=[" = 2048"]) + + # Run to completion. + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/android/platform/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/android/platform/main.cpp new file mode 100644 index 00000000000..e8f3fa65eb0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/android/platform/main.cpp @@ -0,0 +1,12 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main () +{ + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py new file mode 100644 index 00000000000..6f95cd7959e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py @@ -0,0 +1,69 @@ +"""Test the integrity of the lldb public api directory containing SB*.h headers. + +There should be nothing unwanted there and a simpe main.cpp which includes SB*.h +should compile and link with the LLDB framework.""" + +from __future__ import print_function + + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SBDirCheckerCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + TestBase.setUp(self) + self.source = 'main.cpp' + self.generateSource(self.source) + + @skipIfNoSBHeaders + def test_sb_api_directory(self): + """Test the SB API directory and make sure there's no unwanted stuff.""" + + # Only proceed if this is an Apple OS, "x86_64", and local platform. + if not (self.platformIsDarwin() and self.getArchitecture() == "x86_64"): + self.skipTest("This test is only for LLDB.framework built 64-bit") + if self.getArchitecture() == "i386": + self.skipTest( + "LLDB is 64-bit and cannot be linked to 32-bit test program.") + + exe_name = self.getBuildArtifact("a.out") + self.buildDriver(self.source, exe_name) + self.sanity_check_executable(exe_name) + + def sanity_check_executable(self, exe_name): + """Sanity check executable compiled from the auto-generated program.""" + exe_name = self.getBuildArtifact("a.out") + exe = self.getBuildArtifact(exe_name) + self.runCmd("file %s" % exe, CURRENT_EXECUTABLE_SET) + + # This test uses a generated source file, so it's in the build directory. + self.line_to_break = line_number( + self.getBuildArtifact(self.source), '// Set breakpoint here.') + + env_cmd = "settings set target.env-vars %s=%s" % ( + self.dylibPath, self.getLLDBLibraryEnvVal()) + if self.TraceOn(): + print("Set environment to: ", env_cmd) + self.runCmd(env_cmd) + self.addTearDownHook( + lambda: self.dbg.HandleCommand( + "settings remove target.env-vars %s" % + self.dylibPath)) + + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line_to_break, num_expected_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=['stopped', + 'stop reason = breakpoint']) + + self.runCmd('frame variable') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/main.cpp.template b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/main.cpp.template new file mode 100644 index 00000000000..7fced85cd3a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/check_public_api_headers/main.cpp.template @@ -0,0 +1,23 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +%include_SB_APIs% + +using namespace lldb; +int +main(int argc, char const *argv[]) +{ + SBDebugger::Initialize(); + SBDebugger dbg = SBDebugger::Create(); + + printf("Hello SBDebugger %llu\n", dbg.GetID()); // Set breakpoint here. + + SBDebugger::Terminate(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/command-return-object/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/command-return-object/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/command-return-object/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/command-return-object/TestSBCommandReturnObject.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/command-return-object/TestSBCommandReturnObject.py new file mode 100644 index 00000000000..c7aa2eced83 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/command-return-object/TestSBCommandReturnObject.py @@ -0,0 +1,34 @@ +"""Test the lldb public C++ api for returning SBCommandReturnObject.""" + +from __future__ import print_function + + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestSBCommandReturnObject(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipIfNoSBHeaders + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr43570") + def test_sb_command_return_object(self): + env = {self.dylibPath: self.getLLDBLibraryEnvVal()} + + self.driver_exe = self.getBuildArtifact("command-return-object") + self.buildDriver('main.cpp', self.driver_exe) + self.addTearDownHook(lambda: os.remove(self.driver_exe)) + self.signBinary(self.driver_exe) + + if self.TraceOn(): + print("Running test %s" % self.driver_exe) + check_call([self.driver_exe, self.driver_exe], env=env) + else: + with open(os.devnull, 'w') as fnull: + check_call([self.driver_exe, self.driver_exe], + env=env, stdout=fnull, stderr=fnull) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/command-return-object/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/command-return-object/main.cpp new file mode 100644 index 00000000000..c1d4d246a43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/command-return-object/main.cpp @@ -0,0 +1,33 @@ +#include "lldb/API/SBCommandInterpreter.h" +#include "lldb/API/SBCommandReturnObject.h" +#include "lldb/API/SBDebugger.h" + +using namespace lldb; + +static SBCommandReturnObject subcommand(SBDebugger &dbg, const char *cmd) { + SBCommandReturnObject Result; + dbg.GetCommandInterpreter().HandleCommand(cmd, Result); + return Result; +} + +class CommandCrasher : public SBCommandPluginInterface { +public: + bool DoExecute(SBDebugger dbg, char **command, + SBCommandReturnObject &result) { + // Test assignment from a different SBCommandReturnObject instance. + result = subcommand(dbg, "help"); + // Test also whether self-assignment is handled correctly. + result = result; + return result.Succeeded(); + } +}; + +int main() { + SBDebugger::Initialize(); + SBDebugger dbg = SBDebugger::Create(false /*source_init_files*/); + SBCommandInterpreter interp = dbg.GetCommandInterpreter(); + static CommandCrasher crasher; + interp.AddCommand("crasher", &crasher, nullptr /*help*/); + SBCommandReturnObject Result; + dbg.GetCommandInterpreter().HandleCommand("crasher", Result); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/listeners/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/listeners/Makefile new file mode 100644 index 00000000000..692ba173228 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/listeners/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c + +include Makefile.rules + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/listeners/TestListener.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/listeners/TestListener.py new file mode 100644 index 00000000000..480041b3e1f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/listeners/TestListener.py @@ -0,0 +1,63 @@ +""" +Test that we can listen to modules loaded events. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +import six + + +class ListenToModuleLoadedEvents (TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_receiving_breakpoint_added(self): + """Test that we get breakpoint added events, waiting on event classes on the debugger""" + self.build() + + my_listener = lldb.SBListener("test_listener") + + my_listener.StartListeningForEventClass( + self.dbg, + lldb.SBTarget.GetBroadcasterClassName(), + lldb.SBTarget.eBroadcastBitBreakpointChanged) + + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + + bkpt = target.BreakpointCreateByName("main") + + event = lldb.SBEvent() + my_listener.WaitForEvent(1, event) + + self.assertTrue(event.IsValid(), "Got a valid event.") + self.assertTrue( + lldb.SBBreakpoint.EventIsBreakpointEvent(event), + "It is a breakpoint event.") + self.assertTrue(lldb.SBBreakpoint.GetBreakpointEventTypeFromEvent( + event) == lldb.eBreakpointEventTypeAdded, "It is a breakpoint added event.") + self.assertTrue( + bkpt == lldb.SBBreakpoint.GetBreakpointFromEvent(event), + "It is our breakpoint.") + + # Now make sure if we stop listening for events we don't get them: + + my_listener.StopListeningForEventClass( + self.dbg, + lldb.SBTarget.GetBroadcasterClassName(), + lldb.SBTarget.eBroadcastBitBreakpointChanged) + my_listener.StopListeningForEvents( + target.GetBroadcaster(), + lldb.SBTarget.eBroadcastBitBreakpointChanged) + + bkpt2 = target.BreakpointCreateByName("main") + my_listener.WaitForEvent(1, event) + self.assertTrue( + not event.IsValid(), + "We don't get events we aren't listening to.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/listeners/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/listeners/main.c new file mode 100644 index 00000000000..f930e511915 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/listeners/main.c @@ -0,0 +1,7 @@ +#include <stdio.h> + +int +main() +{ + printf ("Hello there.\n"); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/log/TestAPILog.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/log/TestAPILog.py new file mode 100644 index 00000000000..c0ffa2c6f50 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/log/TestAPILog.py @@ -0,0 +1,51 @@ +""" +Test API logging. +""" + +import re + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class APILogTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test_api_log(self): + """Test API logging""" + logfile = os.path.join(self.getBuildDir(), "api-log.txt") + + def cleanup(): + if os.path.exists(logfile): + os.unlink(logfile) + + self.addTearDownHook(cleanup) + self.expect("log enable lldb api -f {}".format(logfile)) + + self.dbg.SetDefaultArchitecture(None) + self.dbg.GetScriptingLanguage(None) + target = self.dbg.CreateTarget(None) + + print(logfile) + with open(logfile, 'r') as f: + log = f.read() + + # Find the SBDebugger's address. + debugger_addr = re.findall( + r"lldb::SBDebugger::GetScriptingLanguage\([^)]*\) \(0x([0-9a-fA-F]+),", + log) + + # Make sure we've found a match. + self.assertTrue(debugger_addr, log) + + # Make sure the GetScriptingLanguage matches. + self.assertTrue(re.search(r'lldb::SBDebugger::GetScriptingLanguage\([^)]*\) \(0x{}, ""\)'.format( + debugger_addr[0]), log), log) + + # Make sure the address matches. + self.assertTrue(re.search(r'lldb::SBDebugger::CreateTarget\([^)]*\) \(0x{}, ""\)'.format( + debugger_addr[0]), log), log) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/.categories new file mode 100644 index 00000000000..6e70196ccd7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/.categories @@ -0,0 +1 @@ +stresstest diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/Makefile new file mode 100644 index 00000000000..f40386a5227 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/Makefile @@ -0,0 +1,6 @@ +MAKE_DSYM := NO + +ENABLE_THREADS := YES +CXX_SOURCES := multi-process-driver.cpp testprog.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py new file mode 100644 index 00000000000..1447bbdfe42 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py @@ -0,0 +1,43 @@ +"""Test the lldb public C++ api when doing multiple debug sessions simultaneously.""" + +from __future__ import print_function + + +import os + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestMultipleSimultaneousDebuggers(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # This test case fails non-deterministically. + @skipIfNoSBHeaders + @expectedFailureAll(bugnumber="llvm.org/pr20282") + def test_multiple_debuggers(self): + env = {self.dylibPath: self.getLLDBLibraryEnvVal()} + + self.driver_exe = self.getBuildArtifact("multi-process-driver") + self.buildDriver('multi-process-driver.cpp', self.driver_exe) + self.addTearDownHook(lambda: os.remove(self.driver_exe)) + self.signBinary(self.driver_exe) + + self.inferior_exe = self.getBuildArtifact("testprog") + self.buildDriver('testprog.cpp', self.inferior_exe) + self.addTearDownHook(lambda: os.remove(self.inferior_exe)) + +# check_call will raise a CalledProcessError if multi-process-driver doesn't return +# exit code 0 to indicate success. We can let this exception go - the test harness +# will recognize it as a test failure. + + if self.TraceOn(): + print("Running test %s" % self.driver_exe) + check_call([self.driver_exe, self.inferior_exe], env=env) + else: + with open(os.devnull, 'w') as fnull: + check_call([self.driver_exe, self.inferior_exe], + env=env, stdout=fnull, stderr=fnull) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/multi-process-driver.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/multi-process-driver.cpp new file mode 100644 index 00000000000..15170a3e5eb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/multi-process-driver.cpp @@ -0,0 +1,287 @@ + +// This program creates NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS of pthreads, +// creates an lldb Debugger on each thread, creates targets, inserts two +// breakpoints, runs to the first breakpoint, backtraces, runs to the second +// breakpoint, backtraces, kills the inferior process, closes down the +// debugger. + +// The main thread keeps track of which pthreads have completed and which +// pthreads have completed successfully, and exits when all pthreads have +// completed successfully, or our time limit has been exceeded. + +// This test file helps to uncover race conditions and locking mistakes +// that are hit when lldb is being used to debug multiple processes +// simultaneously. + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "lldb/API/LLDB.h" +#include "lldb/API/SBCommandInterpreter.h" +#include "lldb/API/SBCommandReturnObject.h" +#include "lldb/API/SBDebugger.h" + +#include <chrono> +#include <thread> + +#define NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS 10 + +#define DEBUG 0 + +using namespace lldb; + +bool *completed_threads_array = 0; +bool *successful_threads_array = 0; + +const char *inferior_process_name = "testprog"; + +bool +wait_for_stop_event (SBProcess process, SBListener listener) +{ + bool stopped = false; + while (!stopped) + { + SBEvent event; + bool waitfor_ret = listener.WaitForEvent (2, event); + if (event.GetType() == SBProcess::eBroadcastBitStateChanged) + { + if (process.GetState() == StateType::eStateStopped + || process.GetState() == StateType::eStateCrashed + || process.GetState() == StateType::eStateDetached + || process.GetState() == StateType::eStateExited) + { + stopped = true; + } + } + } + return stopped; +} + +bool +walk_stack_to_main (SBThread thread) +{ + if (thread.IsValid() == 0) + { + return false; + } + + bool found_main = false; + uint32_t curr_frame = 0; + const uint32_t framecount = thread.GetNumFrames(); + while (!found_main && curr_frame < framecount) + { + SBFrame frame = thread.GetFrameAtIndex (curr_frame); + if (strcmp (frame.GetFunctionName(), "main") == 0) + { + found_main = true; + break; + } + curr_frame += 1; + } + return found_main; +} + +void *do_one_debugger (void *in) +{ + uint64_t threadnum = (uint64_t) in; + +#if defined (__APPLE__) + char *threadname; + asprintf (&threadname, "thread #%lld", threadnum); + pthread_setname_np (threadname); + free (threadname); +#endif + +#if DEBUG == 1 + printf ("#%lld: Starting debug session\n", threadnum); +#endif + + SBDebugger debugger = lldb::SBDebugger::Create (false); + if (debugger.IsValid ()) + { + debugger.SetAsync (true); + SBTarget target = debugger.CreateTargetWithFileAndArch(inferior_process_name, "x86_64"); + SBCommandInterpreter command_interp = debugger.GetCommandInterpreter(); + if (target.IsValid()) + { + SBBreakpoint bar_br = target.BreakpointCreateByName ("bar", "testprog"); + if (!bar_br.IsValid()) + { + printf ("#%lld: failed to set breakpoint on bar, exiting.\n", threadnum); + exit (1); + } + SBBreakpoint foo_br = target.BreakpointCreateByName ("foo", "testprog"); + if (!foo_br.IsValid()) + { + printf ("#%lld: Failed to set breakpoint on foo()\n", threadnum); + } + + SBLaunchInfo launch_info (NULL); + SBError error; + SBProcess process = target.Launch (launch_info, error); + if (process.IsValid()) + { + SBListener listener = debugger.GetListener(); + SBBroadcaster broadcaster = process.GetBroadcaster(); + uint32_t rc = broadcaster.AddListener (listener, SBProcess::eBroadcastBitStateChanged); + if (rc == 0) + { + printf ("adding listener failed\n"); + exit (1); + } + + wait_for_stop_event (process, listener); + + if (!walk_stack_to_main (process.GetThreadAtIndex(0))) + { + printf ("#%lld: backtrace while @ foo() failed\n", threadnum); + completed_threads_array[threadnum] = true; + return (void *) 1; + } + + if (strcmp (process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetFunctionName(), "foo") != 0) + { +#if DEBUG == 1 + printf ("#%lld: First breakpoint did not stop at foo(), instead stopped at '%s'\n", threadnum, process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetFunctionName()); +#endif + completed_threads_array[threadnum] = true; + return (void*) 1; + } + + process.Continue(); + + wait_for_stop_event (process, listener); + + if (process.GetState() == StateType::eStateExited) + { + printf ("#%lld: Process exited\n", threadnum); + completed_threads_array[threadnum] = true; + return (void *) 1; + } + + + if (!walk_stack_to_main (process.GetThreadAtIndex(0))) + { + printf ("#%lld: backtrace while @ bar() failed\n", threadnum); + completed_threads_array[threadnum] = true; + return (void *) 1; + } + + if (strcmp (process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetFunctionName(), "bar") != 0) + { + printf ("#%lld: First breakpoint did not stop at bar()\n", threadnum); + completed_threads_array[threadnum] = true; + return (void*) 1; + } + + process.Kill(); + + wait_for_stop_event (process, listener); + + SBDebugger::Destroy(debugger); + +#if DEBUG == 1 + printf ("#%lld: All good!\n", threadnum); +#endif + successful_threads_array[threadnum] = true; + completed_threads_array[threadnum] = true; + return (void*) 0; + } + else + { + printf("#%lld: process failed to launch\n", threadnum); + successful_threads_array[threadnum] = false; + completed_threads_array[threadnum] = true; + return (void*) 0; + } + } + else + { + printf ("#%lld: did not get valid target\n", threadnum); + successful_threads_array[threadnum] = false; + completed_threads_array[threadnum] = true; + return (void*) 0; + } + } + else + { + printf ("#%lld: did not get debugger\n", threadnum); + successful_threads_array[threadnum] = false; + completed_threads_array[threadnum] = true; + return (void*) 0; + } + completed_threads_array[threadnum] = true; + return (void*) 1; +} + +int main (int argc, char **argv) +{ +#if !defined(_MSC_VER) + signal(SIGPIPE, SIG_IGN); +#endif + + SBDebugger::Initialize(); + + completed_threads_array = (bool *) malloc (sizeof (bool) * NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS); + memset (completed_threads_array, 0, sizeof (bool) * NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS); + successful_threads_array = (bool *) malloc (sizeof (bool) * NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS); + memset (successful_threads_array, 0, sizeof (bool) * NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS); + + if (argc > 1 && argv[1] != NULL) + { + inferior_process_name = argv[1]; + } + + std::thread threads[NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS]; + for (uint64_t i = 0; i< NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS; i++) + { + threads[i] = std::move(std::thread(do_one_debugger, (void*)i)); + } + + + int max_time_to_wait = 20; // 20 iterations, or 60 seconds + int iter = 0; + while (1) + { + std::this_thread::sleep_for(std::chrono::seconds(3)); + bool all_done = true; + int successful_threads = 0; + int total_completed_threads = 0; + for (uint64_t i = 0; i < NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS; i++) + { + if (successful_threads_array[i] == true) + successful_threads++; + if (completed_threads_array[i] == true) + total_completed_threads++; + if (completed_threads_array[i] == false) + { + all_done = false; + } + } + if (all_done) + { +#if DEBUG == 1 + printf ("All threads completed.\n"); + printf ("%d threads completed successfully out of %d\n", successful_threads, NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS); +#endif + SBDebugger::Terminate(); + exit(0); + } + else + { +#if DEBUG == 1 + printf ("%d threads completed so far (%d successfully), out of %d\n", total_completed_threads, successful_threads, NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS); +#endif + } + if (iter++ == max_time_to_wait) + { + printf ("reached maximum timeout but only %d threads have completed so far (%d successfully), out of %d. Exiting.\n", total_completed_threads, successful_threads, NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS); + break; + } + } + + + SBDebugger::Terminate(); + exit (1); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/testprog.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/testprog.cpp new file mode 100644 index 00000000000..c9d1ea14f17 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-debuggers/testprog.cpp @@ -0,0 +1,12 @@ +int bar () +{ + return 5; +} +int foo () +{ + return bar() + 5; +} +int main () +{ + return foo(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-targets/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-targets/Makefile new file mode 100644 index 00000000000..3316b59b623 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-targets/Makefile @@ -0,0 +1,6 @@ +MAKE_DSYM := NO + +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-targets/TestMultipleTargets.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-targets/TestMultipleTargets.py new file mode 100644 index 00000000000..1268ff9306a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-targets/TestMultipleTargets.py @@ -0,0 +1,42 @@ +"""Test the lldb public C++ api when creating multiple targets simultaneously.""" + +from __future__ import print_function + + +import os + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestMultipleTargets(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipIfNoSBHeaders + @skipIfHostIncompatibleWithRemote + @expectedFailureAll( + oslist=["windows", "freebsd"], + bugnumber="llvm.org/pr20282") + def test_multiple_targets(self): + env = {self.dylibPath: self.getLLDBLibraryEnvVal()} + + self.driver_exe = self.getBuildArtifact("multi-target") + self.buildDriver('main.cpp', self.driver_exe) + self.addTearDownHook(lambda: os.remove(self.driver_exe)) + self.signBinary(self.driver_exe) + +# check_call will raise a CalledProcessError if multi-process-driver doesn't return +# exit code 0 to indicate success. We can let this exception go - the test harness +# will recognize it as a test failure. + + if self.TraceOn(): + print("Running test %s" % self.driver_exe) + check_call([self.driver_exe, self.driver_exe], env=env) + else: + with open(os.devnull, 'w') as fnull: + check_call([self.driver_exe, self.driver_exe], + env=env, stdout=fnull, stderr=fnull) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-targets/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-targets/main.cpp new file mode 100644 index 00000000000..35fb4e0d613 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multiple-targets/main.cpp @@ -0,0 +1,31 @@ +#include <thread> + +#include "lldb/API/LLDB.h" +#include "lldb/API/SBDebugger.h" +#include "lldb/API/SBTarget.h" + +using namespace lldb; +int main (int argc, char **argv) +{ + // We are expecting the program path and a path to an executable to load + if (argc != 2) + return 1; + const char *program_file = argv[1]; + SBDebugger::Initialize(); + SBDebugger debugger = SBDebugger::Create(false); + auto lambda = [&](){ + SBError error; + SBTarget target = debugger.CreateTarget(program_file, nullptr, nullptr, + false, error); + }; + + // Create 3 targets at the same time and make sure we don't crash. + std::thread thread1(lambda); + std::thread thread2(lambda); + std::thread thread3(lambda); + thread1.join(); + thread2.join(); + thread3.join(); + SBDebugger::Terminate(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/Makefile new file mode 100644 index 00000000000..81767219067 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/Makefile @@ -0,0 +1,7 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp + +include Makefile.rules + +clean:: + rm -rf $(wildcard *.o *.d *.dSYM) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py new file mode 100644 index 00000000000..436f645e652 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py @@ -0,0 +1,109 @@ +"""Test the lldb public C++ api breakpoint callbacks.""" + +from __future__ import print_function + +# __package__ = "lldbsuite.test" + + +import os +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SBBreakpointCallbackCase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + TestBase.setUp(self) + self.generateSource('driver.cpp') + self.generateSource('listener_test.cpp') + self.generateSource('test_breakpoint_callback.cpp') + self.generateSource('test_listener_event_description.cpp') + self.generateSource('test_listener_event_process_state.cpp') + self.generateSource('test_listener_resume.cpp') + + mydir = TestBase.compute_mydir(__file__) + + @skipIfRemote + @skipIfNoSBHeaders + # clang-cl does not support throw or catch (llvm.org/pr24538) + @skipIfWindows + def test_breakpoint_callback(self): + """Test the that SBBreakpoint callback is invoked when a breakpoint is hit. """ + self.build_and_test('driver.cpp test_breakpoint_callback.cpp', + 'test_breakpoint_callback') + + @skipIfRemote + @skipIfNoSBHeaders + # clang-cl does not support throw or catch (llvm.org/pr24538) + @skipIfWindows + @expectedFlakeyFreeBSD + def test_sb_api_listener_event_description(self): + """ Test the description of an SBListener breakpoint event is valid.""" + self.build_and_test( + 'driver.cpp listener_test.cpp test_listener_event_description.cpp', + 'test_listener_event_description') + + @skipIfRemote + @skipIfNoSBHeaders + # clang-cl does not support throw or catch (llvm.org/pr24538) + @skipIfWindows + @expectedFlakeyFreeBSD + def test_sb_api_listener_event_process_state(self): + """ Test that a registered SBListener receives events when a process + changes state. + """ + self.build_and_test( + 'driver.cpp listener_test.cpp test_listener_event_process_state.cpp', + 'test_listener_event_process_state') + + @skipIfRemote + @skipIfNoSBHeaders + # clang-cl does not support throw or catch (llvm.org/pr24538) + @skipIfWindows + @expectedFlakeyFreeBSD + @skipIf(oslist=["linux"]) # flakey + def test_sb_api_listener_resume(self): + """ Test that a process can be resumed from a non-main thread. """ + self.build_and_test( + 'driver.cpp listener_test.cpp test_listener_resume.cpp', + 'test_listener_resume') + + def build_and_test(self, sources, test_name, args=None): + """ Build LLDB test from sources, and run expecting 0 exit code """ + + # These tests link against host lldb API. + # Compiler's target triple must match liblldb triple + # because remote is disabled, we can assume that the os is the same + # still need to check architecture + if self.getLldbArchitecture() != self.getArchitecture(): + self.skipTest( + "This test is only run if the target arch is the same as the lldb binary arch") + + self.inferior = 'inferior_program' + self.buildProgram('inferior.cpp', self.inferior) + self.addTearDownHook(lambda: + os.remove(self.getBuildArtifact(self.inferior))) + + self.buildDriver(sources, test_name) + self.addTearDownHook(lambda: + os.remove(self.getBuildArtifact(test_name))) + + test_exe = self.getBuildArtifact(test_name) + self.signBinary(test_exe) + exe = [test_exe, self.getBuildArtifact(self.inferior)] + + env = {self.dylibPath: self.getLLDBLibraryEnvVal()} + if 'LLDB_DEBUGSERVER_PATH' in os.environ: + env['LLDB_DEBUGSERVER_PATH'] = os.environ['LLDB_DEBUGSERVER_PATH'] + if self.TraceOn(): + print("Running test %s" % " ".join(exe)) + check_call(exe, env=env) + else: + with open(os.devnull, 'w') as fnull: + check_call(exe, env=env, stdout=fnull, stderr=fnull) + + def build_program(self, sources, program): + return self.buildDriver(sources, program) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/common.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/common.h new file mode 100644 index 00000000000..bd40bdd421a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/common.h @@ -0,0 +1,68 @@ +#ifndef LLDB_TEST_API_COMMON_H +#define LLDB_TEST_API_COMMON_H + +#include <condition_variable> +#include <chrono> +#include <exception> +#include <iostream> +#include <mutex> +#include <string> +#include <queue> + +#include <unistd.h> + +/// Simple exception class with a message +struct Exception : public std::exception +{ + std::string s; + Exception(std::string ss) : s(ss) {} + virtual ~Exception() throw () { } + const char* what() const throw() { return s.c_str(); } +}; + +// Synchronized data structure for listener to send events through +template<typename T> +class multithreaded_queue { + std::condition_variable m_condition; + std::mutex m_mutex; + std::queue<T> m_data; + bool m_notified; + +public: + + void push(T e) { + std::lock_guard<std::mutex> lock(m_mutex); + m_data.push(e); + m_notified = true; + m_condition.notify_all(); + } + + T pop(int timeout_seconds, bool &success) { + int count = 0; + while (count < timeout_seconds) { + std::unique_lock<std::mutex> lock(m_mutex); + if (!m_data.empty()) { + m_notified = false; + T ret = m_data.front(); + m_data.pop(); + success = true; + return ret; + } else if (!m_notified) + m_condition.wait_for(lock, std::chrono::seconds(1)); + count ++; + } + success = false; + return T(); + } +}; + +/// Allocates a char buffer with the current working directory +inline char* get_working_dir() { +#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) + return getwd(0); +#else + return get_current_dir_name(); +#endif +} + +#endif // LLDB_TEST_API_COMMON_H diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/driver.cpp.template b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/driver.cpp.template new file mode 100644 index 00000000000..32459425c88 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/driver.cpp.template @@ -0,0 +1,51 @@ + +/// LLDB C API Test Driver + +#include <algorithm> +#include <iostream> +#include <iterator> +#include <string> +#include <vector> +#if !defined(_MSC_VER) + #include <signal.h> +#endif + +%include_SB_APIs% + +#include "common.h" + +using namespace std; +using namespace lldb; + +void test(SBDebugger &dbg, std::vector<string> args); + +int main(int argc, char** argv) { + +// Ignore SIGPIPE. The lldb driver does this as well, +// because we seem to get spurious SIGPIPES on some +// Unixen that take the driver down. +#if !defined(_MSC_VER) + signal(SIGPIPE, SIG_IGN); +#endif + int code = 0; + + SBDebugger::Initialize(); + SBDebugger dbg = SBDebugger::Create(); + dbg.HandleCommand("settings set symbols.enable-external-lookup false"); + dbg.HandleCommand( + "settings set plugin.process.gdb-remote.packet-timeout 60"); + + try { + if (!dbg.IsValid()) + throw Exception("invalid debugger"); + vector<string> args(argv + 1, argv + argc); + + test(dbg, args); + } catch (Exception &e) { + cout << "ERROR: " << e.what() << endl; + code = 1; + } + + SBDebugger::Destroy(dbg); + return code; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/inferior.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/inferior.cpp new file mode 100644 index 00000000000..9dbb289f98b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/inferior.cpp @@ -0,0 +1,17 @@ + +#include <iostream> + +using namespace std; + +int next() { + static int i = 0; + cout << "incrementing " << i << endl; + return ++i; +} + +int main() { + int i = 0; + while (i < 5) + i = next(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/listener_test.cpp.template b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/listener_test.cpp.template new file mode 100644 index 00000000000..e305d1af489 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/listener_test.cpp.template @@ -0,0 +1,74 @@ +// LLDB test snippet that registers a listener with a process that hits +// a breakpoint. + +#include <atomic> +#include <iostream> +#include <string> +#include <thread> +#include <vector> + +%include_SB_APIs% +#include "common.h" + +using namespace lldb; +using namespace std; + +void listener_func(); +void check_listener(SBDebugger &dbg); + +// Listener thread and related variables +atomic<bool> g_done; +SBListener g_listener("test-listener"); +thread g_listener_thread; + +void shutdown_listener() { + g_done.store(true); + if (g_listener_thread.joinable()) + g_listener_thread.join(); +} + +void test(SBDebugger &dbg, std::vector<string> args) { + try { + g_done.store(false); + SBTarget target = dbg.CreateTarget(args.at(0).c_str()); + if (!target.IsValid()) throw Exception("invalid target"); + + SBBreakpoint breakpoint = target.BreakpointCreateByName("next"); + if (!breakpoint.IsValid()) throw Exception("invalid breakpoint"); + + std::unique_ptr<char> working_dir(get_working_dir()); + + SBError error; + SBProcess process = target.Launch(g_listener, + 0, 0, 0, 0, 0, + working_dir.get(), + 0, + false, + error); + if (!error.Success()) + throw Exception("Error launching process."); + + /* FIXME: the approach below deadlocks + SBProcess process = target.LaunchSimple (0, 0, working_dir.get()); + + // get debugger listener (which is attached to process by default) + g_listener = dbg.GetListener(); + */ + + // FIXME: because a listener is attached to the process at launch-time, + // registering the listener below results in two listeners being attached, + // which is not supported by LLDB. + // register listener + // process.GetBroadcaster().AddListener(g_listener, + // SBProcess::eBroadcastBitStateChanged); + + // start listener thread + g_listener_thread = thread(listener_func); + check_listener(dbg); + + } catch (Exception &e) { + shutdown_listener(); + throw e; + } + shutdown_listener(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_breakpoint_callback.cpp.template b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_breakpoint_callback.cpp.template new file mode 100644 index 00000000000..4133025aa49 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_breakpoint_callback.cpp.template @@ -0,0 +1,49 @@ + +// LLDB C++ API Test: verify that the function registered with +// SBBreakpoint.SetCallback() is invoked when a breakpoint is hit. + +#include <mutex> +#include <iostream> +#include <vector> +#include <string> + +%include_SB_APIs% + +#include "common.h" + +using namespace std; +using namespace lldb; + +mutex g_mutex; +condition_variable g_condition; +int g_breakpoint_hit_count = 0; + +bool BPCallback (void *baton, + SBProcess &process, + SBThread &thread, + SBBreakpointLocation &location) { + lock_guard<mutex> lock(g_mutex); + g_breakpoint_hit_count += 1; + g_condition.notify_all(); + return true; +} + +void test(SBDebugger &dbg, vector<string> args) { + dbg.SetAsync(false); + SBTarget target = dbg.CreateTarget(args.at(0).c_str()); + if (!target.IsValid()) throw Exception("invalid target"); + + SBBreakpoint breakpoint = target.BreakpointCreateByName("next"); + if (!breakpoint.IsValid()) throw Exception("invalid breakpoint"); + breakpoint.SetCallback(BPCallback, 0); + + std::unique_ptr<char> working_dir(get_working_dir()); + SBProcess process = target.LaunchSimple (0, 0, working_dir.get()); + + { + unique_lock<mutex> lock(g_mutex); + g_condition.wait_for(lock, chrono::seconds(5)); + if (g_breakpoint_hit_count != 1) + throw Exception("Breakpoint hit count expected to be 1"); + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_description.cpp.template b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_description.cpp.template new file mode 100644 index 00000000000..63e3f3631e5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_description.cpp.template @@ -0,0 +1,97 @@ + +// LLDB C++ API Test: verify the event description that is received by an +// SBListener object registered with a process with a breakpoint. + +#include <atomic> +#include <array> +#include <iostream> +#include <string> +#include <thread> + +%include_SB_APIs% + +#include "common.h" + +using namespace lldb; +using namespace std; + +// listener thread control +extern atomic<bool> g_done; +extern SBListener g_listener; + +multithreaded_queue<string> g_event_descriptions; +string g_error_desc; + +void listener_func() { + while (!g_done) { + SBEvent event; + bool got_event = g_listener.WaitForEvent(1, event); + + if (got_event) { + if (!event.IsValid()) + throw Exception("event is not valid in listener thread"); + + SBStream description; + event.GetDescription(description); + string str(description.GetData()); + g_event_descriptions.push(str); + } + } +} + +bool check_state(string &state, string &desc, bool got_description) +{ + g_error_desc.clear(); + + if(!got_description) + { + g_error_desc.append("Did not get expected event description"); + return false; + } + + if (desc.find("state-changed") == desc.npos) + g_error_desc.append("Event description incorrect: missing 'state-changed' "); + + if (desc.find("pid = ") == desc.npos) + g_error_desc.append("Event description incorrect: missing process pid "); + + string state_search_str = "state = " + state; + if (desc.find(state_search_str) == desc.npos) + { + string errString = ("Event description incorrect: expected state " + + state + + " but desc was " + + desc); + g_error_desc.append(errString); + } + + if (g_error_desc.length() > 0) + return false; + + cout << "check_state: " << state << " OK\n"; + return true; +} + +void check_listener(SBDebugger &dbg) +{ + bool got_description; + string state; + + // check for "launching" state, this may or may not be present + string desc = g_event_descriptions.pop(5, got_description); + state = "launching"; + if (check_state(state, desc, got_description)) + { + // found a 'launching' state, pop next one from queue + desc = g_event_descriptions.pop(5, got_description); + } + + state = "running"; + if( !check_state(state, desc, got_description) ) + throw Exception(g_error_desc); + + desc = g_event_descriptions.pop(5, got_description); + state = "stopped"; + if( !check_state(state, desc, got_description) ) + throw Exception(g_error_desc); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_process_state.cpp.template b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_process_state.cpp.template new file mode 100644 index 00000000000..2926ece4d8d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_process_state.cpp.template @@ -0,0 +1,63 @@ + +// LLDB C++ API Test: verify the event description as obtained by calling +// SBEvent::GetCStringFromEvent that is received by an +// SBListener object registered with a process with a breakpoint. + +#include <atomic> +#include <iostream> +#include <string> +#include <thread> + +%include_SB_APIs% + +#include "common.h" + +using namespace lldb; +using namespace std; + +// listener thread control +extern atomic<bool> g_done; + +multithreaded_queue<string> g_frame_functions; + +extern SBListener g_listener; + +void listener_func() { + while (!g_done) { + SBEvent event; + bool got_event = g_listener.WaitForEvent(1, event); + if (got_event) { + if (!event.IsValid()) + throw Exception("event is not valid in listener thread"); + // send process description + SBProcess process = SBProcess::GetProcessFromEvent(event); + if (!process.IsValid()) + throw Exception("process is not valid"); + if (SBProcess::GetStateFromEvent(event) != lldb::eStateStopped || SBProcess::GetRestartedFromEvent(event)) + continue; // Only interested in "stopped" events. + + SBStream description; + + for (int i = 0; i < process.GetNumThreads(); ++i) { + // send each thread description + SBThread thread = process.GetThreadAtIndex(i); + // send each frame function name + uint32_t num_frames = thread.GetNumFrames(); + for(int j = 0; j < num_frames; ++j) { + const char* function_name = thread.GetFrameAtIndex(j).GetSymbol().GetName(); + if (function_name) + g_frame_functions.push(string(function_name)); + } + } + } + } +} + +void check_listener(SBDebugger &dbg) { + // check thread description + bool got_description = false; + string func_name = g_frame_functions.pop(5, got_description); + + if(got_description == false) + throw Exception("Expected at least one frame function"); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_listener_resume.cpp.template b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_listener_resume.cpp.template new file mode 100644 index 00000000000..4adc9b33887 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/api/multithreaded/test_listener_resume.cpp.template @@ -0,0 +1,53 @@ + +// LLDB C++ API Test: verify the event description as obtained by calling +// SBEvent::GetCStringFromEvent that is received by an +// SBListener object registered with a process with a breakpoint. + +#include <atomic> +#include <iostream> +#include <string> +#include <thread> + +%include_SB_APIs% + +#include "common.h" + +using namespace lldb; +using namespace std; + +// listener thread control +extern atomic<bool> g_done; + +// used by listener thread to communicate a successful process continue command +// back to the checking thread. + +multithreaded_queue<bool> g_process_started; + +extern SBListener g_listener; + +void listener_func() { + while (!g_done) { + SBEvent event; + bool got_event = g_listener.WaitForEvent(1, event); + if (got_event) { + if (!event.IsValid()) + throw Exception("event is not valid in listener thread"); + + SBProcess process = SBProcess::GetProcessFromEvent(event); + if (process.GetState() == eStateStopped) { + SBError error = process.Continue(); + if (!error.Success()) + throw Exception(string("Cannot continue process from listener thread: ") + + error.GetCString()); + g_process_started.push(true); + } + } + } +} + +void check_listener(SBDebugger &dbg) { + bool got_message = false; + while (!got_message) + g_process_started.pop(5, got_message); + g_done = true; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-it/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-it/Makefile new file mode 100644 index 00000000000..f8f686a3455 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-it/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -mthumb + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-it/TestBreakpointIt.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-it/TestBreakpointIt.py new file mode 100644 index 00000000000..35ea3ae222a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-it/TestBreakpointIt.py @@ -0,0 +1,44 @@ +""" +Test that breakpoints in an IT instruction don't fire if their condition is +false. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestBreakpointIt(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipIf(archs=no_match(["arm"])) + @skipIf(archs=["arm64", "arm64e", "arm64_32"]) + def test_false(self): + self.build() + exe = self.getBuildArtifact("a.out") + + self.runCmd("target create %s" % exe) + lldbutil.run_break_set_by_symbol(self, "bkpt_false", + extra_options="--skip-prologue 0") + + self.runCmd("run") + self.assertEqual(self.process().GetState(), lldb.eStateExited, + "Breakpoint does not get hit") + + @skipIf(archs=no_match(["arm"])) + @skipIf(archs=["arm64", "arm64e", "arm64_32"]) + def test_true(self): + self.build() + exe = self.getBuildArtifact("a.out") + + self.runCmd("target create %s" % exe) + bpid = lldbutil.run_break_set_by_symbol(self, "bkpt_true", + extra_options="--skip-prologue 0") + + self.runCmd("run") + self.assertIsNotNone(lldbutil.get_one_thread_stopped_at_breakpoint_id( + self.process(), bpid)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-it/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-it/main.c new file mode 100644 index 00000000000..35d57bb1b84 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-it/main.c @@ -0,0 +1,14 @@ +int main() { + int value; + asm ( + "cmp %1, %2\n\t" + "ite ne\n\t" + ".thumb_func\n\t" + "bkpt_true:\n\t" + "movne %0, %1\n\t" + ".thumb_func\n\t" + "bkpt_false:\n\t" + "moveq %0, %2\n\t" + : "=r" (value) : "r"(42), "r"(47)); + return value; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-thumb-codesection/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-thumb-codesection/Makefile new file mode 100644 index 00000000000..3f8e5597f7d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-thumb-codesection/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -mthumb + +include Makefile.rules
\ No newline at end of file diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-thumb-codesection/TestBreakpointThumbCodesection.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-thumb-codesection/TestBreakpointThumbCodesection.py new file mode 100644 index 00000000000..0726369b676 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-thumb-codesection/TestBreakpointThumbCodesection.py @@ -0,0 +1,33 @@ +""" +Test that breakpoints correctly work in an thumb function in an arbitrary +named codesection. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestBreakpointThumbCodesection(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(archs=no_match(["arm"])) + @skipIfDarwinEmbedded # codegen on darwin always defaults to thumb for armv7/armv7k targets + def test_breakpoint(self): + self.build() + exe = self.getBuildArtifact("a.out") + line = line_number('main.c', '// Set break point at this line.') + + self.runCmd("target create %s" % exe) + bpid = lldbutil.run_break_set_by_file_and_line(self, "main.c", line) + + self.runCmd("run") + + self.assertIsNotNone(lldbutil.get_one_thread_stopped_at_breakpoint_id( + self.process(), bpid), "Process is not stopped at breakpoint") + + self.process().Continue() + self.assertEqual(self.process().GetState(), lldb.eStateExited, PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-thumb-codesection/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-thumb-codesection/main.c new file mode 100644 index 00000000000..38ea7be6bfc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/breakpoint-thumb-codesection/main.c @@ -0,0 +1,8 @@ +__attribute__((section("__codesection"))) +int f(int a) { + return a + 1; // Set break point at this line. +} + +int main() { + return f(10); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/TestEmulations.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/TestEmulations.py new file mode 100644 index 00000000000..9613edcf3fd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/TestEmulations.py @@ -0,0 +1,54 @@ +""" +Test some ARM instruction emulation. +""" + +from __future__ import print_function + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ARMEmulationTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_thumb_emulations(self): + test_dir = os.path.join(self.getSourceDir(), "new-test-files") + files = os.listdir(test_dir) + thumb_files = list() + for f in files: + if '-thumb.dat' in f: + thumb_files.append(f) + + for f in thumb_files: + test_file = os.path.join(test_dir, f) + self.run_a_single_test(test_file) + + @no_debug_info_test + def test_arm_emulations(self): + test_dir = os.path.join(self.getSourceDir(), "new-test-files") + files = os.listdir(test_dir) + arm_files = list() + for f in files: + if '-arm.dat' in f: + arm_files.append(f) + + for f in arm_files: + test_file = os.path.join(test_dir, f) + self.run_a_single_test(test_file) + + def run_a_single_test(self, filename): + insn = lldb.SBInstruction() + stream = lldb.SBStream() + success = insn.TestEmulation(stream, filename) + output = stream.GetData() + if self.TraceOn(): + print('\nRunning test ' + os.path.basename(filename)) + print(output) + + self.assertTrue(success, 'Emulation test succeeded.') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-1-arm.dat new file mode 100644 index 00000000000..64b2506f9d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r0, r0, r15" +triple=arm-apple-ios +opcode=0xe080000f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00003000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-1-thumb.dat new file mode 100644 index 00000000000..daa32d25a41 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r0, r13, #0" +triple=thumb-apple-ios +opcode=0xa800 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-10-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-10-thumb.dat new file mode 100644 index 00000000000..bb3d760219b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-10-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add sp, r13" +triple=thumb-apple-ios +opcode=0x44ed +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x5fbffca0 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-11-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-11-thumb.dat new file mode 100644 index 00000000000..e26f2218cbc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-11-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add sp, r15" +triple=thumb-apple-ios +opcode=0x44fd +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fe02e50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-12-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-12-thumb.dat new file mode 100644 index 00000000000..a7f7344e7d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-12-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add sp, r8" +triple=thumb-apple-ios +opcode=0x44c5 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-2-arm.dat new file mode 100644 index 00000000000..cf6e0a9779a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-2-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r0, r13, #0" +triple=arm-apple-ios +opcode=0xe28d0000 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-2-thumb.dat new file mode 100644 index 00000000000..9a178a0a159 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-2-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r0, sp, r0" +triple=thumb-apple-ios +opcode=0x4468 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-3-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-3-arm.dat new file mode 100644 index 00000000000..9fc44b79395 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-3-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r0, r1, r0, lsl #2" +triple=arm-apple-ios +opcode=0xe0810100 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000001 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-3-thumb.dat new file mode 100644 index 00000000000..c8f96ec09d3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-3-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add.w r10, r13, #31" +triple=thumb-apple-ios +opcode=0xf10d0a1f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x2fdffe5f +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-4-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-4-arm.dat new file mode 100644 index 00000000000..12b40ed76fc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-4-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r0, r2, r7, lsl r1" +triple=arm-apple-ios +opcode=0xe0820117 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x5fbffc82 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-4-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-4-thumb.dat new file mode 100644 index 00000000000..922b8ecdba5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-4-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r3, r13, #16" +triple=thumb-apple-ios +opcode=0xab04 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x2fdffe58 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-5-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-5-arm.dat new file mode 100644 index 00000000000..dfb6a87f014 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-5-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r10, r13, #31" +triple=arm-apple-ios +opcode=0xe28da01f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x2fdffe6f +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-5-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-5-thumb.dat new file mode 100644 index 00000000000..16ff517436b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-5-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r3, sp, r3" +triple=thumb-apple-ios +opcode=0x446b +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x2fdffe53 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-6-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-6-arm.dat new file mode 100644 index 00000000000..8a87eff5f00 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-6-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r12, r13, #24" +triple=arm-apple-ios +opcode=0xe28dc018 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x2fdffe68 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-6-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-6-thumb.dat new file mode 100644 index 00000000000..e8abd6950f2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-6-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r5, r13, #32" +triple=thumb-apple-ios +opcode=0xad08 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x2fdffe68 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-7-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-7-arm.dat new file mode 100644 index 00000000000..312514246e3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-7-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add r6, sp, #8" +triple=arm-apple-ios +opcode=0xe28d6008 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x2fdffe68 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-7-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-7-thumb.dat new file mode 100644 index 00000000000..506071309d7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-7-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add sp, #16" +triple=thumb-apple-ios +opcode=0xb004 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe68 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-8-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-8-arm.dat new file mode 100644 index 00000000000..44a400f5287 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-8-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add sp, r8" +triple=arm-apple-ios +opcode=0xe08dd008 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe68 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-8-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-8-thumb.dat new file mode 100644 index 00000000000..8bc6c789a51 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-8-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add sp, #4" +triple=thumb-apple-ios +opcode=0xb001 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe5c +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-9-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-9-thumb.dat new file mode 100644 index 00000000000..832af4cf0b4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-add-9-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="add sp, r10" +triple=thumb-apple-ios +opcode=0x44d5 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe5a +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-bic-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-bic-1-arm.dat new file mode 100644 index 00000000000..c1cd4f15ab3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-bic-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="bic r4, r9" +triple=arm-apple-ios +opcode=0xe1c44009 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-bic-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-bic-1-thumb.dat new file mode 100644 index 00000000000..c6242265018 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-bic-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="bics r4, r6" +triple=thumb-apple-ios +opcode=0x43b4 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000000 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-1-arm.dat new file mode 100644 index 00000000000..e1922d9edb9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-1-arm.dat @@ -0,0 +1,119 @@ +InstructionEmulationState={ +assembly_string="ldmia r0!, {r1, r3}" +triple=arm-apple-ios +opcode=0xe8b0000a +before_state={ +memory={ +address=0x2fdffe50 +data_encoding=uint32_t +data=[ + 0x0 + 0x2e7c +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x00000000 +r2=0x2fdffe70 +r3=0x00002e7c +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-1-thumb.dat new file mode 100644 index 00000000000..60a805e09d8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-1-thumb.dat @@ -0,0 +1,119 @@ +InstructionEmulationState={ +assembly_string="ldmia r0!, {r1, r3}" +triple=thumb-apple-ios +opcode=0xc80a +before_state={ +memory={ +address=0x2fdffe40 +data_encoding=uint32_t +data=[ +0x0 +0x2f84 +] +} +registers={ +r0=0x2fdffe40 +r1=0x2fdffe50 +r2=0x2fdffe60 +r3=0x2fdffe70 +r4=0x2fdffe80 +r5=0x2fdffe90 +r6=0x2fdffea0 +r7=0x2fdffe40 +r8=0x2fdffec0 +r9=0x2fdffed0 +r10=0x2fdffee0 +r11=0x2fdffef0 +r12=0x2fdfff00 +r13=0x2fdffe40 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe48 +r1=0x00000000 +r2=0x2fdffe60 +r3=0x00002f84 +r4=0x2fdffe80 +r5=0x2fdffe90 +r6=0x2fdffea0 +r7=0x2fdffe40 +r8=0x2fdffec0 +r9=0x2fdffed0 +r10=0x2fdffee0 +r11=0x2fdffef0 +r12=0x2fdfff00 +r13=0x2fdffe40 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-2-arm.dat new file mode 100644 index 00000000000..99401bbd2e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-2-arm.dat @@ -0,0 +1,123 @@ +InstructionEmulationState={ +assembly_string="ldmia r0!, {r2, r4, r6, r8, r10, r12}" +triple=arm-apple-ios +opcode=0xe8b01554 +before_state={ +memory={ +address=0x2fdffe20 +data_encoding=uint32_t +data=[ +0x0 +0x2e7c +0x1 +0x2fdffe84 +0x0 +0x0 +] +} +registers={ +r0=0x2fdffe20 +r1=0x2fdffe30 +r2=0x2fdffe40 +r3=0x0000001f +r4=0x2fdffe60 +r5=0x2fdffe70 +r6=0x2fdffe80 +r7=0x2fdffe20 +r8=0x2fdffea0 +r9=0x2fdffeb0 +r10=0x2fdffec0 +r11=0x2fdffed0 +r12=0x2fdffee0 +r13=0x2fdffe20 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe38 +r1=0x2fdffe30 +r2=0x00000000 +r3=0x0000001f +r4=0x00002e7c +r5=0x2fdffe70 +r6=0x00000001 +r7=0x2fdffe20 +r8=0x2fdffe84 +r9=0x2fdffeb0 +r10=0x00000000 +r11=0x2fdffed0 +r12=0x00000000 +r13=0x2fdffe20 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-2-thumb.dat new file mode 100644 index 00000000000..39ecf947c6d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-2-thumb.dat @@ -0,0 +1,123 @@ +InstructionEmulationState={ +assembly_string="ldmia.w r0!,{r2,r4,r6,r8,r10,r12}" +triple=thumb-apple-ios +opcode=0xe8b01554 +before_state={ +memory={ +address=0x2fdffe50 +data_encoding=uint32_t +data=[ +0x0 +0x2f80 +0x1 +0x2fdffeac +0x0 +0x0 +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe68 +r1=0x2fdffe60 +r2=0x00000000 +r3=0x2fdffe80 +r4=0x00002f80 +r5=0x2fdffea0 +r6=0x00000001 +r7=0x2fdffe50 +r8=0x2fdffeac +r9=0x2fdffee0 +r10=0x00000000 +r11=0x2fdfff00 +r12=0x00000000 +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-3-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-3-arm.dat new file mode 100644 index 00000000000..427d7b27485 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-3-arm.dat @@ -0,0 +1,119 @@ +InstructionEmulationState={ +assembly_string="ldmia r14!, {r1, r3}" +triple=arm-apple-ios +opcode=0xe8be000a +before_state={ +memory={ +address=0x2e7c +data_encoding=uint32_t +data=[ +0xe59fc00c +0xe08fc00c +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0xe59fc00c +r2=0x2fdffe70 +r3=0xe08fc00c +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e84 +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-3-thumb.dat new file mode 100644 index 00000000000..9738073c038 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldmia-3-thumb.dat @@ -0,0 +1,119 @@ +InstructionEmulationState={ +assembly_string="ldmia.w r14!, {r1, r3}" +triple=thumb-apple-ios +opcode=0xe8be000a +before_state={ +memory={ +address=0x2f80 +data_encoding=uint32_t +data=[ +0xe59fc00c +0xe08fc00c +] +} +registers={ +r0=0x2fdffe78 +r1=0x2fdffe88 +r2=0x2fdffe98 +r3=0x2fdffea8 +r4=0x2fdffeb8 +r5=0x2fdffec8 +r6=0x2fdffed8 +r7=0x2fdffe78 +r8=0x2fdffef8 +r9=0x2fdfff08 +r10=0x2fdfff18 +r11=0x2fdfff28 +r12=0x2fdfff38 +r13=0x2fdffe78 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe78 +r1=0xe59fc00c +r2=0x2fdffe98 +r3=0xe08fc00c +r4=0x2fdffeb8 +r5=0x2fdffec8 +r6=0x2fdffed8 +r7=0x2fdffe78 +r8=0x2fdffef8 +r9=0x2fdfff08 +r10=0x2fdfff18 +r11=0x2fdfff28 +r12=0x2fdfff38 +r13=0x2fdffe78 +r14=0x00002f88 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-1-arm.dat new file mode 100644 index 00000000000..307402fd2f5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-1-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r0, [pc, #+24]" +triple=arm-apple-ios +opcode=0xe59f0018 +before_state={ +memory={ +address=0x3018 +data_encoding=uint32_t +data=[ +0x3030 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00003030 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-1-thumb.dat new file mode 100644 index 00000000000..471669b0cb6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-1-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r0, [pc, #12]" +triple=thumb-apple-ios +opcode=0x4803 +before_state={ +memory={ +address=0x300c +data_encoding=uint32_t +data=[ +0x3024 +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00003024 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-10-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-10-thumb.dat new file mode 100644 index 00000000000..bc7693c9a68 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-10-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr.w r10,[ pc, #4]" +triple=thumb-apple-ios +opcode=0xf8dfa004 +before_state={ +memory={ +address=0x3000 +data_encoding=uint32_t +data=[ +0x2fe01000 +] +} +registers={ +r0=0x2fdffe48 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe48 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fe01000 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-11-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-11-thumb.dat new file mode 100644 index 00000000000..b5bf18127cd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-11-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr.w r8, [pc , #0]" +triple=thumb-apple-ios +opcode=0xf8df8000 +before_state={ +memory={ +address=0x2ffc +data_encoding=uint32_t +data=[ +0xa0e1defe +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0xa0e1defe +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-12-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-12-thumb.dat new file mode 100644 index 00000000000..5c3a5485f0b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-12-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr.w r9, [pc, #-4]" +triple=thumb-apple-ios +opcode=0xf85f9004 +before_state={ +memory={ +address=0x2fec +data_encoding=uint32_t +data=[ +0x9004f85f +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x9004f85f +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-2-arm.dat new file mode 100644 index 00000000000..068297e3edc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-2-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r0, [pc, #256]" +triple=arm-apple-ios +opcode=0xe59f0100 +before_state={ +memory={ +address=0x3100 +data_encoding=uint32_t +data=[ +0x0 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-2-thumb.dat new file mode 100644 index 00000000000..27727831d6d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-2-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r0, [pc, #+24]" +triple=thumb-apple-ios +opcode=0x4806 +before_state={ +memory={ +address=0x3018 +data_encoding=uint32_t +data=[ +0x3030 +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00003030 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-3-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-3-arm.dat new file mode 100644 index 00000000000..f0d6d8aaba6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-3-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r0, [r13, #+24]" +triple=arm-apple-ios +opcode=0xe59d0018 +before_state={ +memory={ +address=0x2fdffe70 +data_encoding=uint32_t +data=[ +0x2fdffe80 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe80 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-3-thumb.dat new file mode 100644 index 00000000000..012e1c53e66 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-3-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r0, [pc, #256]" +triple=thumb-apple-ios +opcode=0x4840 +before_state={ +memory={ +address=0x3100 +data_encoding=uint32_t +data=[ +0x0 +] +} +registers={ +r0=0x2fdffe48 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-4-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-4-arm.dat new file mode 100644 index 00000000000..e2d2aa6aa88 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-4-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r1, [r5, #16]" +triple=arm-apple-ios +opcode=0xe5951010 +before_state={ +memory={ +address=0x2fdffeb8 +data_encoding=uint32_t +data=[ +0x7365742d +] +} +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x7365742d +r2=0x2fdffe78 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-4-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-4-thumb.dat new file mode 100644 index 00000000000..3eb6f167b48 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-4-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r0, [r13, #+24]" +triple=thumb-apple-ios +opcode=0x9806 +before_state={ +memory={ +address=0x2fdffe60 +data_encoding=uint32_t +data=[ +0x2fdffe70 +] +} +registers={ +r0=0x2fdffe48 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe70 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-5-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-5-arm.dat new file mode 100644 index 00000000000..45210d9600d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-5-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r2, [r0]" +triple=arm-apple-ios +opcode=0xe5902000 +before_state={ +memory={ +address=0x2fdffe60 +data_encoding=uint32_t +data=[ +0x0 +] +} +registers={ +r0=0x2fdffe60 +r1=0x2fdffe70 +r2=0x2fdffe80 +r3=0x0000001f +r4=0x2fdffea0 +r5=0x2fdffeb0 +r6=0x2fdffec0 +r7=0x2fdffe60 +r8=0x2fdffee0 +r9=0x2fdffef0 +r10=0x2fdfff00 +r11=0x2fdfff10 +r12=0x2fdfff20 +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe60 +r1=0x2fdffe70 +r2=0x00000000 +r3=0x0000001f +r4=0x2fdffea0 +r5=0x2fdffeb0 +r6=0x2fdffec0 +r7=0x2fdffe60 +r8=0x2fdffee0 +r9=0x2fdffef0 +r10=0x2fdfff00 +r11=0x2fdfff10 +r12=0x2fdfff20 +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-5-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-5-thumb.dat new file mode 100644 index 00000000000..45289e7e899 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-5-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r1, [pc, #0]" +triple=thumb-apple-ios +opcode=0x4900 +before_state={ +memory={ +address=0x3000 +data_encoding=uint32_t +data=[ +0x2fe01000 +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fe01000 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-6-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-6-arm.dat new file mode 100644 index 00000000000..0f379fd4980 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-6-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r2, [r6], +r8, lsl #2" +triple=arm-apple-ios +opcode=0xe6962108 +before_state={ +memory={ +address=0x2fdffea8 +data_encoding=uint32_t +data=[ +0x7365742d +] +} +registers={ +r0=0x2fdffe48 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x0000001f +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe48 +r1=0x2fdffe58 +r2=0x7365742d +r3=0x0000001f +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0xef5ff9c8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-6-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-6-thumb.dat new file mode 100644 index 00000000000..5b3c119e743 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-6-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r1, [r5, #16]" +triple=thumb-apple-ios +opcode=0x6929 +before_state={ +memory={ +address=0x2fdffeb0 +data_encoding=uint32_t +data=[ +0x65742d62 +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x65742d62 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-7-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-7-arm.dat new file mode 100644 index 00000000000..ff425ef5284 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-7-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r2, [sp, #24]" +triple=arm-apple-ios +opcode=0xe59d2018 +before_state={ +memory={ +address=0x2fdffe70 +data_encoding=uint32_t +data=[ +0x0 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000000 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-7-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-7-thumb.dat new file mode 100644 index 00000000000..db8d58796ca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-7-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r2, [r0]" +triple=thumb-apple-ios +opcode=0x6802 +before_state={ +memory={ +address=0x2fdffe58 +data_encoding=uint32_t +data=[ +0x0 +] +} +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x2fdffe88 +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x00000000 +r3=0x2fdffe88 +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-8-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-8-arm.dat new file mode 100644 index 00000000000..c11dfc133e5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-8-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r3, [r11, #-8]" +triple=arm-apple-ios +opcode=0xe51b3008 +before_state={ +memory={ +address=0x2fdfff00 +data_encoding=uint32_t +data=[ +0x63387830 +] +} +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x63387830 +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-8-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-8-thumb.dat new file mode 100644 index 00000000000..01d7013ceaa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-8-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr r2, [sp, #24]" +triple=thumb-apple-ios +opcode=0x9a06 +before_state={ +memory={ +address=0x2fdffe68 +data_encoding=uint32_t +data=[ +0x2fdffe78 +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe78 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-9-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-9-thumb.dat new file mode 100644 index 00000000000..cc3c4db2f4d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldr-9-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldr.w r3, [r11, #8]" +triple=thumb-apple-ios +opcode=0xf8db3008 +before_state={ +memory={ +address=0x2fdfff08 +data_encoding=uint32_t +data=[ +0x62343134 +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x62343134 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrd-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrd-1-arm.dat new file mode 100644 index 00000000000..970f8aa7c0a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrd-1-arm.dat @@ -0,0 +1,119 @@ +InstructionEmulationState={ +assembly_string="ldrd r0, r1, [r12, #+4]" +triple=arm-apple-ios +opcode=0xe1cc00d4 +before_state={ +memory={ +address=0x2fdfff14 +data_encoding=uint32_t +data=[ +0x30313038 +0x31623039 +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x30313038 +r1=0x31623039 +r2=0x2fdffe70 +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrd-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrd-1-thumb.dat new file mode 100644 index 00000000000..7ab41ce35db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrd-1-thumb.dat @@ -0,0 +1,119 @@ +InstructionEmulationState={ +assembly_string="ldrd r0, r1, [r12, #+4]" +triple=thumb-apple-ios +opcode=0xe9dc0101 +before_state={ +memory={ +address=0x2fdfff3c +data_encoding=uint32_t +data=[ +0x0 +0x0 +] +} +registers={ +r0=0x2fdffe78 +r1=0x2fdffe88 +r2=0x2fdffe98 +r3=0x2fdffea8 +r4=0x2fdffeb8 +r5=0x2fdffec8 +r6=0x2fdffed8 +r7=0x2fdffe78 +r8=0x2fdffef8 +r9=0x2fdfff08 +r10=0x2fdfff18 +r11=0x2fdfff28 +r12=0x2fdfff38 +r13=0x2fdffe78 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000000 +r2=0x2fdffe98 +r3=0x2fdffea8 +r4=0x2fdffeb8 +r5=0x2fdffec8 +r6=0x2fdffed8 +r7=0x2fdffe78 +r8=0x2fdffef8 +r9=0x2fdfff08 +r10=0x2fdfff18 +r11=0x2fdfff28 +r12=0x2fdfff38 +r13=0x2fdffe78 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrd-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrd-2-thumb.dat new file mode 100644 index 00000000000..70fe6f5cfff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrd-2-thumb.dat @@ -0,0 +1,119 @@ +InstructionEmulationState={ +assembly_string="ldrd r4, r5, [pc, #-0]" +triple=thumb-apple-ios +opcode=0xe9df4500 +before_state={ +memory={ +address=0x2ffc +data_encoding=uint32_t +data=[ +0xa0e1defe +0x2fe01000 +] +} +registers={ +r0=0x2fdffe78 +r1=0x2fdffe88 +r2=0x2fdffe98 +r3=0x2fdffea8 +r4=0x2fdffeb8 +r5=0x2fdffec8 +r6=0x2fdffed8 +r7=0x2fdffe78 +r8=0x2fdffef8 +r9=0x2fdfff08 +r10=0x2fdfff18 +r11=0x2fdfff28 +r12=0x2fdfff38 +r13=0x2fdffe78 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe78 +r1=0x2fdffe88 +r2=0x2fdffe98 +r3=0x2fdffea8 +r4=0xa0e1defe +r5=0x2fe01000 +r6=0x2fdffed8 +r7=0x2fdffe78 +r8=0x2fdffef8 +r9=0x2fdfff08 +r10=0x2fdfff18 +r11=0x2fdfff28 +r12=0x2fdfff38 +r13=0x2fdffe78 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrh-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrh-1-thumb.dat new file mode 100644 index 00000000000..2a47002fb65 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrh-1-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldrh r0, [r2, #16]" +triple=thumb-apple-ios +opcode=0x8a10 +before_state={ +memory={ +address=0x2fdffe78 +data_encoding=uint32_t +data=[ +0x762f +] +} +registers={ +r0=0x2fdffe48 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x0000762f +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrsh-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrsh-1-arm.dat new file mode 100644 index 00000000000..cecf397f1d4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrsh-1-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldrsh r0, [r2], #+15" +triple=arm-apple-ios +opcode=0xe0d200ff +before_state={ +memory={ +address=0x2fdffe70 +data_encoding=uint32_t +data=[ +0xfffffeeb +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0xfffffeeb +r1=0x2fdffe60 +r2=0x2fdffe7f +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrsh-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrsh-2-arm.dat new file mode 100644 index 00000000000..660b3d3b5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-ldrsh-2-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="ldrsh r14, [r2], #+15" +triple=arm-apple-ios +opcode=0xe0d2e0ff +before_state={ +memory={ +address=0x2fdffe70 +data_encoding=uint32_t +data=[ +0xfffffeec +] +} +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe7f +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0xfffffeec +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-1-arm.dat new file mode 100644 index 00000000000..232bc967fed --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r12, #256" +triple=arm-apple-ios +opcode=0xe3a0cc01 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x00000100 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-1-thumb.dat new file mode 100644 index 00000000000..569510dbd3b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov ip, pc" +triple=thumb-apple-ios +opcode=0x46fc +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x00003000 +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-10-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-10-thumb.dat new file mode 100644 index 00000000000..6bf9b0d7ef7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-10-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r0, r15" +triple=thumb-apple-ios +opcode=0x4678 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00003000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-11-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-11-thumb.dat new file mode 100644 index 00000000000..82043ef335b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-11-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r0, r7" +triple=thumb-apple-ios +opcode=0x4638 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-12-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-12-thumb.dat new file mode 100644 index 00000000000..1fce18af917 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-12-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov.w r12, #256" +triple=thumb-apple-ios +opcode=0xf44f7c80 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x00000100 +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-13-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-13-thumb.dat new file mode 100644 index 00000000000..d1c1a4428c9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-13-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r12, r13" +triple=thumb-apple-ios +opcode=0x46ec +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x2fdffe50 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-14-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-14-thumb.dat new file mode 100644 index 00000000000..dfd89c265fb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-14-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r14, r2" +triple=thumb-apple-ios +opcode=0x4696 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00000002 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-15-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-15-thumb.dat new file mode 100644 index 00000000000..0ff8e5d7dc5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-15-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r1, r14" +triple=thumb-apple-ios +opcode=0x4671 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00002f84 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-16-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-16-thumb.dat new file mode 100644 index 00000000000..1baf42dfc56 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-16-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r2, ip" +triple=thumb-apple-ios +opcode=0x4662 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x0000000c +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-17-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-17-thumb.dat new file mode 100644 index 00000000000..70cee03fb54 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-17-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r2, r13" +triple=thumb-apple-ios +opcode=0x466a +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x2fdffe50 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-18-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-18-thumb.dat new file mode 100644 index 00000000000..1893e188b0d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-18-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r2, r9" +triple=thumb-apple-ios +opcode=0x464a +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000009 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-19-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-19-thumb.dat new file mode 100644 index 00000000000..238e16b4aa4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-19-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r3, r12" +triple=thumb-apple-ios +opcode=0x4663 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000000c +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-2-arm.dat new file mode 100644 index 00000000000..6d6c0cbf80c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-2-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r12, r13" +triple=arm-apple-ios +opcode=0xe1a0c00d +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x2fdffe58 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-2-thumb.dat new file mode 100644 index 00000000000..ad6854427fb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-2-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov ip, r8" +triple=thumb-apple-ios +opcode=0x46c4 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x00000008 +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-20-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-20-thumb.dat new file mode 100644 index 00000000000..15ecd2ebfa0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-20-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r3, r13" +triple=thumb-apple-ios +opcode=0x466b +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x2fdffe50 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-21-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-21-thumb.dat new file mode 100644 index 00000000000..6a38f1671b7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-21-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r3, sp" +triple=thumb-apple-ios +opcode=0x466b +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x2fdffe58 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-22-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-22-thumb.dat new file mode 100644 index 00000000000..242b5682419 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-22-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r4, r11" +triple=thumb-apple-ios +opcode=0x465c +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x0000000b +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-23-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-23-thumb.dat new file mode 100644 index 00000000000..7f57440a842 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-23-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r5, r10" +triple=thumb-apple-ios +opcode=0x4655 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x0000000a +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-24-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-24-thumb.dat new file mode 100644 index 00000000000..9a1756e8473 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-24-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r6, r9" +triple=thumb-apple-ios +opcode=0x464e +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000009 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-25-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-25-thumb.dat new file mode 100644 index 00000000000..c2fd6a73964 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-25-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r7, lr" +triple=thumb-apple-ios +opcode=0x4677 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x00002f84 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-26-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-26-thumb.dat new file mode 100644 index 00000000000..2cc155d8071 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-26-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r7, r8" +triple=thumb-apple-ios +opcode=0x4647 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x00000008 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-27-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-27-thumb.dat new file mode 100644 index 00000000000..0b35377b08e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-27-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r9, pc" +triple=thumb-apple-ios +opcode=0x46f9 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00003000 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-28-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-28-thumb.dat new file mode 100644 index 00000000000..f7d7778a251 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-28-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov sp, ip" +triple=thumb-apple-ios +opcode=0x46e5 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x0000000c +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-29-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-29-thumb.dat new file mode 100644 index 00000000000..5e9098f99d2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-29-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov sp, pc" +triple=thumb-apple-ios +opcode=0x46fd +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x00003000 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-3-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-3-arm.dat new file mode 100644 index 00000000000..1fe7155bd3a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-3-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r14, r2" +triple=arm-apple-ios +opcode=0xe1a0e002 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00000002 +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-3-thumb.dat new file mode 100644 index 00000000000..8ce129682bf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-3-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov ip, sp" +triple=thumb-apple-ios +opcode=0x46ec +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x2fdffe58 +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-30-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-30-thumb.dat new file mode 100644 index 00000000000..a0dddad6b5a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-30-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov sp, r7" +triple=thumb-apple-ios +opcode=0x46bd +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-31-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-31-thumb.dat new file mode 100644 index 00000000000..20d8dc7c06f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-31-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="movs r3, #1" +triple=thumb-apple-ios +opcode=0x2301 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000001 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x20000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-4-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-4-arm.dat new file mode 100644 index 00000000000..8ef83b26805 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-4-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r2, r9" +triple=arm-apple-ios +opcode=0xe1a02009 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000009 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-4-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-4-thumb.dat new file mode 100644 index 00000000000..f854ba26641 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-4-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov lr, pc" +triple=thumb-apple-ios +opcode=0x46fe +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00003000 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-5-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-5-arm.dat new file mode 100644 index 00000000000..ee85779083f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-5-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r3, #2147483648" +triple=arm-apple-ios +opcode=0xe3a03102 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x80000000 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-5-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-5-thumb.dat new file mode 100644 index 00000000000..d6140bdb92d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-5-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov lr, r2" +triple=thumb-apple-ios +opcode=0x4696 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00000002 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-6-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-6-arm.dat new file mode 100644 index 00000000000..863a6d3e9bd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-6-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov r3, r13" +triple=arm-apple-ios +opcode=0xe1a0300d +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x2fdffe60 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-6-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-6-thumb.dat new file mode 100644 index 00000000000..fac96bf5a5a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-6-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov pc, ip" +triple=thumb-apple-ios +opcode=0x46e7 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x0000000c +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-7-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-7-thumb.dat new file mode 100644 index 00000000000..c537d30cb24 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-7-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov pc, lr" +triple=thumb-apple-ios +opcode=0x46f7 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002f84 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-8-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-8-thumb.dat new file mode 100644 index 00000000000..b724c79a0d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-8-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov pc, r4" +triple=thumb-apple-ios +opcode=0x46a7 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00000004 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-9-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-9-thumb.dat new file mode 100644 index 00000000000..ccf7ea6c342 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mov-9-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mov pc, sp" +triple=thumb-apple-ios +opcode=0x46ef +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x2fdffe58 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-moveq-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-moveq-1-arm.dat new file mode 100644 index 00000000000..f46b1bfd6e8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-moveq-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="moveq r3, #1" +triple=arm-apple-ios +opcode=0x3a03001 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000001 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-movs-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-movs-1-arm.dat new file mode 100644 index 00000000000..38292508d43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-movs-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="movs r12, r13" +triple=arm-apple-ios +opcode=0xe1b0c00d +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x2fdffe58 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x20000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-1-arm.dat new file mode 100644 index 00000000000..024dd9fa4bc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mvn r14, #1" +triple=arm-apple-ios +opcode=0xe3e0e001 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0xfffffffe +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-1-thumb.dat new file mode 100644 index 00000000000..c5c385c8522 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mvn r0, #1" +triple=thumb-apple-ios +opcode=0xf06f0001 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe98 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe98 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0xfffffffe +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe98 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe98 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-2-arm.dat new file mode 100644 index 00000000000..10df542fcad --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-2-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mvn r0, #1" +triple=arm-apple-ios +opcode=0xe3e00001 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe68 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe68 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0xfffffffe +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe68 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe68 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-2-thumb.dat new file mode 100644 index 00000000000..3c2f6f4da27 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-2-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mvn r0, #31" +triple=thumb-apple-ios +opcode=0xf06f001f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe90 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe90 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0xffffffe0 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe90 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe90 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-3-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-3-arm.dat new file mode 100644 index 00000000000..742708978b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-3-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mvn r0, #31" +triple=arm-apple-ios +opcode=0xe3e0001f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0xffffffe0 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-3-thumb.dat new file mode 100644 index 00000000000..ff4ca7331a9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-3-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mvn r14, #1" +triple=thumb-apple-ios +opcode=0xf06f0e01 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe90 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe90 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe90 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe90 +r14=0xfffffffe +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-4-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-4-arm.dat new file mode 100644 index 00000000000..4efc18cc5f2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-4-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mvn r3, r8" +triple=arm-apple-ios +opcode=0xe1e03008 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0xfffffff7 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-4-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-4-thumb.dat new file mode 100644 index 00000000000..f8b1569e906 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-mvn-4-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="mvns r3, r8" +triple=thumb-apple-ios +opcode=0xea7f0308 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe90 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe90 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0xfffffff7 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe90 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe90 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0xa0000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-1-arm.dat new file mode 100644 index 00000000000..07163f80aeb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-1-arm.dat @@ -0,0 +1,121 @@ +InstructionEmulationState={ +assembly_string="pop {r3, r4, r8, r10}" +triple=arm-apple-ios +opcode=0xe8bd0518 +before_state={ +memory={ +address=0x2fdffe50 +data_encoding=uint32_t +data=[ +0x0 +0x2e7c +0x1 +0x2fdffeac +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000000 +r4=0x00002e7c +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000001 +r9=0x00000009 +r10=0x2fdffeac +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-1-thumb.dat new file mode 100644 index 00000000000..fad6765be9a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-1-thumb.dat @@ -0,0 +1,121 @@ +InstructionEmulationState={ +assembly_string="pop.w {r3, r4, r8, r10}" +triple=thumb-apple-ios +opcode=0xe8bd0518 +before_state={ +memory={ +address=0x2fdffe38 +data_encoding=uint32_t +data=[ +0x0 +0x2f80 +0x1000 +0x1 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000000 +r4=0x00002f80 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00001000 +r9=0x00000009 +r10=0x00000001 +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-2-arm.dat new file mode 100644 index 00000000000..4b6ae43ca28 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-2-arm.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="pop {r9}" +triple=arm-apple-ios +opcode=0xe8bd0200 +before_state={ +memory={ +address=0x2fdffe70 +data_encoding=uint32_t +data=[ +0x0 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe70 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe70 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe70 +r8=0x00000008 +r9=0x00000000 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe74 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-2-thumb.dat new file mode 100644 index 00000000000..9f3efe57e9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-2-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="pop {r3}" +triple=thumb-apple-ios +opcode=0xbc08 +before_state={ +memory={ +address=0x2fdffe60 +data_encoding=uint32_t +data=[ +0x0 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000000 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe64 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-3-thumb.dat new file mode 100644 index 00000000000..a2adc418c4a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-pop-3-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="pop {r6}" +triple=thumb-apple-ios +opcode=0xbc40 +before_state={ +memory={ +address=0x2fdffe60 +data_encoding=uint32_t +data=[ +0x0 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000000 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe64 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-1-arm.dat new file mode 100644 index 00000000000..b2f6e0965ab --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="push {r0, r1, r2, r3, r7, r14}" +triple=arm-apple-ios +opcode=0xe92d408f +before_state={ +registers={ +r0=0x2fdffe30 +r1=0x2fdffe40 +r2=0x2fdffe50 +r3=0x0000001f +r4=0x2fdffe70 +r5=0x2fdffe80 +r6=0x2fdffe90 +r7=0x2fdffe30 +r8=0x2fdffeb0 +r9=0x2fdffec0 +r10=0x2fdffed0 +r11=0x2fdffee0 +r12=0x2fdffef0 +r13=0x2fdffe30 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe30 +r1=0x2fdffe40 +r2=0x2fdffe50 +r3=0x0000001f +r4=0x2fdffe70 +r5=0x2fdffe80 +r6=0x2fdffe90 +r7=0x2fdffe30 +r8=0x2fdffeb0 +r9=0x2fdffec0 +r10=0x2fdffed0 +r11=0x2fdffee0 +r12=0x2fdffef0 +r13=0x2fdffe18 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-1-thumb.dat new file mode 100644 index 00000000000..6f5b29ed199 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="push {r0, r1, r2, r3, r7, r14}" +triple=thumb-apple-ios +opcode=0xb58f +before_state={ +registers={ +r0=0x2fdffe28 +r1=0x2fdffe38 +r2=0x2fdffe48 +r3=0x2fdffe58 +r4=0x2fdffe68 +r5=0x2fdffe78 +r6=0x2fdffe88 +r7=0x2fdffe28 +r8=0x2fdffea8 +r9=0x2fdffeb8 +r10=0x2fdffec8 +r11=0x2fdffed8 +r12=0x2fdffee8 +r13=0x2fdffe28 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe28 +r1=0x2fdffe38 +r2=0x2fdffe48 +r3=0x2fdffe58 +r4=0x2fdffe68 +r5=0x2fdffe78 +r6=0x2fdffe88 +r7=0x2fdffe28 +r8=0x2fdffea8 +r9=0x2fdffeb8 +r10=0x2fdffec8 +r11=0x2fdffed8 +r12=0x2fdffee8 +r13=0x2fdffe10 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-2-arm.dat new file mode 100644 index 00000000000..6f1f4389e80 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-2-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="push {r6}" +triple=arm-apple-ios +opcode=0xe92d0040 +before_state={ +registers={ +r0=0x2fdffe68 +r1=0x2fdffe78 +r2=0x2fdffe88 +r3=0x0000001f +r4=0x2fdffea8 +r5=0x2fdffeb8 +r6=0x2fdffec8 +r7=0x2fdffe68 +r8=0x2fdffee8 +r9=0x2fdffef8 +r10=0x2fdfff08 +r11=0x2fdfff18 +r12=0x2fdfff28 +r13=0x2fdffe68 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe68 +r1=0x2fdffe78 +r2=0x2fdffe88 +r3=0x0000001f +r4=0x2fdffea8 +r5=0x2fdffeb8 +r6=0x2fdffec8 +r7=0x2fdffe68 +r8=0x2fdffee8 +r9=0x2fdffef8 +r10=0x2fdfff08 +r11=0x2fdfff18 +r12=0x2fdfff28 +r13=0x2fdffe64 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-2-thumb.dat new file mode 100644 index 00000000000..23e4df446bf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-2-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="push {r6}" +triple=thumb-apple-ios +opcode=0xb440 +before_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x2fdffe88 +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x2fdffe88 +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe54 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-3-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-3-arm.dat new file mode 100644 index 00000000000..06847a5ff3b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-3-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="push {r7, r14}" +triple=arm-apple-ios +opcode=0xe92d4080 +before_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-3-thumb.dat new file mode 100644 index 00000000000..e3330f537cb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-push-3-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="push {r7, r14}" +triple=thumb-apple-ios +opcode=0xb580 +before_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-1-arm.dat new file mode 100644 index 00000000000..70a5be3cb69 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="str r0, [r13]" +triple=arm-apple-ios +opcode=0xe58d0000 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-1-thumb.dat new file mode 100644 index 00000000000..3559652ce6c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="str r0, [r13]" +triple=thumb-apple-ios +opcode=0x9000 +before_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-2-arm.dat new file mode 100644 index 00000000000..3d77724b4f9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-2-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="str r1, [r0, #+4]" +triple=arm-apple-ios +opcode=0xe5801004 +before_state={ +registers={ +r0=0x2fdffe60 +r1=0x2fdffe70 +r2=0x2fdffe80 +r3=0x0000001f +r4=0x2fdffea0 +r5=0x2fdffeb0 +r6=0x2fdffec0 +r7=0x2fdffe60 +r8=0x2fdffee0 +r9=0x2fdffef0 +r10=0x2fdfff00 +r11=0x2fdfff10 +r12=0x2fdfff20 +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe60 +r1=0x2fdffe70 +r2=0x2fdffe80 +r3=0x0000001f +r4=0x2fdffea0 +r5=0x2fdffeb0 +r6=0x2fdffec0 +r7=0x2fdffe60 +r8=0x2fdffee0 +r9=0x2fdffef0 +r10=0x2fdfff00 +r11=0x2fdfff10 +r12=0x2fdfff20 +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-2-thumb.dat new file mode 100644 index 00000000000..73e8cd3e548 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-2-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="str r0, [sp, #0]" +triple=thumb-apple-ios +opcode=0x9000 +before_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-3-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-3-arm.dat new file mode 100644 index 00000000000..97c90a0050c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-3-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="str r2, [r0]" +triple=arm-apple-ios +opcode=0xe5802000 +before_state={ +registers={ +r0=0x2fdffe60 +r1=0x2fdffe70 +r2=0x2fdffe80 +r3=0x0000001f +r4=0x2fdffea0 +r5=0x2fdffeb0 +r6=0x2fdffec0 +r7=0x2fdffe60 +r8=0x2fdffee0 +r9=0x2fdffef0 +r10=0x2fdfff00 +r11=0x2fdfff10 +r12=0x2fdfff20 +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe60 +r1=0x2fdffe70 +r2=0x2fdffe80 +r3=0x0000001f +r4=0x2fdffea0 +r5=0x2fdffeb0 +r6=0x2fdffec0 +r7=0x2fdffe60 +r8=0x2fdffee0 +r9=0x2fdffef0 +r10=0x2fdfff00 +r11=0x2fdfff10 +r12=0x2fdfff20 +r13=0x2fdffe60 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-3-thumb.dat new file mode 100644 index 00000000000..8e891c04287 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-3-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="str r1, [sp, #32]" +triple=thumb-apple-ios +opcode=0x9108 +before_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x2fdffe80 +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-4-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-4-arm.dat new file mode 100644 index 00000000000..ed3b54eaf38 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-4-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="str r2, [r13, #+4]" +triple=arm-apple-ios +opcode=0xe58d2004 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-4-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-4-thumb.dat new file mode 100644 index 00000000000..ec9e2dc1e54 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-4-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="str.w r7, [r13, #-12]!" +triple=thumb-apple-ios +opcode=0xf84d7d0c +before_state={ +registers={ +r0=0x2fdffe48 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe48 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe48 +r1=0x2fdffe58 +r2=0x2fdffe68 +r3=0x2fdffe78 +r4=0x2fdffe88 +r5=0x2fdffe98 +r6=0x2fdffea8 +r7=0x2fdffe48 +r8=0x2fdffec8 +r9=0x2fdffed8 +r10=0x2fdffee8 +r11=0x2fdffef8 +r12=0x2fdfff08 +r13=0x2fdffe3c +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-5-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-5-arm.dat new file mode 100644 index 00000000000..98b8dfb16b3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-str-5-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="str r7, [r13, #-12]!" +triple=arm-apple-ios +opcode=0xe52d700c +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe4c +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strb-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strb-1-arm.dat new file mode 100644 index 00000000000..2f7320d007a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strb-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="strb r0, [r2], #+15" +triple=arm-apple-ios +opcode=0xe4c2000f +before_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe87 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strb-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strb-2-arm.dat new file mode 100644 index 00000000000..495c8e720a1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strb-2-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="strb r3, [r0, #+8]" +triple=arm-apple-ios +opcode=0xe5c03008 +before_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strbt-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strbt-1-arm.dat new file mode 100644 index 00000000000..494c49af952 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strbt-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="strbt r14, [r2], #+15" +triple=arm-apple-ios +opcode=0xe4e2e00f +before_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe70 +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x2fdffe60 +r2=0x2fdffe7f +r3=0x0000001f +r4=0x2fdffe90 +r5=0x2fdffea0 +r6=0x2fdffeb0 +r7=0x2fdffe50 +r8=0x2fdffed0 +r9=0x2fdffee0 +r10=0x2fdffef0 +r11=0x2fdfff00 +r12=0x2fdfff10 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strd-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strd-1-thumb.dat new file mode 100644 index 00000000000..4876f8741b0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strd-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="strd r10, r11, [r6, #+28]" +triple=thumb-apple-ios +opcode=0xe9c6ab07 +before_state={ +registers={ +r0=0x2fdffe70 +r1=0x2fdffe80 +r2=0x2fdffe90 +r3=0x2fdffea0 +r4=0x2fdffeb0 +r5=0x2fdffec0 +r6=0x2fdffed0 +r7=0x2fdffe70 +r8=0x2fdffef0 +r9=0x2fdfff00 +r10=0x2fdfff10 +r11=0x2fdfff20 +r12=0x2fdfff30 +r13=0x2fdffe70 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe70 +r1=0x2fdffe80 +r2=0x2fdffe90 +r3=0x2fdffea0 +r4=0x2fdffeb0 +r5=0x2fdffec0 +r6=0x2fdffed0 +r7=0x2fdffe70 +r8=0x2fdffef0 +r9=0x2fdfff00 +r10=0x2fdfff10 +r11=0x2fdfff20 +r12=0x2fdfff30 +r13=0x2fdffe70 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strt-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strt-1-arm.dat new file mode 100644 index 00000000000..9fc311565ea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-strt-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="strt r0, [r2], #+15" +triple=arm-apple-ios +opcode=0xe4a2000f +before_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe78 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe58 +r1=0x2fdffe68 +r2=0x2fdffe87 +r3=0x0000001f +r4=0x2fdffe98 +r5=0x2fdffea8 +r6=0x2fdffeb8 +r7=0x2fdffe58 +r8=0x2fdffed8 +r9=0x2fdffee8 +r10=0x2fdffef8 +r11=0x2fdfff08 +r12=0x2fdfff18 +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-1-arm.dat new file mode 100644 index 00000000000..98c435d616a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub r0, sp, r8" +triple=arm-apple-ios +opcode=0xe04d0008 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x2fdffe50 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-1-thumb.dat new file mode 100644 index 00000000000..482480d0cd4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub.w r10, sp, #16" +triple=thumb-apple-ios +opcode=0xf1ad0a10 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x2fdffe30 +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-10-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-10-arm.dat new file mode 100644 index 00000000000..9f07a947f7d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-10-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub r7, r12, #8" +triple=arm-apple-ios +opcode=0xe24c7008 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x00000004 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-2-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-2-arm.dat new file mode 100644 index 00000000000..9a67268196e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-2-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub r10, r12, #31" +triple=arm-apple-ios +opcode=0xe24ca01f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0xffffffed +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-2-thumb.dat new file mode 100644 index 00000000000..11d213803e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-2-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub.w r10, sp, #31" +triple=thumb-apple-ios +opcode=0xf1ad0a1f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x2fdffe21 +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-3-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-3-arm.dat new file mode 100644 index 00000000000..4dfe680ce47 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-3-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub r12, r13, #12" +triple=arm-apple-ios +opcode=0xe24dc00c +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x2fdffe44 +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-3-thumb.dat new file mode 100644 index 00000000000..a017f528430 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-3-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub.w r12, sp, #31" +triple=thumb-apple-ios +opcode=0xf1ad0c1f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe40 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x2fdffe21 +r13=0x2fdffe40 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-4-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-4-arm.dat new file mode 100644 index 00000000000..50d13c99475 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-4-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub r13, r13, #24" +triple=arm-apple-ios +opcode=0xe24dd018 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-4-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-4-thumb.dat new file mode 100644 index 00000000000..214808d6a42 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-4-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub.w r1, sp, r3, lsl #2" +triple=thumb-apple-ios +opcode=0xebad0183 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe30 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe30 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x2fdffe24 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe30 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe30 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-5-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-5-arm.dat new file mode 100644 index 00000000000..58de27b5d4e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-5-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub r13, r13, #4" +triple=arm-apple-ios +opcode=0xe24dd004 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe54 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-5-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-5-thumb.dat new file mode 100644 index 00000000000..12688286685 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-5-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub.w r7, sp, #1" +triple=thumb-apple-ios +opcode=0xf1ad0701 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe4f +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-6-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-6-arm.dat new file mode 100644 index 00000000000..be6891307db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-6-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub r1, r13, #4" +triple=arm-apple-ios +opcode=0xe24d1004 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x2fdffe54 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-6-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-6-thumb.dat new file mode 100644 index 00000000000..d48c42eb8d8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-6-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub.w sp, sp, #4" +triple=thumb-apple-ios +opcode=0xf1ad0d04 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe4c +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-8-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-8-arm.dat new file mode 100644 index 00000000000..21b17dfbcd8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-8-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub r2, r2, r3" +triple=arm-apple-ios +opcode=0xe0422003 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0xffffffe3 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-9-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-9-arm.dat new file mode 100644 index 00000000000..06888ad3a4b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-sub-9-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="sub r4, r12, r7" +triple=arm-apple-ios +opcode=0xe04c4007 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0xd02001b4 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe58 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe58 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-1-arm.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-1-arm.dat new file mode 100644 index 00000000000..856a55749b1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-1-arm.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs r10, r13, #31" +triple=arm-apple-ios +opcode=0xe25da01f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ff8 +cpsr=0x60000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x0000001f +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x2fdffe31 +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002e7c +r15=0x00002ffc +cpsr=0x20000010 +s0=0x00000000 +s1=0x00000001 +s2=0x00000002 +s3=0x00000003 +s4=0x00000004 +s5=0x00000005 +s6=0x00000006 +s7=0x00000007 +s8=0x00000008 +s9=0x00000009 +s10=0x0000000a +s11=0x0000000b +s12=0x0000000c +s13=0x0000000d +s14=0x0000000e +s15=0x0000000f +s16=0x00000010 +s17=0x00000011 +s18=0x00000012 +s19=0x00000013 +s20=0x00000014 +s21=0x00000015 +s22=0x00000016 +s23=0x00000017 +s24=0x00000018 +s25=0x00000019 +s26=0x0000001a +s27=0x0000001b +s28=0x0000001c +s29=0x0000001d +s30=0x0000001e +s31=0x0000001f +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-1-thumb.dat new file mode 100644 index 00000000000..63aa7b8ed13 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs r0, r6, #0" +triple=thumb-apple-ios +opcode=0x1e30 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000006 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x20000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-10-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-10-thumb.dat new file mode 100644 index 00000000000..75938b4e1d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-10-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs.w r1, sp, #4" +triple=thumb-apple-ios +opcode=0xf1bd0104 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x2fdffe44 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x20000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-2-thumb.dat new file mode 100644 index 00000000000..74bddcea97c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-2-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs r0, r7, r5" +triple=thumb-apple-ios +opcode=0x1b78 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x2fdffe43 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x20000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-3-thumb.dat new file mode 100644 index 00000000000..965ebf37017 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-3-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs.w r10, r13, #31" +triple=thumb-apple-ios +opcode=0xf1bd0a1f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00000008 +r9=0x00000009 +r10=0x2fdffe19 +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x20000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-4-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-4-thumb.dat new file mode 100644 index 00000000000..068724170d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-4-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs r1, r3, #4" +triple=thumb-apple-ios +opcode=0x1f19 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0xffffffff +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x80000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-5-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-5-thumb.dat new file mode 100644 index 00000000000..72ed2ef25c0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-5-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs r4, r2, r6" +triple=thumb-apple-ios +opcode=0x1b94 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0xfffffffc +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe48 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe48 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x80000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-6-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-6-thumb.dat new file mode 100644 index 00000000000..67133b2832e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-6-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs r7, r5, #7" +triple=thumb-apple-ios +opcode=0x1fef +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe50 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0xfffffffe +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f84 +r15=0x00002ffe +cpsr=0x80000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-8-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-8-thumb.dat new file mode 100644 index 00000000000..965ebf37017 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-8-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs.w r10, r13, #31" +triple=thumb-apple-ios +opcode=0xf1bd0a1f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00000008 +r9=0x00000009 +r10=0x2fdffe19 +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x20000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-9-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-9-thumb.dat new file mode 100644 index 00000000000..ea159774316 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-subs-9-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="subs.w r10, sp, #31" +triple=thumb-apple-ios +opcode=0xf1bd0a1f +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe38 +r8=0x00000008 +r9=0x00000009 +r10=0x2fdffe19 +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe38 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x20000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpop-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpop-1-thumb.dat new file mode 100644 index 00000000000..22dd9d88b4b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpop-1-thumb.dat @@ -0,0 +1,125 @@ +InstructionEmulationState={ +assembly_string="vpop {d11, d12, d13, d14}" +triple=thumb-apple-ios +opcode=0xecbdbb08 +before_state={ +memory={ +address=0x2fdffe60 +data_encoding=uint32_t +data=[ +0x0 +0x2f80 +0x1000 +0x1 +0x2fdffebc +0x0 +0x0 +0x2fdffe8c +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe80 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00002f80 +s24=0x00001000 +s25=0x00000001 +s26=0x2fdffebc +s27=0x00000000 +s28=0x00000000 +s29=0x2fdffe8c +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpop-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpop-2-thumb.dat new file mode 100644 index 00000000000..e69cd9eef2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpop-2-thumb.dat @@ -0,0 +1,118 @@ +InstructionEmulationState={ +assembly_string="vpop {s0}" +triple=thumb-apple-ios +opcode=0xecbd0a01 +before_state={ +memory={ +address=0x2fdffe98 +data_encoding=uint32_t +data=[ +0x0 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe98 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe98 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe98 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe9c +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpop-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpop-3-thumb.dat new file mode 100644 index 00000000000..375a92eaaab --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpop-3-thumb.dat @@ -0,0 +1,121 @@ +InstructionEmulationState={ +assembly_string="vpop {s11, s12, s13, s14}" +triple=thumb-apple-ios +opcode=0xecfd5a04 +before_state={ +memory={ +address=0x2fdffe60 +data_encoding=uint32_t +data=[ +0x0 +0x2f80 +0x1000 +0x1 +] +} +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe70 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00002f80 +s13=0x00001000 +s14=0x00000001 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpush-1-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpush-1-thumb.dat new file mode 100644 index 00000000000..ac4ef56be66 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpush-1-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="vpush {d11, d12, d13, d14}" +triple=thumb-apple-ios +opcode=0xed2dbb08 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe40 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpush-2-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpush-2-thumb.dat new file mode 100644 index 00000000000..58055d6539c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpush-2-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="vpush {s0}" +triple=thumb-apple-ios +opcode=0xed2d0a01 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe90 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe90 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe90 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe8c +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpush-3-thumb.dat b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpush-3-thumb.dat new file mode 100644 index 00000000000..2658b43bc88 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/arm/emulation/new-test-files/test-vpush-3-thumb.dat @@ -0,0 +1,111 @@ +InstructionEmulationState={ +assembly_string="vpush {s11, s12, s13, s14}" +triple=thumb-apple-ios +opcode=0xed6d5a04 +before_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe60 +r14=0x00002f80 +r15=0x00002ff8 +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +after_state={ +registers={ +r0=0x00000000 +r1=0x00000001 +r2=0x00000002 +r3=0x00000003 +r4=0x00000004 +r5=0x00000005 +r6=0x00000006 +r7=0x2fdffe60 +r8=0x00000008 +r9=0x00000009 +r10=0x0000000a +r11=0x0000000b +r12=0x0000000c +r13=0x2fdffe50 +r14=0x00002f80 +r15=0x00002ffc +cpsr=0x60000030 +s0=0x00000000 +s1=0x00000000 +s2=0x00000000 +s3=0x00000000 +s4=0x00000000 +s5=0x00000000 +s6=0x00000000 +s7=0x00000000 +s8=0x00000000 +s9=0x00000000 +s10=0x00000000 +s11=0x00000000 +s12=0x00000000 +s13=0x00000000 +s14=0x00000000 +s15=0x00000000 +s16=0x00000000 +s17=0x00000000 +s18=0x00000000 +s19=0x00000000 +s20=0x00000000 +s21=0x00000000 +s22=0x00000000 +s23=0x00000000 +s24=0x00000000 +s25=0x00000000 +s26=0x00000000 +s27=0x00000000 +s28=0x00000000 +s29=0x00000000 +s30=0x00000000 +s31=0x00000000 +} +} +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/bench.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/bench.py new file mode 100644 index 00000000000..a9661b6d022 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/bench.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python + +""" +A simple bench runner which delegates to the ./dotest.py test driver to run the +benchmarks defined in the list named 'benches'. + +You need to hand edit 'benches' to modify/change the command lines passed to the +test driver. + +Use the following to get only the benchmark results in your terminal output: + + ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:' +""" + +from __future__ import print_function +from __future__ import absolute_import + +import os +from optparse import OptionParser + +# dotest.py invocation with no '-e exe-path' uses lldb as the inferior program, +# unless there is a mentioning of custom executable program. +benches = [ + # Measure startup delays creating a target, setting a breakpoint, and run + # to breakpoint stop. + './dotest.py -v +b %E %X -n -p TestStartupDelays.py', + + # Measure 'frame variable' response after stopping at a breakpoint. + './dotest.py -v +b %E %X -n -p TestFrameVariableResponse.py', + + # Measure stepping speed after stopping at a breakpoint. + './dotest.py -v +b %E %X -n -p TestSteppingSpeed.py', + + # Measure expression cmd response with a simple custom executable program. + './dotest.py +b -n -p TestExpressionCmd.py', + + # Attach to a spawned process then run disassembly benchmarks. + './dotest.py -v +b -n %E -p TestDoAttachThenDisassembly.py' +] + + +def main(): + """Read the items from 'benches' and run the command line one by one.""" + parser = OptionParser(usage="""\ +%prog [options] +Run the standard benchmarks defined in the list named 'benches'.\ +""") + parser.add_option('-e', '--executable', + type='string', action='store', + dest='exe', + help='The target program launched by lldb.') + parser.add_option('-x', '--breakpoint-spec', + type='string', action='store', + dest='break_spec', + help='The lldb breakpoint spec for the target program.') + + # Parses the options, if any. + opts, args = parser.parse_args() + + print("Starting bench runner....") + + for item in benches: + command = item.replace('%E', + '-e "%s"' % opts.exe if opts.exe else '') + command = command.replace('%X', '-x "%s"' % + opts.break_spec if opts.break_spec else '') + print("Running %s" % (command)) + os.system(command) + + print("Bench runner done.") + +if __name__ == '__main__': + main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/continue/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/continue/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/continue/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py new file mode 100644 index 00000000000..7863481ebe9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py @@ -0,0 +1,72 @@ +""" +Test lldb data formatter subsystem. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbbench import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestBenchmarkContinue(BenchBase): + + mydir = TestBase.compute_mydir(__file__) + + @benchmarks_test + def test_run_command(self): + """Benchmark different ways to continue a process""" + self.build() + self.data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + BenchBase.setUp(self) + + def data_formatter_commands(self): + """Benchmark different ways to continue a process""" + self.runCmd("file "+self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "// break here")) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + runCmd_sw = Stopwatch() + lldbutil_sw = Stopwatch() + + for i in range(0, 15): + runCmd_sw.start() + self.runCmd("continue") + runCmd_sw.stop() + + for i in range(0, 15): + lldbutil_sw.start() + lldbutil.continue_to_breakpoint(self.process(), bkpt) + lldbutil_sw.stop() + + print("runCmd: %s\nlldbutil: %s" % (runCmd_sw, lldbutil_sw)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/continue/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/continue/main.cpp new file mode 100644 index 00000000000..d715a1150d0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/continue/main.cpp @@ -0,0 +1,36 @@ +#include <map> + +#define intint_map std::map<int, int> + +int g_the_foo = 0; + +int thefoo_rw(int arg = 1) +{ + if (arg < 0) + arg = 0; + if (!arg) + arg = 1; + g_the_foo += arg; + return g_the_foo; +} + +int main() +{ + intint_map ii; + + for (int i = 0; i < 15; i++) + { + ii[i] = i + 1; + thefoo_rw(i); // break here + } + + ii.clear(); + + for (int j = 0; j < 15; j++) + { + ii[j] = j + 1; + thefoo_rw(j); // break here + } + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py new file mode 100644 index 00000000000..9e5b0ecc5b3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py @@ -0,0 +1,82 @@ +"""Test lldb's expression evaluations and collect statistics.""" + +from __future__ import print_function + + +import sys +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbbench import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import configuration +from lldbsuite.test import lldbutil + + +class ExpressionEvaluationCase(BenchBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + BenchBase.setUp(self) + self.source = 'main.cpp' + self.line_to_break = line_number( + self.source, '// Set breakpoint here.') + self.count = 25 + + @benchmarks_test + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + def test_expr_cmd(self): + """Test lldb's expression commands and collect statistics.""" + self.build() + self.exe_name = 'a.out' + + print() + self.run_lldb_repeated_exprs(self.exe_name, self.count) + print("lldb expr cmd benchmark:", self.stopwatch) + + def run_lldb_repeated_exprs(self, exe_name, count): + import pexpect + exe = self.getBuildArtifact(exe_name) + + # Set self.child_prompt, which is "(lldb) ". + self.child_prompt = '(lldb) ' + prompt = self.child_prompt + + # Reset the stopwatch now. + self.stopwatch.reset() + for i in range(count): + # So that the child gets torn down after the test. + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + child.expect_exact(prompt) + child.sendline( + 'breakpoint set -f %s -l %d' % + (self.source, self.line_to_break)) + child.expect_exact(prompt) + child.sendline('run') + child.expect_exact(prompt) + expr_cmd1 = 'expr ptr[j]->point.x' + expr_cmd2 = 'expr ptr[j]->point.y' + + with self.stopwatch: + child.sendline(expr_cmd1) + child.expect_exact(prompt) + child.sendline(expr_cmd2) + child.expect_exact(prompt) + + child.sendline('quit') + try: + self.child.expect(pexpect.EOF) + except: + pass + + self.child = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py new file mode 100644 index 00000000000..438a1fdd30a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py @@ -0,0 +1,140 @@ +"""Test evaluating expressions repeatedly comparing lldb against gdb.""" + +from __future__ import print_function + + +import sys +import lldb +from lldbsuite.test.lldbbench import BenchBase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import configuration +from lldbsuite.test import lldbutil + + +class RepeatedExprsCase(BenchBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + BenchBase.setUp(self) + self.source = 'main.cpp' + self.line_to_break = line_number( + self.source, '// Set breakpoint here.') + self.lldb_avg = None + self.gdb_avg = None + self.count = 100 + + @benchmarks_test + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + def test_compare_lldb_to_gdb(self): + """Test repeated expressions with lldb vs. gdb.""" + self.build() + self.exe_name = 'a.out' + + print() + self.run_lldb_repeated_exprs(self.exe_name, self.count) + print("lldb benchmark:", self.stopwatch) + self.run_gdb_repeated_exprs(self.exe_name, self.count) + print("gdb benchmark:", self.stopwatch) + print("lldb_avg/gdb_avg: %f" % (self.lldb_avg / self.gdb_avg)) + + def run_lldb_repeated_exprs(self, exe_name, count): + import pexpect + exe = self.getBuildArtifact(exe_name) + + # Set self.child_prompt, which is "(lldb) ". + self.child_prompt = '(lldb) ' + prompt = self.child_prompt + + # So that the child gets torn down after the test. + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + child.expect_exact(prompt) + child.sendline( + 'breakpoint set -f %s -l %d' % + (self.source, self.line_to_break)) + child.expect_exact(prompt) + child.sendline('run') + child.expect_exact(prompt) + expr_cmd1 = 'expr ptr[j]->point.x' + expr_cmd2 = 'expr ptr[j]->point.y' + + # Reset the stopwatch now. + self.stopwatch.reset() + for i in range(count): + with self.stopwatch: + child.sendline(expr_cmd1) + child.expect_exact(prompt) + child.sendline(expr_cmd2) + child.expect_exact(prompt) + child.sendline('process continue') + child.expect_exact(prompt) + + child.sendline('quit') + try: + self.child.expect(pexpect.EOF) + except: + pass + + self.lldb_avg = self.stopwatch.avg() + if self.TraceOn(): + print("lldb expression benchmark:", str(self.stopwatch)) + self.child = None + + def run_gdb_repeated_exprs(self, exe_name, count): + import pexpect + exe = self.getBuildArtifact(exe_name) + + # Set self.child_prompt, which is "(gdb) ". + self.child_prompt = '(gdb) ' + prompt = self.child_prompt + + # So that the child gets torn down after the test. + self.child = pexpect.spawn('gdb --nx %s' % exe) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + child.expect_exact(prompt) + child.sendline('break %s:%d' % (self.source, self.line_to_break)) + child.expect_exact(prompt) + child.sendline('run') + child.expect_exact(prompt) + expr_cmd1 = 'print ptr[j]->point.x' + expr_cmd2 = 'print ptr[j]->point.y' + + # Reset the stopwatch now. + self.stopwatch.reset() + for i in range(count): + with self.stopwatch: + child.sendline(expr_cmd1) + child.expect_exact(prompt) + child.sendline(expr_cmd2) + child.expect_exact(prompt) + child.sendline('continue') + child.expect_exact(prompt) + + child.sendline('quit') + child.expect_exact('The program is running. Exit anyway?') + child.sendline('y') + try: + self.child.expect(pexpect.EOF) + except: + pass + + self.gdb_avg = self.stopwatch.avg() + if self.TraceOn(): + print("gdb expression benchmark:", str(self.stopwatch)) + self.child = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/main.cpp new file mode 100644 index 00000000000..4083a680865 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/expression/main.cpp @@ -0,0 +1,50 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +class Point { +public: + int x; + int y; + Point(int a, int b): + x(a), + y(b) + {} +}; + +class Data { +public: + int id; + Point point; + Data(int i): + id(i), + point(0, 0) + {} +}; + +int main(int argc, char const *argv[]) { + Data *data[1000]; + Data **ptr = data; + for (int i = 0; i < 1000; ++i) { + ptr[i] = new Data(i); + ptr[i]->point.x = i; + ptr[i]->point.y = i+1; + } + + printf("Finished populating data.\n"); + for (int j = 0; j < 1000; ++j) { + bool dump = argc > 1; // Set breakpoint here. + // Evaluate a couple of expressions (2*1000 = 2000 exprs): + // expr ptr[j]->point.x + // expr ptr[j]->point.y + if (dump) { + printf("data[%d] = %d (%d, %d)\n", j, ptr[j]->id, ptr[j]->point.x, ptr[j]->point.y); + } + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py new file mode 100644 index 00000000000..5261204beea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py @@ -0,0 +1,75 @@ +"""Test lldb's response time for 'frame variable' command.""" + +from __future__ import print_function + + +import sys +import lldb +from lldbsuite.test import configuration +from lldbsuite.test import lldbtest_config +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbbench import * + + +class FrameVariableResponseBench(BenchBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + BenchBase.setUp(self) + self.exe = lldbtest_config.lldbExec + self.break_spec = '-n main' + self.count = 20 + + @benchmarks_test + @no_debug_info_test + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + def test_startup_delay(self): + """Test response time for the 'frame variable' command.""" + print() + self.run_frame_variable_bench(self.exe, self.break_spec, self.count) + print("lldb frame variable benchmark:", self.stopwatch) + + def run_frame_variable_bench(self, exe, break_spec, count): + import pexpect + # Set self.child_prompt, which is "(lldb) ". + self.child_prompt = '(lldb) ' + prompt = self.child_prompt + + # Reset the stopwatchs now. + self.stopwatch.reset() + for i in range(count): + # So that the child gets torn down after the test. + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + # Set our breakpoint. + child.sendline('breakpoint set %s' % break_spec) + child.expect_exact(prompt) + + # Run the target and expect it to be stopped due to breakpoint. + child.sendline('run') # Aka 'process launch'. + child.expect_exact(prompt) + + with self.stopwatch: + # Measure the 'frame variable' response time. + child.sendline('frame variable') + child.expect_exact(prompt) + + child.sendline('quit') + try: + self.child.expect(pexpect.EOF) + except: + pass + + # The test is about to end and if we come to here, the child process has + # been terminated. Mark it so. + self.child = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py new file mode 100644 index 00000000000..5ad59f34dbf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py @@ -0,0 +1,65 @@ +""" +Test lldb data formatter subsystem. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbbench import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestBenchmarkLibcxxList(BenchBase): + + mydir = TestBase.compute_mydir(__file__) + + @benchmarks_test + def test_run_command(self): + """Benchmark the std::list data formatter (libc++)""" + self.build() + self.data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + BenchBase.setUp(self) + + def data_formatter_commands(self): + """Benchmark the std::list data formatter (libc++)""" + self.runCmd("file " + self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "break here")) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + sw = Stopwatch() + + sw.start() + self.expect('frame variable -A list', substrs=['[300]', '300']) + sw.stop() + + print("time to print: %s" % (sw)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/main.cpp new file mode 100644 index 00000000000..9c4113ad051 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxlist/main.cpp @@ -0,0 +1,11 @@ +#include <list> + +int main() +{ + std::list<int> list; + for (int i = 0; + i < 1500; + i++) + list.push_back(i); + return list.size(); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py new file mode 100644 index 00000000000..ba5ba084c8b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py @@ -0,0 +1,65 @@ +""" +Test lldb data formatter subsystem. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.lldbbench import * +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestBenchmarkLibcxxMap(BenchBase): + + mydir = TestBase.compute_mydir(__file__) + + @benchmarks_test + def test_run_command(self): + """Benchmark the std::map data formatter (libc++)""" + self.build() + self.data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + BenchBase.setUp(self) + + def data_formatter_commands(self): + """Benchmark the std::map data formatter (libc++)""" + self.runCmd("file " +self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "break here")) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + sw = Stopwatch() + + sw.start() + self.expect('frame variable -A map', substrs=['[300]', '300']) + sw.stop() + + print("time to print: %s" % (sw)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/main.cpp new file mode 100644 index 00000000000..45efb26b6b0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/libcxxmap/main.cpp @@ -0,0 +1,11 @@ +#include <map> + +int main() +{ + std::map<int, int> map; + for (int i = 0; + i < 1500; + i++) + map[i] = i; + return map.size(); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py new file mode 100644 index 00000000000..104b5d74c74 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py @@ -0,0 +1,91 @@ +"""Test lldb's startup delays creating a target, setting a breakpoint, and run to breakpoint stop.""" + +from __future__ import print_function + + +import sys +import lldb +from lldbsuite.test import configuration +from lldbsuite.test import lldbtest_config +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbbench import * + + +class StartupDelaysBench(BenchBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + BenchBase.setUp(self) + # Create self.stopwatch2 for measuring "set first breakpoint". + # The default self.stopwatch is for "create fresh target". + self.stopwatch2 = Stopwatch() + # Create self.stopwatch3 for measuring "run to breakpoint". + self.stopwatch3 = Stopwatch() + self.exe = lldbtest_config.lldbExec + self.break_spec = '-n main' + self.count = 30 + + @benchmarks_test + @no_debug_info_test + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + def test_startup_delay(self): + """Test start up delays creating a target, setting a breakpoint, and run to breakpoint stop.""" + print() + self.run_startup_delays_bench(self.exe, self.break_spec, self.count) + print( + "lldb startup delay (create fresh target) benchmark:", + self.stopwatch) + print( + "lldb startup delay (set first breakpoint) benchmark:", + self.stopwatch2) + print( + "lldb startup delay (run to breakpoint) benchmark:", + self.stopwatch3) + + def run_startup_delays_bench(self, exe, break_spec, count): + import pexpect + # Set self.child_prompt, which is "(lldb) ". + self.child_prompt = '(lldb) ' + prompt = self.child_prompt + + # Reset the stopwatchs now. + self.stopwatch.reset() + self.stopwatch2.reset() + for i in range(count): + # So that the child gets torn down after the test. + self.child = pexpect.spawn( + '%s %s' % + (lldbtest_config.lldbExec, self.lldbOption)) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + with self.stopwatch: + # Create a fresh target. + child.sendline('file %s' % exe) # Aka 'target create'. + child.expect_exact(prompt) + + with self.stopwatch2: + # Read debug info and set the first breakpoint. + child.sendline('breakpoint set %s' % break_spec) + child.expect_exact(prompt) + + with self.stopwatch3: + # Run to the breakpoint just set. + child.sendline('run') + child.expect_exact(prompt) + + child.sendline('quit') + try: + self.child.expect(pexpect.EOF) + except: + pass + + # The test is about to end and if we come to here, the child process has + # been terminated. Mark it so. + self.child = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py new file mode 100644 index 00000000000..e5a8f168b64 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py @@ -0,0 +1,75 @@ +"""Test lldb's stepping speed.""" + +from __future__ import print_function + +import sys +import lldb +from lldbsuite.test import configuration +from lldbsuite.test import lldbtest_config +from lldbsuite.test.lldbbench import * +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SteppingSpeedBench(BenchBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + BenchBase.setUp(self) + self.exe = lldbtest_config.lldbExec + self.break_spec = '-n main' + self.count = 50 + + #print("self.exe=%s" % self.exe) + #print("self.break_spec=%s" % self.break_spec) + + @benchmarks_test + @no_debug_info_test + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + def test_run_lldb_steppings(self): + """Test lldb steppings on a large executable.""" + print() + self.run_lldb_steppings(self.exe, self.break_spec, self.count) + print("lldb stepping benchmark:", self.stopwatch) + + def run_lldb_steppings(self, exe, break_spec, count): + import pexpect + # Set self.child_prompt, which is "(lldb) ". + self.child_prompt = '(lldb) ' + prompt = self.child_prompt + + # So that the child gets torn down after the test. + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + child.expect_exact(prompt) + child.sendline('breakpoint set %s' % break_spec) + child.expect_exact(prompt) + child.sendline('run') + child.expect_exact(prompt) + + # Reset the stopwatch now. + self.stopwatch.reset() + for i in range(count): + with self.stopwatch: + # Disassemble the function. + child.sendline('next') # Aka 'thread step-over'. + child.expect_exact(prompt) + + child.sendline('quit') + try: + self.child.expect(pexpect.EOF) + except: + pass + + self.child = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py new file mode 100644 index 00000000000..5bf78035be4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py @@ -0,0 +1,130 @@ +"""Benchmark the turnaround time starting a debugger and run to the breakpont with lldb vs. gdb.""" + +from __future__ import print_function + + +import sys +import lldb +from lldbsuite.test.lldbbench import * +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import configuration +from lldbsuite.test import lldbutil + + +class CompileRunToBreakpointBench(BenchBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + BenchBase.setUp(self) + self.exe = lldbtest_config.lldbExec + self.function = 'Driver::MainLoop()' + self.count = 3 + + self.lldb_avg = None + self.gdb_avg = None + + @benchmarks_test + @no_debug_info_test + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + def test_run_lldb_then_gdb(self): + """Benchmark turnaround time with lldb vs. gdb.""" + print() + self.run_lldb_turnaround(self.exe, self.function, self.count) + print("lldb turnaround benchmark:", self.stopwatch) + self.run_gdb_turnaround(self.exe, self.function, self.count) + print("gdb turnaround benchmark:", self.stopwatch) + print("lldb_avg/gdb_avg: %f" % (self.lldb_avg / self.gdb_avg)) + + def run_lldb_turnaround(self, exe, function, count): + import pexpect + + def run_one_round(): + prompt = self.child_prompt + + # So that the child gets torn down after the test. + self.child = pexpect.spawn( + '%s %s %s' % + (lldbtest_config.lldbExec, self.lldbOption, exe)) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + child.expect_exact(prompt) + child.sendline('breakpoint set -F %s' % function) + child.expect_exact(prompt) + child.sendline('run') + child.expect_exact(prompt) + + # Set self.child_prompt, which is "(lldb) ". + self.child_prompt = '(lldb) ' + # Reset the stopwatch now. + self.stopwatch.reset() + + for i in range(count + 1): + # Ignore the first invoke lldb and run to the breakpoint turnaround + # time. + if i == 0: + run_one_round() + else: + with self.stopwatch: + run_one_round() + + self.child.sendline('quit') + try: + self.child.expect(pexpect.EOF) + except: + pass + + self.lldb_avg = self.stopwatch.avg() + self.child = None + + def run_gdb_turnaround(self, exe, function, count): + import pexpect + + def run_one_round(): + prompt = self.child_prompt + + # So that the child gets torn down after the test. + self.child = pexpect.spawn('gdb --nx %s' % exe) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + child.expect_exact(prompt) + child.sendline('break %s' % function) + child.expect_exact(prompt) + child.sendline('run') + child.expect_exact(prompt) + + # Set self.child_prompt, which is "(gdb) ". + self.child_prompt = '(gdb) ' + # Reset the stopwatch now. + self.stopwatch.reset() + + for i in range(count + 1): + # Ignore the first invoke lldb and run to the breakpoint turnaround + # time. + if i == 0: + run_one_round() + else: + with self.stopwatch: + run_one_round() + + self.child.sendline('quit') + self.child.expect_exact('The program is running. Exit anyway?') + self.child.sendline('y') + try: + self.child.expect(pexpect.EOF) + except: + pass + + self.gdb_avg = self.stopwatch.avg() + self.child = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/add-dsym/uuid/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/add-dsym/uuid/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/add-dsym/uuid/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/add-dsym/uuid/TestAddDsymCommand.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/add-dsym/uuid/TestAddDsymCommand.py new file mode 100644 index 00000000000..8a0fe377f26 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/add-dsym/uuid/TestAddDsymCommand.py @@ -0,0 +1,130 @@ +"""Test that the 'add-dsym', aka 'target symbols add', command informs the user about success or failure.""" + + + +import os +import time +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class AddDsymCommandCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.template = 'main.cpp.template' + self.source = 'main.cpp' + self.teardown_hook_added = False + + @no_debug_info_test + def test_add_dsym_command_with_error(self): + """Test that the 'add-dsym' command informs the user about failures.""" + + # Call the program generator to produce main.cpp, version 1. + self.generate_main_cpp(version=1) + self.buildDefault(dictionary={'MAKE_DSYM':'YES'}) + + # Insert some delay and then call the program generator to produce + # main.cpp, version 2. + time.sleep(5) + self.generate_main_cpp(version=101) + # Now call make again, but this time don't generate the dSYM. + self.buildDefault(dictionary={'MAKE_DSYM':'NO'}) + + self.exe_name = 'a.out' + self.do_add_dsym_with_error(self.exe_name) + + @no_debug_info_test + def test_add_dsym_command_with_success(self): + """Test that the 'add-dsym' command informs the user about success.""" + + # Call the program generator to produce main.cpp, version 1. + self.generate_main_cpp(version=1) + self.buildDefault(dictionary={'MAKE_DSYM':'YES'}) + + self.exe_name = 'a.out' + self.do_add_dsym_with_success(self.exe_name) + + @no_debug_info_test + def test_add_dsym_with_dSYM_bundle(self): + """Test that the 'add-dsym' command informs the user about success.""" + + # Call the program generator to produce main.cpp, version 1. + self.generate_main_cpp(version=1) + self.buildDefault(dictionary={'MAKE_DSYM':'YES'}) + + self.exe_name = 'a.out' + self.do_add_dsym_with_dSYM_bundle(self.exe_name) + + def generate_main_cpp(self, version=0): + """Generate main.cpp from main.cpp.template.""" + temp = os.path.join(self.getSourceDir(), self.template) + with open(temp, 'r') as f: + content = f.read() + + new_content = content.replace( + '%ADD_EXTRA_CODE%', + 'printf("This is version %d\\n");' % + version) + src = os.path.join(self.getBuildDir(), self.source) + with open(src, 'w') as f: + f.write(new_content) + + # The main.cpp has been generated, add a teardown hook to remove it. + if not self.teardown_hook_added: + self.addTearDownHook(lambda: os.remove(src)) + self.teardown_hook_added = True + + def do_add_dsym_with_error(self, exe_name): + """Test that the 'add-dsym' command informs the user about failures.""" + exe_path = self.getBuildArtifact(exe_name) + self.runCmd("file " + exe_path, CURRENT_EXECUTABLE_SET) + + wrong_path = os.path.join(self.getBuildDir(), + "%s.dSYM" % exe_name, "Contents") + self.expect("add-dsym " + wrong_path, error=True, + substrs=['invalid module path']) + + right_path = os.path.join( + self.getBuildDir(), + "%s.dSYM" % + exe_path, + "Contents", + "Resources", + "DWARF", + exe_name) + self.expect("add-dsym " + right_path, error=True, + substrs=['symbol file', 'does not match']) + + def do_add_dsym_with_success(self, exe_name): + """Test that the 'add-dsym' command informs the user about success.""" + exe_path = self.getBuildArtifact(exe_name) + self.runCmd("file " + exe_path, CURRENT_EXECUTABLE_SET) + + # This time, the UUID should match and we expect some feedback from + # lldb. + right_path = os.path.join( + self.getBuildDir(), + "%s.dSYM" % + exe_path, + "Contents", + "Resources", + "DWARF", + exe_name) + self.expect("add-dsym " + right_path, + substrs=['symbol file', 'has been added to']) + + def do_add_dsym_with_dSYM_bundle(self, exe_name): + """Test that the 'add-dsym' command informs the user about success when loading files in bundles.""" + exe_path = self.getBuildArtifact(exe_name) + self.runCmd("file " + exe_path, CURRENT_EXECUTABLE_SET) + + # This time, the UUID should be found inside the bundle + right_path = "%s.dSYM" % exe_path + self.expect("add-dsym " + right_path, + substrs=['symbol file', 'has been added to']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/add-dsym/uuid/main.cpp.template b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/add-dsym/uuid/main.cpp.template new file mode 100644 index 00000000000..d486b3dd8b9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/add-dsym/uuid/main.cpp.template @@ -0,0 +1,18 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +int +main(int argc, char const *argv[]) +{ + int my_int = argc + 3; + printf("Hello UUID Mismatch: %d\n", my_int); // Set breakpoint here. + %ADD_EXTRA_CODE% + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/basic/TestApropos.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/basic/TestApropos.py new file mode 100644 index 00000000000..920f0dd0b24 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/basic/TestApropos.py @@ -0,0 +1,26 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +class AproposTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_apropos(self): + self.expect("apropos", error=True, + substrs=[' must be called with exactly one argument']) + self.expect("apropos a b", error=True, + substrs=[' must be called with exactly one argument']) + self.expect("apropos ''", error=True, + substrs=['\'\' is not a valid search word']) + + @no_debug_info_test + def test_apropos_variable(self): + """Test that 'apropos variable' prints the fully qualified command name""" + self.expect( + 'apropos variable', + substrs=[ + 'frame variable', + 'target variable', + 'watchpoint set variable']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/with-process/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/with-process/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/with-process/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/with-process/TestAproposWithProcess.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/with-process/TestAproposWithProcess.py new file mode 100644 index 00000000000..64eca718aea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/with-process/TestAproposWithProcess.py @@ -0,0 +1,43 @@ +""" +Test that apropos env doesn't crash trying to touch the process plugin command +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class AproposWithProcessTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// break here') + + def test_apropos_with_process(self): + """Test that apropos env doesn't crash trying to touch the process plugin command.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break in main() after the variables are assigned values. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.runCmd('apropos env') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/with-process/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/with-process/main.cpp new file mode 100644 index 00000000000..d18c86512bf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/apropos/with-process/main.cpp @@ -0,0 +1,14 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int main (int argc, char const *argv[]) +{ + return 0; // break here +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/breakpoint/command/list/TestBreakpointCommandList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/breakpoint/command/list/TestBreakpointCommandList.py new file mode 100644 index 00000000000..f1a8656a73b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/breakpoint/command/list/TestBreakpointCommandList.py @@ -0,0 +1,44 @@ +""" +Test 'breakpoint command list'. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_list_commands(self): + src_dir = self.getSourceDir() + yaml_path = os.path.join(src_dir, "a.yaml") + yaml_base, ext = os.path.splitext(yaml_path) + obj_path = self.getBuildArtifact("main.o") + self.yaml2obj(yaml_path, obj_path) + + # Create a target with the object file we just created from YAML + target = self.dbg.CreateTarget(obj_path) + self.assertTrue(target, VALID_TARGET) + + # Test without any breakpoints. + self.expect("breakpoint command list 1", error=True, substrs=["error: No breakpoints exist for which to list commands"]) + + # Set a breakpoint + self.runCmd("b foo") + + # Check list breakpoint commands for breakpoints that have no commands. + self.expect("breakpoint command list 1", startstr="Breakpoint 1 does not have an associated command.") + + # Add a breakpoint command. + self.runCmd("breakpoint command add -o 'source list' 1") + + # List breakpoint command that we just created. + self.expect("breakpoint command list 1", startstr="""Breakpoint 1: + Breakpoint commands: + source list +""") + + # List breakpoint command with invalid breakpoint ID. + self.expect("breakpoint command list 2", error=True, startstr="error: '2' is not a currently valid breakpoint ID.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/breakpoint/command/list/a.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/breakpoint/command/list/a.yaml new file mode 100644 index 00000000000..1007f60c19e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/breakpoint/command/list/a.yaml @@ -0,0 +1,18 @@ +--- !ELF +FileHeader: + Class: ELFCLASS64 + Data: ELFDATA2LSB + Type: ET_REL + Machine: EM_X86_64 +Sections: + - Name: .text + Type: SHT_PROGBITS + Flags: [ SHF_ALLOC, SHF_EXECINSTR ] + AddressAlign: 0x0000000000000010 + Content: 554889E5897DFC5DC3 +Symbols: + - Name: foo + Type: STT_FUNC + Section: .text + Size: 0x0000000000000009 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/.categories new file mode 100644 index 00000000000..3a3f4df6416 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/.categories @@ -0,0 +1 @@ +cmdline diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/delete/TestCommandDelete.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/delete/TestCommandDelete.py new file mode 100644 index 00000000000..3fa654d20aa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/delete/TestCommandDelete.py @@ -0,0 +1,17 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +class DeleteCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_delete_builtin(self): + self.expect("command delete settings", error=True, + substrs=["'settings' is a permanent debugger command and cannot be removed."]) + + @no_debug_info_test + def test_delete_alias(self): + self.expect("command delete bt", error=True, + substrs=["'bt' is not a known command."]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/history/TestCommandHistory.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/history/TestCommandHistory.py new file mode 100644 index 00000000000..c866198f26b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/history/TestCommandHistory.py @@ -0,0 +1,106 @@ +""" +Test the command history mechanism +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CommandHistoryTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_history(self): + self.runCmd('command history --clear', inHistory=False) + self.runCmd('breakpoint list', check=False, inHistory=True) # 0 + self.runCmd('register read', check=False, inHistory=True) # 1 + self.runCmd('apropos hello', check=False, inHistory=True) # 2 + self.runCmd('memory write', check=False, inHistory=True) # 3 + self.runCmd('log list', check=False, inHistory=True) # 4 + self.runCmd('disassemble', check=False, inHistory=True) # 5 + self.runCmd('expression 1', check=False, inHistory=True) # 6 + self.runCmd( + 'type summary list -w default', + check=False, + inHistory=True) # 7 + self.runCmd('version', check=False, inHistory=True) # 8 + self.runCmd('frame select 1', check=False, inHistory=True) # 9 + + self.expect( + "command history -s 3 -c 3", + inHistory=True, + substrs=[ + '3: memory write', + '4: log list', + '5: disassemble']) + + self.expect("command history -s 3 -e 3", inHistory=True, + substrs=['3: memory write']) + + self.expect( + "command history -s 6 -e 7", + inHistory=True, + substrs=[ + '6: expression 1', + '7: type summary list -w default']) + + self.expect("command history -c 2", inHistory=True, + substrs=['0: breakpoint list', '1: register read']) + + self.expect("command history -e 3 -c 1", inHistory=True, + substrs=['3: memory write']) + + self.expect( + "command history -e 2", + inHistory=True, + substrs=[ + '0: breakpoint list', + '1: register read', + '2: apropos hello']) + + self.expect( + "command history -s 12", + inHistory=True, + substrs=[ + '12: command history -s 6 -e 7', + '13: command history -c 2', + '14: command history -e 3 -c 1', + '15: command history -e 2', + '16: command history -s 12']) + + self.expect( + "command history -s end -c 3", + inHistory=True, + substrs=[ + '15: command history -e 2', + '16: command history -s 12', + '17: command history -s end -c 3']) + + self.expect( + "command history -s end -e 15", + inHistory=True, + substrs=[ + '15: command history -e 2', + '16: command history -s 12', + '17: command history -s end -c 3', + 'command history -s end -e 15']) + + self.expect("command history -s 5 -c 1", inHistory=True, + substrs=['5: disassemble']) + + self.expect("command history -c 1 -s 5", inHistory=True, + substrs=['5: disassemble']) + + self.expect("command history -c 1 -e 3", inHistory=True, + substrs=['3: memory write']) + + self.expect( + "command history -c 1 -e 3 -s 5", + error=True, + inHistory=True, + substrs=['error: --count, --start-index and --end-index cannot be all specified in the same invocation']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/invalid-args/TestInvalidArgsCommand.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/invalid-args/TestInvalidArgsCommand.py new file mode 100644 index 00000000000..47d77b0e569 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/invalid-args/TestInvalidArgsCommand.py @@ -0,0 +1,58 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +class InvalidArgsCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_script_add(self): + self.expect("command script add 1 2", error=True, + substrs=["'command script add' requires one argument"]) + + self.expect("command script add", error=True, + substrs=["'command script add' requires one argument"]) + + @no_debug_info_test + def test_script_clear(self): + self.expect("command script clear f", error=True, + substrs=["'command script clear' doesn't take any arguments"]) + + @no_debug_info_test + def test_script_list(self): + self.expect("command script list f", error=True, + substrs=["'command script list' doesn't take any arguments"]) + + @no_debug_info_test + def test_script_import(self): + self.expect("command script import", error=True, + substrs=["command script import needs one or more arguments"]) + + @no_debug_info_test + def test_alias(self): + self.expect("command alias", error=True, + substrs=["'command alias' requires at least two arguments"]) + + self.expect("command alias blub foo", error=True, + substrs=["error: invalid command given to 'command alias'. 'foo' does not begin with a valid command. No alias created."]) + + @no_debug_info_test + def test_unalias(self): + self.expect("command unalias", error=True, + substrs=["must call 'unalias' with a valid alias"]) + + @no_debug_info_test + def test_delete(self): + self.expect("command delete", error=True, + substrs=["must call 'command delete' with one or more valid user"]) + + @no_debug_info_test + def test_regex(self): + self.expect("command regex", error=True, + substrs=["usage: 'command regex <command-name> "]) + + @no_debug_info_test + def test_source(self): + self.expect("command source", error=True, + substrs=["'command source' takes exactly one executable filename argument."]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/nested_alias/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/nested_alias/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/nested_alias/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/nested_alias/TestNestedAlias.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/nested_alias/TestNestedAlias.py new file mode 100644 index 00000000000..a1374a9c716 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/nested_alias/TestNestedAlias.py @@ -0,0 +1,99 @@ +""" +Test that an alias can reference other aliases without crashing. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class NestedAliasTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// break here') + + def test_nested_alias(self): + """Test that an alias can reference other aliases without crashing.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break in main() after the variables are assigned values. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # This is the function to remove the custom aliases in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('command unalias read', check=False) + self.runCmd('command unalias rd', check=False) + self.runCmd('command unalias fo', check=False) + self.runCmd('command unalias foself', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd('command alias read memory read -f A') + self.runCmd('command alias rd read -c 3') + + self.expect( + 'memory read -f A -c 3 `&my_ptr[0]`', + substrs=[ + 'deadbeef', + 'main.cpp:', + 'feedbeef']) + self.expect( + 'rd `&my_ptr[0]`', + substrs=[ + 'deadbeef', + 'main.cpp:', + 'feedbeef']) + + self.expect( + 'memory read -f A -c 3 `&my_ptr[0]`', + substrs=['deadfeed'], + matching=False) + self.expect('rd `&my_ptr[0]`', substrs=['deadfeed'], matching=False) + + self.runCmd('command alias fo frame variable -O --') + self.runCmd('command alias foself fo self') + + self.expect( + 'help foself', + substrs=[ + '--show-all-children', + '--raw-output'], + matching=False) + self.expect( + 'help foself', + substrs=[ + 'Show variables for the current', + 'stack frame.'], + matching=True) + + # Check that foself was resolved and is now independent of 'fo'. + self.runCmd('command unalias fo') + self.expect( + 'help foself', + substrs=[ + 'Show variables for the current', + 'stack frame.'], + matching=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/nested_alias/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/nested_alias/main.cpp new file mode 100644 index 00000000000..4df7eed40a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/nested_alias/main.cpp @@ -0,0 +1,21 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int main (int argc, char const *argv[]) +{ + void* my_ptr[] = { + reinterpret_cast<void*>(0xDEADBEEF), + reinterpret_cast<void*>(main), + reinterpret_cast<void*>(0xFEEDBEEF), + reinterpret_cast<void*>(0xFEEDDEAD), + reinterpret_cast<void*>(0xDEADFEED) + }; + return 0; // break here +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/TestCommandScript.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/TestCommandScript.py new file mode 100644 index 00000000000..de449612a37 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/TestCommandScript.py @@ -0,0 +1,167 @@ +""" +Test lldb Python commands. +""" + + +import sys +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class CmdPythonTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test(self): + self.build() + self.pycmd_tests() + + def pycmd_tests(self): + self.runCmd("command source py_import") + + # Test a bunch of different kinds of python callables with + # both 4 and 5 positional arguments. + self.expect("foobar", substrs=["All good"]) + self.expect("foobar4", substrs=["All good"]) + self.expect("vfoobar", substrs=["All good"]) + self.expect("v5foobar", substrs=["All good"]) + self.expect("sfoobar", substrs=["All good"]) + self.expect("cfoobar", substrs=["All good"]) + self.expect("ifoobar", substrs=["All good"]) + self.expect("sfoobar4", substrs=["All good"]) + self.expect("cfoobar4", substrs=["All good"]) + self.expect("ifoobar4", substrs=["All good"]) + self.expect("ofoobar", substrs=["All good"]) + self.expect("ofoobar4", substrs=["All good"]) + + # Verify command that specifies eCommandRequiresTarget returns failure + # without a target. + self.expect('targetname', + substrs=['a.out'], matching=False, error=True) + + exe = self.getBuildArtifact("a.out") + self.expect("file " + exe, + patterns=["Current executable set to .*a.out"]) + + self.expect('targetname', + substrs=['a.out'], matching=True, error=False) + + # This is the function to remove the custom commands in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('command script delete welcome', check=False) + self.runCmd('command script delete targetname', check=False) + self.runCmd('command script delete longwait', check=False) + self.runCmd('command script delete mysto', check=False) + self.runCmd('command script delete tell_sync', check=False) + self.runCmd('command script delete tell_async', check=False) + self.runCmd('command script delete tell_curr', check=False) + self.runCmd('command script delete bug11569', check=False) + self.runCmd('command script delete takes_exe_ctx', check=False) + self.runCmd('command script delete decorated', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Interact with debugger in synchronous mode + self.setAsync(False) + + # We don't want to display the stdout if not in TraceOn() mode. + if not self.TraceOn(): + self.HideStdout() + + self.expect('welcome Enrico', + substrs=['Hello Enrico, welcome to LLDB']) + + self.expect("help welcome", + substrs=['Just a docstring for welcome_impl', + 'A command that says hello to LLDB users']) + + decorated_commands = ["decorated" + str(n) for n in range(1, 5)] + for name in decorated_commands: + self.expect(name, substrs=["hello from " + name]) + self.expect("help " + name, + substrs=["Python command defined by @lldb.command"]) + + self.expect("help", + substrs=['For more information run', + 'welcome'] + decorated_commands) + + self.expect("help -a", + substrs=['For more information run', + 'welcome'] + decorated_commands) + + self.expect("help -u", matching=False, + substrs=['For more information run']) + + self.runCmd("command script delete welcome") + + self.expect('welcome Enrico', matching=False, error=True, + substrs=['Hello Enrico, welcome to LLDB']) + + self.expect('targetname fail', error=True, + substrs=['a test for error in command']) + + self.expect('command script list', + substrs=['targetname', + 'For more information run']) + + self.expect("help targetname", + substrs=['Expects', '\'raw\'', 'input', + 'help', 'raw-input']) + + self.expect("longwait", + substrs=['Done; if you saw the delays I am doing OK']) + + self.runCmd("b main") + self.runCmd("run") + self.runCmd("mysto 3") + self.expect("frame variable array", + substrs=['[0] = 79630', '[1] = 388785018', '[2] = 0']) + self.runCmd("mysto 3") + self.expect("frame variable array", + substrs=['[0] = 79630', '[4] = 388785018', '[5] = 0']) + +# we cannot use the stepover command to check for async execution mode since LLDB +# seems to get confused when events start to queue up + self.expect("tell_sync", + substrs=['running sync']) + self.expect("tell_async", + substrs=['running async']) + self.expect("tell_curr", + substrs=['I am running sync']) + +# check that the execution context is passed in to commands that ask for it + self.expect("takes_exe_ctx", substrs=["a.out"]) + + # Test that a python command can redefine itself + self.expect('command script add -f foobar welcome -h "just some help"') + + self.runCmd("command script clear") + + # Test that re-defining an existing command works + self.runCmd( + 'command script add my_command --class welcome.WelcomeCommand') + self.expect('my_command Blah', substrs=['Hello Blah, welcome to LLDB']) + + self.runCmd( + 'command script add my_command --class welcome.TargetnameCommand') + self.expect('my_command', substrs=['a.out']) + + self.runCmd("command script clear") + + self.expect('command script list', matching=False, + substrs=['targetname', + 'longwait']) + + self.expect('command script add -f foobar frame', error=True, + substrs=['cannot add command']) + + # http://llvm.org/bugs/show_bug.cgi?id=11569 + # LLDBSwigPythonCallCommand crashes when a command script returns an + # object + self.runCmd('command script add -f bug11569 bug11569') + # This should not crash. + self.runCmd('bug11569', check=False) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/bug11569.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/bug11569.py new file mode 100644 index 00000000000..3c124de79bf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/bug11569.py @@ -0,0 +1,6 @@ +def bug11569(debugger, args, result, dict): + """ + http://llvm.org/bugs/show_bug.cgi?id=11569 + LLDBSwigPythonCallCommand crashes when a command script returns an object. + """ + return ["return", "a", "non-string", "should", "not", "crash", "LLDB"] diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/callables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/callables.py new file mode 100644 index 00000000000..c31e84cbb53 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/callables.py @@ -0,0 +1,62 @@ + + +import lldb + +# bunch of different kinds of python callables that should +# all work as commands. + +def check(debugger, command, context, result, internal_dict): + if (not isinstance(debugger, lldb.SBDebugger) or + not isinstance(command, str) or + not isinstance(result, lldb.SBCommandReturnObject) or + not isinstance(internal_dict, dict) or + (not context is None and + not isinstance(context, lldb.SBExecutionContext))): + raise Exception() + result.AppendMessage("All good.") + +def vfoobar(*args): + check(*args) + +def v5foobar(debugger, command, context, result, internal_dict, *args): + check(debugger, command, context, result, internal_dict) + +def foobar(debugger, command, context, result, internal_dict): + check(debugger, command, context, result, internal_dict) + +def foobar4(debugger, command, result, internal_dict): + check(debugger, command, None, result, internal_dict) + +class FooBar: + @staticmethod + def sfoobar(debugger, command, context, result, internal_dict): + check(debugger, command, context, result, internal_dict) + + @classmethod + def cfoobar(cls, debugger, command, context, result, internal_dict): + check(debugger, command, context, result, internal_dict) + + def ifoobar(self, debugger, command, context, result, internal_dict): + check(debugger, command, context, result, internal_dict) + + def __call__(self, debugger, command, context, result, internal_dict): + check(debugger, command, context, result, internal_dict) + + @staticmethod + def sfoobar4(debugger, command, result, internal_dict): + check(debugger, command, None, result, internal_dict) + + @classmethod + def cfoobar4(cls, debugger, command, result, internal_dict): + check(debugger, command, None, result, internal_dict) + + def ifoobar4(self, debugger, command, result, internal_dict): + check(debugger, command, None, result, internal_dict) + +class FooBar4: + def __call__(self, debugger, command, result, internal_dict): + check(debugger, command, None, result, internal_dict) + +FooBarObj = FooBar() + +FooBar4Obj = FooBar4()
\ No newline at end of file diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/decorated.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/decorated.py new file mode 100644 index 00000000000..f9707a5706a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/decorated.py @@ -0,0 +1,35 @@ +from __future__ import print_function + +import lldb + + +@lldb.command() +def decorated1(debugger, args, exe_ctx, result, dict): + """ + Python command defined by @lldb.command + """ + print("hello from decorated1", file=result) + + +@lldb.command(doc="Python command defined by @lldb.command") +def decorated2(debugger, args, exe_ctx, result, dict): + """ + This docstring is overridden. + """ + print("hello from decorated2", file=result) + + +@lldb.command() +def decorated3(debugger, args, result, dict): + """ + Python command defined by @lldb.command + """ + print("hello from decorated3", file=result) + + +@lldb.command("decorated4") +def _decorated4(debugger, args, exe_ctx, result, dict): + """ + Python command defined by @lldb.command + """ + print("hello from decorated4", file=result) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/Makefile new file mode 100644 index 00000000000..d9ee1cc4116 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +EXE := hello_world + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/TestImport.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/TestImport.py new file mode 100644 index 00000000000..a10c23bad1f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/TestImport.py @@ -0,0 +1,71 @@ +"""Test custom import command to import files by path.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ImportTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + @no_debug_info_test + def test_import_command(self): + """Import some Python scripts by path and test them""" + self.run_test() + + def run_test(self): + """Import some Python scripts by path and test them.""" + + # This is the function to remove the custom commands in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('command script delete foo2cmd', check=False) + self.runCmd('command script delete foocmd', check=False) + self.runCmd('command script delete foobarcmd', check=False) + self.runCmd('command script delete barcmd', check=False) + self.runCmd('command script delete barothercmd', check=False) + self.runCmd('command script delete TPcommandA', check=False) + self.runCmd('command script delete TPcommandB', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("command script import ./foo/foo.py --allow-reload") + self.runCmd("command script import ./foo/foo2.py --allow-reload") + self.runCmd("command script import ./foo/bar/foobar.py --allow-reload") + self.runCmd("command script import ./bar/bar.py --allow-reload") + + self.expect("command script import ./nosuchfile.py", + error=True, startstr='error: module importing failed') + self.expect("command script import ./nosuchfolder/", + error=True, startstr='error: module importing failed') + self.expect("command script import ./foo/foo.py", error=False) + + self.runCmd("command script import --allow-reload ./thepackage") + self.expect("TPcommandA", substrs=["hello world A"]) + self.expect("TPcommandB", substrs=["hello world B"]) + + self.runCmd("script import dummymodule") + self.expect("command script import ./dummymodule.py", error=False) + self.expect( + "command script import --allow-reload ./dummymodule.py", + error=False) + + self.runCmd("command script add -f foo.foo_function foocmd") + self.runCmd("command script add -f foobar.foo_function foobarcmd") + self.runCmd("command script add -f bar.bar_function barcmd") + self.expect("foocmd hello", + substrs=['foo says', 'hello']) + self.expect("foo2cmd hello", + substrs=['foo2 says', 'hello']) + self.expect("barcmd hello", + substrs=['barutil says', 'bar told me', 'hello']) + self.expect("barothercmd hello", + substrs=['barutil says', 'bar told me', 'hello']) + self.expect("foobarcmd hello", + substrs=['foobar says', 'hello']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/bar/bar.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/bar/bar.py new file mode 100644 index 00000000000..444e00976ad --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/bar/bar.py @@ -0,0 +1,15 @@ +from __future__ import print_function + + +def bar_function(debugger, args, result, dict): + global UtilityModule + print(UtilityModule.barutil_function("bar told me " + args), file=result) + return None + + +def __lldb_init_module(debugger, session_dict): + global UtilityModule + UtilityModule = __import__("barutil") + debugger.HandleCommand( + "command script add -f bar.bar_function barothercmd") + return None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/bar/barutil.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/bar/barutil.py new file mode 100644 index 00000000000..70ecea30057 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/bar/barutil.py @@ -0,0 +1,2 @@ +def barutil_function(x): + return "barutil says: " + x diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/dummymodule.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/dummymodule.py new file mode 100644 index 00000000000..668a5b90ea4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/dummymodule.py @@ -0,0 +1,2 @@ +def no_useful_code(foo): + return foo diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/foo/bar/foobar.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/foo/bar/foobar.py new file mode 100644 index 00000000000..6ef71064c9a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/foo/bar/foobar.py @@ -0,0 +1,6 @@ +from __future__ import print_function + + +def foo_function(debugger, args, result, dict): + print("foobar says " + args, file=result) + return None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/foo/foo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/foo/foo.py new file mode 100644 index 00000000000..1ccc3892939 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/foo/foo.py @@ -0,0 +1,6 @@ +from __future__ import print_function + + +def foo_function(debugger, args, result, dict): + print("foo says " + args, file=result) + return None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/foo/foo2.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/foo/foo2.py new file mode 100644 index 00000000000..71657c299c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/foo/foo2.py @@ -0,0 +1,11 @@ +from __future__ import print_function + + +def foo2_function(debugger, args, result, dict): + print("foo2 says " + args, file=result) + return None + + +def __lldb_init_module(debugger, session_dict): + debugger.HandleCommand("command script add -f foo2.foo2_function foo2cmd") + return None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/main.c new file mode 100644 index 00000000000..dffc8c77b04 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/main.c @@ -0,0 +1,15 @@ +#include <stdio.h> + +int main(int argc, char const *argv[]) { + printf("Hello world.\n"); // Set break point at this line. + if (argc == 1) + return 0; + + // Waiting to be attached by the debugger, otherwise. + char line[100]; + while (fgets(line, sizeof(line), stdin)) { // Waiting to be attached... + printf("input line=>%s\n", line); + } + + printf("Exiting now\n"); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/Makefile new file mode 100644 index 00000000000..22f1051530f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/Makefile @@ -0,0 +1 @@ +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/TestRdar12586188.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/TestRdar12586188.py new file mode 100644 index 00000000000..478cfa38d03 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/TestRdar12586188.py @@ -0,0 +1,31 @@ +"""Check that we handle an ImportError in a special way when command script importing files.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class Rdar12586188TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + @no_debug_info_test + def test_rdar12586188_command(self): + """Check that we handle an ImportError in a special way when command script importing files.""" + self.run_test() + + def run_test(self): + """Check that we handle an ImportError in a special way when command script importing files.""" + + self.expect( + "command script import ./fail12586188.py --allow-reload", + error=True, + substrs=['raise ImportError("I do not want to be imported")']) + self.expect( + "command script import ./fail212586188.py --allow-reload", + error=True, + substrs=['raise ValueError("I do not want to be imported")']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/fail12586188.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/fail12586188.py new file mode 100644 index 00000000000..ea385e03e04 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/fail12586188.py @@ -0,0 +1,4 @@ +def f(x): + return x + 1 + +raise ImportError("I do not want to be imported") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/fail212586188.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/fail212586188.py new file mode 100644 index 00000000000..8dbc0e67ba1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/rdar-12586188/fail212586188.py @@ -0,0 +1,4 @@ +def f(x): + return x + 1 + +raise ValueError("I do not want to be imported") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/thepackage/TPunitA.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/thepackage/TPunitA.py new file mode 100644 index 00000000000..9694b084295 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/thepackage/TPunitA.py @@ -0,0 +1,7 @@ + +import six + + +def command(debugger, command, result, internal_dict): + result.PutCString(six.u("hello world A")) + return None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/thepackage/TPunitB.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/thepackage/TPunitB.py new file mode 100644 index 00000000000..94a333bc696 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/thepackage/TPunitB.py @@ -0,0 +1,7 @@ + +import six + + +def command(debugger, command, result, internal_dict): + result.PutCString(six.u("hello world B")) + return None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/thepackage/__init__.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/thepackage/__init__.py new file mode 100644 index 00000000000..24cdea60f2c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/import/thepackage/__init__.py @@ -0,0 +1,11 @@ +from __future__ import absolute_import + +from . import TPunitA +from . import TPunitB + + +def __lldb_init_module(debugger, *args): + debugger.HandleCommand( + "command script add -f thepackage.TPunitA.command TPcommandA") + debugger.HandleCommand( + "command script add -f thepackage.TPunitB.command TPcommandB") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/main.cpp new file mode 100644 index 00000000000..a0e9efd6ee0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/main.cpp @@ -0,0 +1,69 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <cstdlib> +#include <cstring> +#include <string> +#include <fstream> +#include <iostream> + +int +product (int x, int y) +{ + int result = x * y; + return result; +} + +int +sum (int a, int b) +{ + int result = a + b; + return result; +} + +int +strange_max (int m, int n) +{ + if (m > n) + return m; + else if (n > m) + return n; + else + return 0; +} + +int +foo (int i, int j) +{ + if (strange_max (i, j) == i) + return product (i, j); + else if (strange_max (i, j) == j) + return sum (i, j); + else + return product (sum (i, i), sum (j, j)); +} + +int +main(int argc, char const *argv[]) +{ + + int array[9]; + memset(array,0,9*sizeof(int)); + + array[0] = foo (1238, 78392); + array[1] = foo (379265, 23674); + array[2] = foo (872934, 234); + array[3] = foo (1238, 78392); + array[4] = foo (379265, 23674); + array[5] = foo (872934, 234); + array[6] = foo (1238, 78392); + array[7] = foo (379265, 23674); + array[8] = foo (872934, 234); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/mysto.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/mysto.py new file mode 100644 index 00000000000..04eceb7eb93 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/mysto.py @@ -0,0 +1,22 @@ +from __future__ import print_function + +import lldb + + +def StepOver(debugger, args, result, dict): + """ + Step over a given number of times instead of only just once + """ + arg_split = args.split(" ") + print(type(arg_split)) + count = int(arg_split[0]) + for i in range(0, count): + debugger.GetSelectedTarget().GetProcess( + ).GetSelectedThread().StepOver(lldb.eOnlyThisThread) + print("step<%d>" % i) + + +def __lldb_init_module(debugger, session_dict): + # by default, --synchronicity is set to synchronous + debugger.HandleCommand("command script add -f mysto.StepOver mysto") + return None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/py_import b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/py_import new file mode 100644 index 00000000000..4372d32b0ad --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/py_import @@ -0,0 +1,32 @@ +script import sys, os +script sys.path.append(os.path.join(os.getcwd(), os.pardir)) +script import welcome +script import bug11569 +command script add welcome --class welcome.WelcomeCommand +command script add targetname --class welcome.TargetnameCommand +command script add longwait --function welcome.print_wait_impl +command script import mysto.py --allow-reload +command script add tell_sync --function welcome.check_for_synchro --synchronicity sync +command script add tell_async --function welcome.check_for_synchro --synchronicity async +command script add tell_curr --function welcome.check_for_synchro --synchronicity curr +command script add takes_exe_ctx --function welcome.takes_exe_ctx +command script import decorated.py + + +command script import callables.py + +command script add -f callables.foobar foobar +command script add -f callables.foobar4 foobar4 +command script add -f callables.vfoobar vfoobar +command script add -f callables.v5foobar v5foobar + +command script add -f callables.FooBar.sfoobar sfoobar +command script add -f callables.FooBar.cfoobar cfoobar +command script add -f callables.FooBarObj.ifoobar ifoobar + +command script add -f callables.FooBar.sfoobar4 sfoobar4 +command script add -f callables.FooBar.cfoobar4 cfoobar4 +command script add -f callables.FooBarObj.ifoobar4 ifoobar4 + +command script add -f callables.FooBarObj ofoobar +command script add -f callables.FooBar4Obj ofoobar4 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/welcome.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/welcome.py new file mode 100644 index 00000000000..0539d7c1721 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script/welcome.py @@ -0,0 +1,53 @@ +from __future__ import print_function +import lldb +import sys + + +class WelcomeCommand(object): + + def __init__(self, debugger, session_dict): + pass + + def get_short_help(self): + return "Just a docstring for welcome_impl\nA command that says hello to LLDB users" + + def __call__(self, debugger, args, exe_ctx, result): + print('Hello ' + args + ', welcome to LLDB', file=result) + return None + + +class TargetnameCommand(object): + + def __init__(self, debugger, session_dict): + pass + + def __call__(self, debugger, args, exe_ctx, result): + target = debugger.GetSelectedTarget() + file = target.GetExecutable() + print('Current target ' + file.GetFilename(), file=result) + if args == 'fail': + result.SetError('a test for error in command') + + def get_flags(self): + return lldb.eCommandRequiresTarget + + +def print_wait_impl(debugger, args, result, dict): + result.SetImmediateOutputFile(sys.stdout) + print('Trying to do long task..', file=result) + import time + time.sleep(1) + print('Still doing long task..', file=result) + time.sleep(1) + print('Done; if you saw the delays I am doing OK', file=result) + + +def check_for_synchro(debugger, args, result, dict): + if debugger.GetAsync(): + print('I am running async', file=result) + if debugger.GetAsync() == False: + print('I am running sync', file=result) + + +def takes_exe_ctx(debugger, args, exe_ctx, result, dict): + print(str(exe_ctx.GetTarget()), file=result) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script_alias/TestCommandScriptAlias.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script_alias/TestCommandScriptAlias.py new file mode 100644 index 00000000000..3f2e8ccec29 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script_alias/TestCommandScriptAlias.py @@ -0,0 +1,35 @@ +""" +Test lldb Python commands. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * + + +class CommandScriptAliasTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_pycmd(self): + self.runCmd("command script import tcsacmd.py") + self.runCmd("command script add -f tcsacmd.some_command_here attach") + + # This is the function to remove the custom commands in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('command script delete attach', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # We don't want to display the stdout if not in TraceOn() mode. + if not self.TraceOn(): + self.HideStdout() + + self.expect('attach a', substrs=['Victory is mine']) + self.runCmd("command script delete attach") + # this can't crash but we don't care whether the actual attach works + self.runCmd('attach noprocessexistswiththisname', check=False) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script_alias/tcsacmd.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script_alias/tcsacmd.py new file mode 100644 index 00000000000..8d3248c2723 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/script_alias/tcsacmd.py @@ -0,0 +1,11 @@ +from __future__ import print_function +import lldb + + +def some_command_here(debugger, command, result, d): + if command == "a": + print("Victory is mine", file=result) + return True + else: + print("Sadness for all", file=result) + return False diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/.lldb b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/.lldb new file mode 100644 index 00000000000..ecbdcff4462 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/.lldb @@ -0,0 +1,2 @@ +# one more level of indirection to stress the command interpreter reentrancy +command source commands.txt diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/TestCommandSource.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/TestCommandSource.py new file mode 100644 index 00000000000..6d2717b16e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/TestCommandSource.py @@ -0,0 +1,34 @@ +""" +Test that lldb command "command source" works correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CommandSourceTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_command_source(self): + """Test that lldb command "command source" works correctly.""" + + # Sourcing .lldb in the current working directory, which in turn imports + # the "my" package that defines the date() function. + self.runCmd("command source .lldb") + + # Python should evaluate "my.date()" successfully. + command_interpreter = self.dbg.GetCommandInterpreter() + self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER) + result = lldb.SBCommandReturnObject() + command_interpreter.HandleCommand("script my.date()", result) + + import datetime + self.expect(result.GetOutput(), "script my.date() runs successfully", + exe=False, + substrs=[str(datetime.date.today())]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/commands.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/commands.txt new file mode 100644 index 00000000000..8e4de66d469 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/commands.txt @@ -0,0 +1,2 @@ +script import my +p 1 + 1 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/my.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/my.py new file mode 100644 index 00000000000..bd97fda3cbb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/command/source/my.py @@ -0,0 +1,7 @@ +from __future__ import print_function + + +def date(): + import datetime + today = datetime.date.today() + print(today) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/TestDisassembleBreakpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/TestDisassembleBreakpoint.py new file mode 100644 index 00000000000..4130aae9621 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/TestDisassembleBreakpoint.py @@ -0,0 +1,38 @@ +""" +Test some lldb command abbreviations. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DisassemblyTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test(self): + self.build() + target, _, _, bkpt = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", lldb.SBFileSpec("main.cpp")) + self.runCmd("dis -f") + disassembly_with_break = self.res.GetOutput().splitlines() + + self.assertTrue(target.BreakpointDelete(bkpt.GetID())) + + self.runCmd("dis -f") + disassembly_without_break = self.res.GetOutput().splitlines() + + # Make sure all assembly instructions are the same as instructions + # with the breakpoint removed. + self.assertEqual(len(disassembly_with_break), + len(disassembly_without_break)) + for dis_inst_with, dis_inst_without in \ + zip(disassembly_with_break, disassembly_without_break): + inst_with = dis_inst_with.split(':')[-1] + inst_without = dis_inst_without.split(':')[-1] + self.assertEqual(inst_with, inst_without) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/TestFrameDisassemble.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/TestFrameDisassemble.py new file mode 100644 index 00000000000..66f7891d9a8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/TestFrameDisassemble.py @@ -0,0 +1,60 @@ +""" +Test to ensure SBFrame::Disassemble produces SOME output +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class FrameDisassembleTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test_frame_disassemble(self): + """Sample test to ensure SBFrame::Disassemble produces SOME output.""" + self.build() + self.frame_disassemble_test() + + def frame_disassemble_test(self): + """Sample test to ensure SBFrame::Disassemble produces SOME output""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint in main.c at the source matching + # "Set a breakpoint here" + breakpoint = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here", lldb.SBFileSpec("main.cpp")) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + error = lldb.SBError() + # This is the launch info. If you want to launch with arguments or + # environment variables, add them using SetArguments or + # SetEnvironmentEntries + + launch_info = lldb.SBLaunchInfo(None) + process = target.Launch(launch_info, error) + self.assertTrue(process, PROCESS_IS_VALID) + + # Did we hit our breakpoint? + from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) + self.assertTrue( + len(threads) == 1, + "There should be a thread stopped at our breakpoint") + + # The hit count for the breakpoint should be 1. + self.assertTrue(breakpoint.GetHitCount() == 1) + + frame = threads[0].GetFrameAtIndex(0) + disassembly = frame.Disassemble() + self.assertTrue(len(disassembly) != 0, "Disassembly was empty.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/main.cpp new file mode 100644 index 00000000000..93d4b1cbd39 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/disassemble/basic/main.cpp @@ -0,0 +1,27 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int +sum (int a, int b) +{ + int result = a + b; // Set a breakpoint here + return result; +} + +int +main(int argc, char const *argv[]) +{ + + int array[3]; + + array[0] = sum (1238, 78392); + array[1] = sum (379265, 23674); + array[2] = sum (872934, 234); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/.categories new file mode 100644 index 00000000000..897e40a99dd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/.categories @@ -0,0 +1 @@ +expression diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/anonymous-struct/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/anonymous-struct/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/anonymous-struct/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/anonymous-struct/TestCallUserAnonTypedef.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/anonymous-struct/TestCallUserAnonTypedef.py new file mode 100644 index 00000000000..d53fc522078 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/anonymous-struct/TestCallUserAnonTypedef.py @@ -0,0 +1,44 @@ +""" +Test calling user defined functions using expression evaluation. +This test checks that typesystem lookup works correctly for typedefs of +untagged structures. + +Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790 +""" + + +import lldb + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestExprLookupAnonStructTypedef(TestBase): + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + # Find the breakpoint + self.line = line_number('main.cpp', '// lldb testsuite break') + + @expectedFailureAll( + oslist=['linux'], + archs=['arm'], + bugnumber="llvm.org/pr27868") + def test(self): + """Test typedeffed untagged struct arguments for function call expressions""" + self.build() + + self.runCmd("file "+self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line, + num_expected_locations=-1, + loc_exact=True + ) + + self.runCmd("run", RUN_SUCCEEDED) + self.expect("expr multiply(&s)", substrs=['$0 = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/anonymous-struct/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/anonymous-struct/main.cpp new file mode 100644 index 00000000000..5b170c5f943 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/anonymous-struct/main.cpp @@ -0,0 +1,26 @@ +#include <tgmath.h> + +typedef struct { + float f; + int i; +} my_untagged_struct; + +double multiply(my_untagged_struct *s) +{ + return s->f * s->i; +} + +double multiply(my_untagged_struct *s, int x) +{ + return multiply(s) * x; +} + +int main(int argc, char **argv) +{ + my_untagged_struct s = { + .f = (float)argc, + .i = argc, + }; + // lldb testsuite break + return !(multiply(&s, argc) == pow(argc, 3)); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/argument_passing_restrictions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/argument_passing_restrictions/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/argument_passing_restrictions/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/argument_passing_restrictions/TestArgumentPassingRestrictions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/argument_passing_restrictions/TestArgumentPassingRestrictions.py new file mode 100644 index 00000000000..858f2785be8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/argument_passing_restrictions/TestArgumentPassingRestrictions.py @@ -0,0 +1,33 @@ +""" +This is a test to ensure that both lldb is reconstructing the right +calling convention for a CXXRecordDecl as represented by: + + DW_CC_pass_by_reference + DW_CC_pass_by_value + +and to also make sure that the ASTImporter is copying over this +setting when importing the CXXRecordDecl via setArgPassingRestrictions. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestArgumentPassingRestrictions(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(compiler="clang", compiler_version=['<', '7.0']) + def test_argument_passing_restrictions(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp")) + + self.expect("expr returnPassByRef()", + substrs=['(PassByRef)', '= 11223344']) + + self.expect("expr takePassByRef(p)", + substrs=['(int)', '= 42']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/argument_passing_restrictions/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/argument_passing_restrictions/main.cpp new file mode 100644 index 00000000000..4b3b6950455 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/argument_passing_restrictions/main.cpp @@ -0,0 +1,19 @@ +// This structure has a non-trivial copy constructor so +// it needs to be passed by reference. +struct PassByRef { + PassByRef() = default; + PassByRef(const PassByRef &p){x = p.x;}; + + int x = 11223344; +}; + +PassByRef returnPassByRef() { return PassByRef(); } +int takePassByRef(PassByRef p) { + return p.x; +} + +int main() { + PassByRef p = returnPassByRef(); + p.x = 42; + return takePassByRef(p); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/calculator_mode/TestCalculatorMode.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/calculator_mode/TestCalculatorMode.py new file mode 100644 index 00000000000..9cd3c817047 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/calculator_mode/TestCalculatorMode.py @@ -0,0 +1,23 @@ +""" +Test calling an expression without a target. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestCalculatorMode(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test__calculator_mode(self): + """Test calling expressions in the dummy target.""" + self.expect("expression 11 + 22", "11 + 22 didn't get the expected result", substrs=["33"]) + # Now try it with a specific language: + self.expect("expression -l c -- 11 + 22", "11 + 22 didn't get the expected result", substrs=["33"]) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/Makefile new file mode 100644 index 00000000000..31f2d5e8fc2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules + +clean:: + rm -rf $(wildcard *.o *.d *.dSYM) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallBuiltinFunction.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallBuiltinFunction.py new file mode 100644 index 00000000000..44627990d2f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallBuiltinFunction.py @@ -0,0 +1,45 @@ +""" +Tests calling builtin functions using expression evaluation. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCommandCallBuiltinFunction(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # Builtins are expanded by Clang, so debug info shouldn't matter. + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number( + 'main.cpp', + '// Please test these expressions while stopped at this line:') + + def test(self): + self.build() + + # Set breakpoint in main and run exe + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + + # Test different builtin functions. + + self.expect_expr("__builtin_isinf(0.0f)", result_type="int", result_value="0") + self.expect_expr("__builtin_isnormal(0.0f)", result_type="int", result_value="0") + self.expect_expr("__builtin_constant_p(1)", result_type="int", result_value="1") + self.expect_expr("__builtin_abs(-14)", result_type="int", result_value="14") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallStdStringFunction.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallStdStringFunction.py new file mode 100644 index 00000000000..261e702fa59 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallStdStringFunction.py @@ -0,0 +1,56 @@ +""" +Test calling std::String member functions. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCommandCallFunctionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number( + 'main.cpp', + '// Please test these expressions while stopped at this line:') + + @expectedFailureAll( + compiler="icc", + bugnumber="llvm.org/pr14437, fails with ICC 13.1") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") + def test_with(self): + """Test calling std::String member function.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + + # Some versions of GCC encode two locations for the 'return' statement + # in main.cpp + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + self.expect("print str", + substrs=['Hello world']) + + # Calling this function now succeeds, but we follow the typedef return type through to + # const char *, and thus don't invoke the Summary formatter. + + # clang's libstdc++ on ios arm64 inlines std::string::c_str() always; + # skip this part of the test. + triple = self.dbg.GetSelectedPlatform().GetTriple() + do_cstr_test = True + if triple in ["arm64-apple-ios", "arm64e-apple-ios", "arm64-apple-tvos", "armv7k-apple-watchos", "arm64-apple-bridgeos", "arm64_32-apple-watchos"]: + do_cstr_test = False + if do_cstr_test: + self.expect("print str.c_str()", + substrs=['Hello world']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallStopAndContinue.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallStopAndContinue.py new file mode 100644 index 00000000000..0f0f1a54e31 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallStopAndContinue.py @@ -0,0 +1,52 @@ +""" +Test calling a function, stopping in the call, continue and gather the result on stop. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCommandCallStopContinueTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number( + 'main.cpp', + '// Please test these expressions while stopped at this line:') + self.func_line = line_number('main.cpp', '{5, "five"}') + + def test(self): + """Test gathering result from interrupted function call.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + # Some versions of GCC encode two locations for the 'return' statement + # in main.cpp + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.func_line, + num_expected_locations=-1, + loc_exact=True) + + self.expect("expr -i false -- returnsFive()", error=True, + substrs=['Execution was interrupted, reason: breakpoint']) + + self.runCmd("continue", "Continue completed") + self.expect( + "thread list", + substrs=[ + 'stop reason = User Expression thread plan', + r'Completed expression: (Five) $0 = (number = 5, name = "five")']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallUserDefinedFunction.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallUserDefinedFunction.py new file mode 100644 index 00000000000..8ced082680d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/TestCallUserDefinedFunction.py @@ -0,0 +1,57 @@ +""" +Test calling user defined functions using expression evaluation. + +Note: + LLDBs current first choice of evaluating functions is using the IR interpreter, + which is only supported on Hexagon. Otherwise JIT is used for the evaluation. + +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCommandCallUserDefinedFunction(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number( + 'main.cpp', + '// Please test these expressions while stopped at this line:') + + def test(self): + """Test return values of user defined function calls.""" + self.build() + + # Set breakpoint in main and run exe + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # Test recursive function call. + self.expect("expr fib(5)", substrs=['$0 = 5']) + + # Test function with more than one paramter + self.expect("expr add(4,8)", substrs=['$1 = 12']) + + # Test nesting function calls in function paramters + self.expect("expr add(add(5,2),add(3,4))", substrs=['$2 = 14']) + self.expect("expr add(add(5,2),fib(5))", substrs=['$3 = 12']) + + # Test function with pointer paramter + self.expect( + "exp stringCompare((const char*) \"Hello world\")", + substrs=['$4 = true']) + self.expect( + "exp stringCompare((const char*) \"Hellworld\")", + substrs=['$5 = false']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/main.cpp new file mode 100644 index 00000000000..cc5f52dbf56 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-function/main.cpp @@ -0,0 +1,53 @@ +#include <iostream> +#include <string> +#include <cstring> + +struct Five +{ + int number; + const char *name; +}; + +Five +returnsFive() +{ + Five my_five = {5, "five"}; + return my_five; +} + +unsigned int +fib(unsigned int n) +{ + if (n < 2) + return n; + else + return fib(n - 1) + fib(n - 2); +} + +int +add(int a, int b) +{ + return a + b; +} + +bool +stringCompare(const char *str) +{ + if (strcmp( str, "Hello world" ) == 0) + return true; + else + return false; +} + +int main (int argc, char const *argv[]) +{ + std::string str = "Hello world"; + std::cout << str << std::endl; + std::cout << str.c_str() << std::endl; + Five main_five = returnsFive(); +#if 0 + print str + print str.c_str() +#endif + return 0; // Please test these expressions while stopped at this line: +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-overridden-method/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-overridden-method/Makefile new file mode 100644 index 00000000000..31f2d5e8fc2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-overridden-method/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules + +clean:: + rm -rf $(wildcard *.o *.d *.dSYM) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-overridden-method/TestCallOverriddenMethod.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-overridden-method/TestCallOverriddenMethod.py new file mode 100644 index 00000000000..57987c8cb36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-overridden-method/TestCallOverriddenMethod.py @@ -0,0 +1,82 @@ +""" +Test calling an overriden method. + +Note: + This verifies that LLDB is correctly building the method overrides table. + If this table is not built correctly then calls to overridden methods in + derived classes may generate references to non-existant vtable entries, + as the compiler treats the overridden method as a totally new virtual + method definition. + <rdar://problem/14205774> + +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class ExprCommandCallOverriddenMethod(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number('main.cpp', '// Set breakpoint here') + + def test_call_on_base(self): + """Test calls to overridden methods in derived classes.""" + self.build() + + # Set breakpoint in main and run exe + self.runCmd("file " + self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # Test call to method in base class (this should always work as the base + # class method is never an override). + self.expect("expr b->foo()", substrs=["= 2"]) + + # Test calling the base class. + self.expect("expr realbase.foo()", substrs=["= 1"]) + + @skipIfLinux # Returns wrong result code on some platforms. + def test_call_on_derived(self): + """Test calls to overridden methods in derived classes.""" + self.build() + + # Set breakpoint in main and run exe + self.runCmd("file " + self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # Test call to overridden method in derived class (this will fail if the + # overrides table is not correctly set up, as Derived::foo will be assigned + # a vtable entry that does not exist in the compiled program). + self.expect("expr d.foo()", substrs=["= 2"]) + + @skipIf(oslist=["linux"], archs=["aarch64"]) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr43707") + def test_call_on_temporary(self): + """Test calls to overridden methods in derived classes.""" + self.build() + + # Set breakpoint in main and run exe + self.runCmd("file " + self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # Test with locally constructed instances. + self.expect("expr Base().foo()", substrs=["= 1"]) + self.expect("expr Derived().foo()", substrs=["= 2"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-overridden-method/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-overridden-method/main.cpp new file mode 100644 index 00000000000..87997fa354c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-overridden-method/main.cpp @@ -0,0 +1,18 @@ +class Base { +public: + virtual ~Base() {} + virtual int foo() { return 1; } +}; + +class Derived : public Base { +public: + virtual int foo() { return 2; } +}; + +int main() { + Base realbase; + realbase.foo(); + Derived d; + Base *b = &d; + return 0; // Set breakpoint here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-restarts/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-restarts/Makefile new file mode 100644 index 00000000000..fa5901ebca1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-restarts/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := lotta-signals.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-restarts/TestCallThatRestarts.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-restarts/TestCallThatRestarts.py new file mode 100644 index 00000000000..a61e69a1476 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-restarts/TestCallThatRestarts.py @@ -0,0 +1,166 @@ +""" +Test calling a function that hits a signal set to auto-restart, make sure the call completes. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCommandThatRestartsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.main_source = "lotta-signals.c" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + @skipIfFreeBSD # llvm.org/pr19246: intermittent failure + @skipIfDarwin # llvm.org/pr19246: intermittent failure + @skipIfWindows # Test relies on signals, unsupported on Windows + @expectedFlakeyAndroid(bugnumber="llvm.org/pr19246") + @expectedFailureNetBSD + def test(self): + """Test calling function that hits a signal and restarts.""" + self.build() + self.call_function() + + def check_after_call(self, num_sigchld): + after_call = self.sigchld_no.GetValueAsSigned(-1) + self.assertTrue( + after_call - + self.start_sigchld_no == num_sigchld, + "Really got %d SIGCHLD signals through the call." % + (num_sigchld)) + self.start_sigchld_no = after_call + + # Check that we are back where we were before: + frame = self.thread.GetFrameAtIndex(0) + self.assertTrue( + self.orig_frame_pc == frame.GetPC(), + "Restored the zeroth frame correctly") + + def call_function(self): + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + 'Stop here in main.', self.main_source_spec) + + # Make sure the SIGCHLD behavior is pass/no-stop/no-notify: + return_obj = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle SIGCHLD -s 0 -p 1 -n 0", return_obj) + self.assertTrue(return_obj.Succeeded(), "Set SIGCHLD to pass, no-stop") + + # The sigchld_no variable should be 0 at this point. + self.sigchld_no = target.FindFirstGlobalVariable("sigchld_no") + self.assertTrue( + self.sigchld_no.IsValid(), + "Got a value for sigchld_no") + + self.start_sigchld_no = self.sigchld_no.GetValueAsSigned(-1) + self.assertTrue( + self.start_sigchld_no != -1, + "Got an actual value for sigchld_no") + + options = lldb.SBExpressionOptions() + # processing 30 signals takes a while, increase the expression timeout + # a bit + options.SetTimeoutInMicroSeconds(3000000) # 3s + options.SetUnwindOnError(True) + + frame = self.thread.GetFrameAtIndex(0) + # Store away the PC to check that the functions unwind to the right + # place after calls + self.orig_frame_pc = frame.GetPC() + + num_sigchld = 30 + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsSigned(-1) == num_sigchld) + + self.check_after_call(num_sigchld) + + # Okay, now try with a breakpoint in the called code in the case where + # we are ignoring breakpoint hits. + handler_bkpt = target.BreakpointCreateBySourceRegex( + "Got sigchld %d.", self.main_source_spec) + self.assertTrue(handler_bkpt.GetNumLocations() > 0) + options.SetIgnoreBreakpoints(True) + options.SetUnwindOnError(True) + + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) + + self.assertTrue(value.IsValid() and value.GetError().Success()) + self.assertTrue(value.GetValueAsSigned(-1) == num_sigchld) + self.check_after_call(num_sigchld) + + # Now set the signal to print but not stop and make sure that calling + # still works: + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle SIGCHLD -s 0 -p 1 -n 1", return_obj) + self.assertTrue( + return_obj.Succeeded(), + "Set SIGCHLD to pass, no-stop, notify") + + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) + + self.assertTrue(value.IsValid() and value.GetError().Success()) + self.assertTrue(value.GetValueAsSigned(-1) == num_sigchld) + self.check_after_call(num_sigchld) + + # Now set this unwind on error to false, and make sure that we still + # complete the call: + options.SetUnwindOnError(False) + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) + + self.assertTrue(value.IsValid() and value.GetError().Success()) + self.assertTrue(value.GetValueAsSigned(-1) == num_sigchld) + self.check_after_call(num_sigchld) + + # Okay, now set UnwindOnError to true, and then make the signal behavior to stop + # and see that now we do stop at the signal point: + + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle SIGCHLD -s 1 -p 1 -n 1", return_obj) + self.assertTrue( + return_obj.Succeeded(), + "Set SIGCHLD to pass, stop, notify") + + value = frame.EvaluateExpression( + "call_me (%d)" % + (num_sigchld), options) + self.assertTrue( + value.IsValid() and value.GetError().Success() == False) + + # Set signal handling back to no-stop, and continue and we should end + # up back in out starting frame: + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle SIGCHLD -s 0 -p 1 -n 1", return_obj) + self.assertTrue( + return_obj.Succeeded(), + "Set SIGCHLD to pass, no-stop, notify") + + error = process.Continue() + self.assertTrue( + error.Success(), + "Continuing after stopping for signal succeeds.") + + frame = self.thread.GetFrameAtIndex(0) + self.assertTrue( + frame.GetPC() == self.orig_frame_pc, + "Continuing returned to the place we started.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-restarts/lotta-signals.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-restarts/lotta-signals.c new file mode 100644 index 00000000000..f5c15b41e2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-restarts/lotta-signals.c @@ -0,0 +1,61 @@ +#include <unistd.h> +#include <stdio.h> +#include <signal.h> + +static int sigchld_no; +static int nosig_no; +static int weird_value; + +void +sigchld_handler (int signo) +{ + sigchld_no++; + printf ("Got sigchld %d.\n", sigchld_no); +} + +int +call_me (int some_value) +{ + int ret_val = 0; + int i; + for (i = 0; i < some_value; i++) + { + int result = 0; + if (i%2 == 0) + result = kill (getpid(), SIGCHLD); + else + sigchld_no++; + + usleep(1000); + if (result == 0) + ret_val++; + } + usleep (10000); + return ret_val; +} + +int +call_me_nosig (int some_value) +{ + int ret_val = 0; + int i; + for (i = 0; i < some_value; i++) + weird_value += i % 4; + + nosig_no += some_value; + return some_value; +} + +int +main () +{ + int ret_val; + signal (SIGCHLD, sigchld_handler); + + ret_val = call_me (2); // Stop here in main. + + ret_val = call_me_nosig (10); + + return 0; + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-throws/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-throws/Makefile new file mode 100644 index 00000000000..becb2f09658 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-throws/Makefile @@ -0,0 +1,3 @@ +OBJC_SOURCES := call-throws.m +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-throws/TestCallThatThrows.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-throws/TestCallThatThrows.py new file mode 100644 index 00000000000..fea56f1bb5b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-throws/TestCallThatThrows.py @@ -0,0 +1,103 @@ +""" +Test calling a function that throws an ObjC exception, make sure that it doesn't propagate the exception. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCommandWithThrowTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.main_source = "call-throws.m" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + @skipUnlessDarwin + def test(self): + """Test calling a function that throws and ObjC exception.""" + self.build() + self.call_function() + + def check_after_call(self): + # Check that we are back where we were before: + frame = self.thread.GetFrameAtIndex(0) + self.assertTrue( + self.orig_frame_pc == frame.GetPC(), + "Restored the zeroth frame correctly") + + def call_function(self): + """Test calling function that throws.""" + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + 'I am about to throw.', self.main_source_spec) + + options = lldb.SBExpressionOptions() + options.SetUnwindOnError(True) + + frame = self.thread.GetFrameAtIndex(0) + # Store away the PC to check that the functions unwind to the right + # place after calls + self.orig_frame_pc = frame.GetPC() + + value = frame.EvaluateExpression("[my_class callMeIThrow]", options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success() == False) + + self.check_after_call() + + # Okay, now try with a breakpoint in the called code in the case where + # we are ignoring breakpoint hits. + handler_bkpt = target.BreakpointCreateBySourceRegex( + "I felt like it", self.main_source_spec) + self.assertTrue(handler_bkpt.GetNumLocations() > 0) + options.SetIgnoreBreakpoints(True) + options.SetUnwindOnError(True) + + value = frame.EvaluateExpression("[my_class callMeIThrow]", options) + + self.assertTrue( + value.IsValid() and value.GetError().Success() == False) + self.check_after_call() + + # Now set the ObjC language breakpoint and make sure that doesn't + # interfere with the call: + exception_bkpt = target.BreakpointCreateForException( + lldb.eLanguageTypeObjC, False, True) + self.assertTrue(exception_bkpt.GetNumLocations() > 0) + + options.SetIgnoreBreakpoints(True) + options.SetUnwindOnError(True) + + value = frame.EvaluateExpression("[my_class callMeIThrow]", options) + + self.assertTrue( + value.IsValid() and value.GetError().Success() == False) + self.check_after_call() + + # Now turn off exception trapping, and call a function that catches the exceptions, + # and make sure the function actually completes, and we get the right + # value: + options.SetTrapExceptions(False) + value = frame.EvaluateExpression("[my_class iCatchMyself]", options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsUnsigned() == 57) + self.check_after_call() + options.SetTrapExceptions(True) + + # Now set this unwind on error to false, and make sure that we stop + # where the exception was thrown + options.SetUnwindOnError(False) + value = frame.EvaluateExpression("[my_class callMeIThrow]", options) + + self.assertTrue( + value.IsValid() and value.GetError().Success() == False) + self.check_after_call() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-throws/call-throws.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-throws/call-throws.m new file mode 100644 index 00000000000..a184718be7d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/call-throws/call-throws.m @@ -0,0 +1,47 @@ +#import <Foundation/Foundation.h> + +@interface MyClass : NSObject +{ +} +- (int) callMeIThrow; +- (int) iCatchMyself; +@end + +@implementation MyClass +- (int) callMeIThrow +{ + NSException *e = [NSException + exceptionWithName:@"JustForTheHeckOfItException" + reason:@"I felt like it" + userInfo:nil]; + @throw e; + return 56; +} + +- (int) iCatchMyself +{ + int return_value = 55; + @try + { + return_value = [self callMeIThrow]; + } + @catch (NSException *e) + { + return_value = 57; + } + return return_value; +} +@end + +int +main () +{ + int return_value; + MyClass *my_class = [[MyClass alloc] init]; + + NSLog (@"I am about to throw."); + + return_value = [my_class iCatchMyself]; + + return return_value; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/cast_int_to_anonymous_enum/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/cast_int_to_anonymous_enum/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/cast_int_to_anonymous_enum/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/cast_int_to_anonymous_enum/TestCastIntToAnonymousEnum.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/cast_int_to_anonymous_enum/TestCastIntToAnonymousEnum.py new file mode 100644 index 00000000000..b8eaf51d3e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/cast_int_to_anonymous_enum/TestCastIntToAnonymousEnum.py @@ -0,0 +1,22 @@ +""" +Test Expression Parser regression text to ensure that we handle anonymous +enums importing correctly. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestCastIntToAnonymousEnum(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_cast_int_to_anonymous_enum(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + self.expect("expr (flow_e)0", substrs=['(flow_e) $0 = A']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/cast_int_to_anonymous_enum/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/cast_int_to_anonymous_enum/main.cpp new file mode 100644 index 00000000000..7ae4c1735db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/cast_int_to_anonymous_enum/main.cpp @@ -0,0 +1,9 @@ +enum flow_e { + A=0, +}; + +int main() { + flow_e f; + + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/char/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/char/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/char/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/char/TestExprsChar.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/char/TestExprsChar.py new file mode 100644 index 00000000000..f1fa7805384 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/char/TestExprsChar.py @@ -0,0 +1,68 @@ + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCharTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + def do_test(self, dictionary=None): + """These basic expression commands should work as expected.""" + self.build(dictionary=dictionary) + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + '// Break here', self.main_source_spec) + frame = thread.GetFrameAtIndex(0) + + value = frame.EvaluateExpression("foo(c)") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(0), 1) + + value = frame.EvaluateExpression("foo(sc)") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(0), 2) + + value = frame.EvaluateExpression("foo(uc)") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(0), 3) + + def test_default_char(self): + self.do_test() + + @expectedFailureAll( + archs=[ + "arm", + "aarch64", + "powerpc64le", + "s390x"], + bugnumber="llvm.org/pr23069") + def test_signed_char(self): + self.do_test(dictionary={'CFLAGS_EXTRAS': '-fsigned-char'}) + + @expectedFailureAll( + archs=[ + "i[3-6]86", + "x86_64", + "arm64", + 'arm64e', + 'armv7', + 'armv7k', + 'arm64_32'], + bugnumber="llvm.org/pr23069, <rdar://problem/28721938>") + @expectedFailureAll(triple='mips*', bugnumber="llvm.org/pr23069") + def test_unsigned_char(self): + self.do_test(dictionary={'CFLAGS_EXTRAS': '-funsigned-char'}) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/char/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/char/main.cpp new file mode 100644 index 00000000000..c8b0beb1b35 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/char/main.cpp @@ -0,0 +1,10 @@ +int foo(char c) { return 1; } +int foo(signed char c) { return 2; } +int foo(unsigned char c) { return 3; } + +int main() { + char c = 0; + signed char sc = 0; + unsigned char uc = 0; + return 0; // Break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/class_template_specialization_empty_pack/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/class_template_specialization_empty_pack/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/class_template_specialization_empty_pack/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/class_template_specialization_empty_pack/TestClassTemplateSpecializationParametersHandling.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/class_template_specialization_empty_pack/TestClassTemplateSpecializationParametersHandling.py new file mode 100644 index 00000000000..d1974d05a24 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/class_template_specialization_empty_pack/TestClassTemplateSpecializationParametersHandling.py @@ -0,0 +1,23 @@ +""" +Test Expression Parser code gen for ClassTemplateSpecializationDecl to insure +that we generate a TemplateTypeParmDecl in the TemplateParameterList for empty +variadic packs. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestClassTemplateSpecializationParametersHandling(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_class_template_specialization(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + self.expect("expr -u 0 -- b.foo()", substrs=['$0 = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/class_template_specialization_empty_pack/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/class_template_specialization_empty_pack/main.cpp new file mode 100644 index 00000000000..bc831604aed --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/class_template_specialization_empty_pack/main.cpp @@ -0,0 +1,9 @@ +template <typename N, class... P> +struct A { + int foo() { return 1;} +}; + +int main() { + A<int> b; + return b.foo(); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/codegen-crash-typedefdecl-not-in_declcontext/TestCodegenCrashTypedefDeclNotInDeclContext.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/codegen-crash-typedefdecl-not-in_declcontext/TestCodegenCrashTypedefDeclNotInDeclContext.py new file mode 100644 index 00000000000..f08c0dcbda9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/codegen-crash-typedefdecl-not-in_declcontext/TestCodegenCrashTypedefDeclNotInDeclContext.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), []) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/codegen-crash-typedefdecl-not-in_declcontext/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/codegen-crash-typedefdecl-not-in_declcontext/main.cpp new file mode 100644 index 00000000000..e4f6600eab2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/codegen-crash-typedefdecl-not-in_declcontext/main.cpp @@ -0,0 +1,39 @@ +// This is a reproducer for a crash in codegen. It happens when we have a +// RecordDecl used in an expression and one of the FieldDecl are not complete. +// This case happens when: +// - A RecordDecl (E) has a FieldDecl which is a reference member variable +// - The underlying type of the FieldDec is a TypedefDecl +// - The typedef refers to a ClassTemplateSpecialization (DWrapper) +// - The typedef is not present in the DeclContext of B +// - The typedef shows up as a return value of a member function of E (f()) +template <typename T> struct DWrapper {}; + +struct D {}; + +namespace NS { +typedef DWrapper<D> DW; +} + +struct B { + NS::DW spd; + int a = 0; +}; + +struct E { + E(B &b) : b_ref(b) {} + NS::DW f() { return {}; }; + void g() { + return; //%self.expect("p b_ref", substrs=['(B) $0 =', '(spd = NS::DW', 'a = 0)']) + } + + B &b_ref; +}; + +int main() { + B b; + E e(b); + + e.g(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash-incomplete-record/TestCompletionCrashIncompleteRecord.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash-incomplete-record/TestCompletionCrashIncompleteRecord.py new file mode 100644 index 00000000000..f08c0dcbda9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash-incomplete-record/TestCompletionCrashIncompleteRecord.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), []) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash-incomplete-record/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash-incomplete-record/main.cpp new file mode 100644 index 00000000000..f7ca83c6540 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash-incomplete-record/main.cpp @@ -0,0 +1,11 @@ +int i; +struct F { + int &r; + F() : r(i) {} +}; +template <class T> struct unique_ptr { + F i; + unique_ptr() : i() {//%self.dbg.GetCommandInterpreter().HandleCompletion("e ", len("e "), 0, -1, lldb.SBStringList()) +} +}; +int main() {unique_ptr<F> u; } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash1/TestCompletionCrash1.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash1/TestCompletionCrash1.py new file mode 100644 index 00000000000..3f2a6100607 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash1/TestCompletionCrash1.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), [decorators.skipIf(bugnumber="rdar://53659341")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash1/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash1/main.cpp new file mode 100644 index 00000000000..7b123c0662d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-crash1/main.cpp @@ -0,0 +1,12 @@ +namespace std { +struct a { + a() {} + a(a &&); +}; +template <class> struct au { + a ay; + ~au() { //%self.dbg.GetCommandInterpreter().HandleCompletion("e ", len("e "), 0, -1, lldb.SBStringList()) + } +}; +} +int main() { std::au<int>{}; } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-in-lambda-and-unnamed-class/TestCompletionInLambdaAndUnnamedClass.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-in-lambda-and-unnamed-class/TestCompletionInLambdaAndUnnamedClass.py new file mode 100644 index 00000000000..57fb94b6d66 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-in-lambda-and-unnamed-class/TestCompletionInLambdaAndUnnamedClass.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(),) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-in-lambda-and-unnamed-class/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-in-lambda-and-unnamed-class/main.cpp new file mode 100644 index 00000000000..a3d8ab6532e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion-in-lambda-and-unnamed-class/main.cpp @@ -0,0 +1,11 @@ +int main() { + []() + { //%self.dbg.GetCommandInterpreter().HandleCompletion("e ", len("e "), 0, -1, lldb.SBStringList()) + } + (); + struct { + void f() + { //%self.dbg.GetCommandInterpreter().HandleCompletion("e ", len("e "), 0, -1, lldb.SBStringList()) + } + } A; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/.categories new file mode 100644 index 00000000000..3a3f4df6416 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/.categories @@ -0,0 +1 @@ +cmdline diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/Makefile new file mode 100644 index 00000000000..020dce7c31d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp other.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/TestExprCompletion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/TestExprCompletion.py new file mode 100644 index 00000000000..5266266b6ab --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/TestExprCompletion.py @@ -0,0 +1,254 @@ +""" +Test the lldb command line completion mechanism for the 'expr' command. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbplatform +from lldbsuite.test import lldbutil + +class CommandLineExprCompletionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test_expr_completion(self): + self.build() + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + + # Try the completion before we have a context to complete on. + self.assume_no_completions('expr some_expr') + self.assume_no_completions('expr ') + self.assume_no_completions('expr f') + + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + '// Break here', self.main_source_spec) + + # Completing member functions + self.complete_exactly('expr some_expr.FooNoArgs', + 'expr some_expr.FooNoArgsBar()') + self.complete_exactly('expr some_expr.FooWithArgs', + 'expr some_expr.FooWithArgsBar(') + self.complete_exactly('expr some_expr.FooWithMultipleArgs', + 'expr some_expr.FooWithMultipleArgsBar(') + self.complete_exactly('expr some_expr.FooUnderscore', + 'expr some_expr.FooUnderscoreBar_()') + self.complete_exactly('expr some_expr.FooNumbers', + 'expr some_expr.FooNumbersBar1()') + self.complete_exactly('expr some_expr.StaticMemberMethod', + 'expr some_expr.StaticMemberMethodBar()') + + # Completing static functions + self.complete_exactly('expr Expr::StaticMemberMethod', + 'expr Expr::StaticMemberMethodBar()') + + # Completing member variables + self.complete_exactly('expr some_expr.MemberVariab', + 'expr some_expr.MemberVariableBar') + + # Multiple completions + self.completions_contain('expr some_expr.', + ['some_expr.FooNumbersBar1()', + 'some_expr.FooUnderscoreBar_()', + 'some_expr.FooWithArgsBar(', + 'some_expr.MemberVariableBar']) + + self.completions_contain('expr some_expr.Foo', + ['some_expr.FooNumbersBar1()', + 'some_expr.FooUnderscoreBar_()', + 'some_expr.FooWithArgsBar(']) + + self.completions_contain('expr ', + ['static_cast', + 'reinterpret_cast', + 'dynamic_cast']) + + self.completions_contain('expr 1 + ', + ['static_cast', + 'reinterpret_cast', + 'dynamic_cast']) + + # Completion expr without spaces + # This is a bit awkward looking for the user, but that's how + # the completion API works at the moment. + self.completions_contain('expr 1+', + ['1+some_expr', "1+static_cast"]) + + # Test with spaces + self.complete_exactly('expr some_expr .FooNoArgs', + 'expr some_expr .FooNoArgsBar()') + self.complete_exactly('expr some_expr .FooNoArgs', + 'expr some_expr .FooNoArgsBar()') + self.complete_exactly('expr some_expr .FooNoArgs', + 'expr some_expr .FooNoArgsBar()') + self.complete_exactly('expr some_expr. FooNoArgs', + 'expr some_expr. FooNoArgsBar()') + self.complete_exactly('expr some_expr . FooNoArgs', + 'expr some_expr . FooNoArgsBar()') + self.complete_exactly('expr Expr :: StaticMemberMethod', + 'expr Expr :: StaticMemberMethodBar()') + self.complete_exactly('expr Expr ::StaticMemberMethod', + 'expr Expr ::StaticMemberMethodBar()') + self.complete_exactly('expr Expr:: StaticMemberMethod', + 'expr Expr:: StaticMemberMethodBar()') + + # Test that string literals don't break our parsing logic. + self.complete_exactly('expr const char *cstr = "some_e"; char c = *cst', + 'expr const char *cstr = "some_e"; char c = *cstr') + self.complete_exactly('expr const char *cstr = "some_e" ; char c = *cst', + 'expr const char *cstr = "some_e" ; char c = *cstr') + # Requesting completions inside an incomplete string doesn't provide any + # completions. + self.complete_exactly('expr const char *cstr = "some_e', + 'expr const char *cstr = "some_e') + + # Completing inside double dash should do nothing + self.assume_no_completions('expr -i0 -- some_expr.', 10) + self.assume_no_completions('expr -i0 -- some_expr.', 11) + + # Test with expr arguments + self.complete_exactly('expr -i0 -- some_expr .FooNoArgs', + 'expr -i0 -- some_expr .FooNoArgsBar()') + self.complete_exactly('expr -i0 -- some_expr .FooNoArgs', + 'expr -i0 -- some_expr .FooNoArgsBar()') + + # Addrof and deref + self.complete_exactly('expr (*(&some_expr)).FooNoArgs', + 'expr (*(&some_expr)).FooNoArgsBar()') + self.complete_exactly('expr (*(&some_expr)) .FooNoArgs', + 'expr (*(&some_expr)) .FooNoArgsBar()') + self.complete_exactly('expr (* (&some_expr)) .FooNoArgs', + 'expr (* (&some_expr)) .FooNoArgsBar()') + self.complete_exactly('expr (* (& some_expr)) .FooNoArgs', + 'expr (* (& some_expr)) .FooNoArgsBar()') + + # Addrof and deref (part 2) + self.complete_exactly('expr (&some_expr)->FooNoArgs', + 'expr (&some_expr)->FooNoArgsBar()') + self.complete_exactly('expr (&some_expr) ->FooNoArgs', + 'expr (&some_expr) ->FooNoArgsBar()') + self.complete_exactly('expr (&some_expr) -> FooNoArgs', + 'expr (&some_expr) -> FooNoArgsBar()') + self.complete_exactly('expr (&some_expr)-> FooNoArgs', + 'expr (&some_expr)-> FooNoArgsBar()') + + # Builtin arg + self.complete_exactly('expr static_ca', + 'expr static_cast') + + # From other files + self.complete_exactly('expr fwd_decl_ptr->Hidden', + 'expr fwd_decl_ptr->HiddenMember') + + + # Types + self.complete_exactly('expr LongClassNa', + 'expr LongClassName') + self.complete_exactly('expr LongNamespaceName::NestedCla', + 'expr LongNamespaceName::NestedClass') + + # Namespaces + self.complete_exactly('expr LongNamespaceNa', + 'expr LongNamespaceName::') + + # Multiple arguments + self.complete_exactly('expr &some_expr + &some_e', + 'expr &some_expr + &some_expr') + self.complete_exactly('expr SomeLongVarNameWithCapitals + SomeLongVarName', + 'expr SomeLongVarNameWithCapitals + SomeLongVarNameWithCapitals') + self.complete_exactly('expr SomeIntVar + SomeIntV', + 'expr SomeIntVar + SomeIntVar') + + # Multiple statements + self.complete_exactly('expr long LocalVariable = 0; LocalVaria', + 'expr long LocalVariable = 0; LocalVariable') + + # Custom Decls + self.complete_exactly('expr auto l = [](int LeftHandSide, int bx){ return LeftHandS', + 'expr auto l = [](int LeftHandSide, int bx){ return LeftHandSide') + self.complete_exactly('expr struct LocalStruct { long MemberName; } ; LocalStruct S; S.Mem', + 'expr struct LocalStruct { long MemberName; } ; LocalStruct S; S.MemberName') + + # Completing function call arguments + self.complete_exactly('expr some_expr.FooWithArgsBar(some_exp', + 'expr some_expr.FooWithArgsBar(some_expr') + self.complete_exactly('expr some_expr.FooWithArgsBar(SomeIntV', + 'expr some_expr.FooWithArgsBar(SomeIntVar') + self.complete_exactly('expr some_expr.FooWithMultipleArgsBar(SomeIntVar, SomeIntVa', + 'expr some_expr.FooWithMultipleArgsBar(SomeIntVar, SomeIntVar') + + # Function return values + self.complete_exactly('expr some_expr.Self().FooNoArgs', + 'expr some_expr.Self().FooNoArgsBar()') + self.complete_exactly('expr some_expr.Self() .FooNoArgs', + 'expr some_expr.Self() .FooNoArgsBar()') + self.complete_exactly('expr some_expr.Self(). FooNoArgs', + 'expr some_expr.Self(). FooNoArgsBar()') + + def test_expr_completion_with_descriptions(self): + self.build() + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + '// Break here', self.main_source_spec) + + self.check_completion_with_desc("expr ", [ + # VarDecls have their type as description. + ["some_expr", "Expr &"], + # builtin types have no description. + ["int", ""], + ["float", ""] + ]) + self.check_completion_with_desc("expr some_expr.", [ + # Functions have their signature as description. + ["some_expr.Self()", "Expr &Self()"], + ["some_expr.operator=(", "inline Expr &operator=(const Expr &)"], + ["some_expr.FooNumbersBar1()", "int FooNumbersBar1()"], + ["some_expr.StaticMemberMethodBar()", "static int StaticMemberMethodBar()"], + ["some_expr.FooWithArgsBar(", "int FooWithArgsBar(int)"], + ["some_expr.FooNoArgsBar()", "int FooNoArgsBar()"], + ["some_expr.FooUnderscoreBar_()", "int FooUnderscoreBar_()"], + ["some_expr.FooWithMultipleArgsBar(", "int FooWithMultipleArgsBar(int, int)"], + ["some_expr.~Expr()", "inline ~Expr()"], + # FieldDecls have their type as description. + ["some_expr.MemberVariableBar", "int"], + ]) + + def assume_no_completions(self, str_input, cursor_pos = None): + interp = self.dbg.GetCommandInterpreter() + match_strings = lldb.SBStringList() + if cursor_pos is None: + cursor_pos = len(str_input) + num_matches = interp.HandleCompletion(str_input, cursor_pos, 0, -1, match_strings) + + available_completions = [] + for m in match_strings: + available_completions.append(m) + + self.assertEquals(num_matches, 0, "Got matches, but didn't expect any: " + str(available_completions)) + + def completions_contain(self, str_input, items): + interp = self.dbg.GetCommandInterpreter() + match_strings = lldb.SBStringList() + num_matches = interp.HandleCompletion(str_input, len(str_input), 0, -1, match_strings) + common_match = match_strings.GetStringAtIndex(0) + + for item in items: + found = False + for m in match_strings: + if m == item: + found = True + if not found: + # Transform match_strings to a python list with strings + available_completions = [] + for m in match_strings: + available_completions.append(m) + self.assertTrue(found, "Couldn't find completion " + item + " in completions " + str(available_completions)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/main.cpp new file mode 100644 index 00000000000..908bebbebff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/main.cpp @@ -0,0 +1,35 @@ +namespace LongNamespaceName { class NestedClass { long m; }; } + +// Defined in other.cpp, we only have a forward declaration here. +struct ForwardDecl; +extern ForwardDecl fwd_decl; + +class LongClassName { long i ; }; + +class Expr { +public: + int FooNoArgsBar() { return 1; } + int FooWithArgsBar(int i) { return i; } + int FooWithMultipleArgsBar(int i, int j) { return i + j; } + int FooUnderscoreBar_() { return 4; } + int FooNumbersBar1() { return 8; } + int MemberVariableBar = 0; + Expr &Self() { return *this; } + static int StaticMemberMethodBar() { return 82; } +}; + +int main() +{ + LongClassName a; + LongNamespaceName::NestedClass NestedFoo; + long SomeLongVarNameWithCapitals = 44; + int SomeIntVar = 33; + Expr some_expr; + some_expr.FooNoArgsBar(); + some_expr.FooWithArgsBar(1); + some_expr.FooUnderscoreBar_(); + some_expr.FooNumbersBar1(); + Expr::StaticMemberMethodBar(); + ForwardDecl *fwd_decl_ptr = &fwd_decl; + return 0; // Break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/other.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/other.cpp new file mode 100644 index 00000000000..1f8a488639b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/completion/other.cpp @@ -0,0 +1,4 @@ +struct ForwardDecl { + long HiddenMemberName; +}; +ForwardDecl fwd_decl; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object-objc/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object-objc/Makefile new file mode 100644 index 00000000000..a3198db9e8e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object-objc/Makefile @@ -0,0 +1,3 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object-objc/TestContextObjectObjc.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object-objc/TestContextObjectObjc.py new file mode 100644 index 00000000000..4ae4fd8680d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object-objc/TestContextObjectObjc.py @@ -0,0 +1,78 @@ +""" +Tests expression evaluation in context of an objc class. +""" + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + +class ContextObjectObjcTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_context_object_objc(self): + """Tests expression evaluation in context of an objc class.""" + self.build() + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, '// Break here', self.main_source_spec) + frame = thread.GetFrameAtIndex(0) + + # + # Test objc class variable + # + + obj_val = frame.FindVariable("objcClass") + self.assertTrue(obj_val.IsValid()) + obj_val = obj_val.Dereference() + self.assertTrue(obj_val.IsValid()) + + # Test an empty expression evaluation + value = obj_val.EvaluateExpression("") + self.assertFalse(value.IsValid()) + self.assertFalse(value.GetError().Success()) + + # Test retrieving of a field (not a local with the same name) + value = obj_val.EvaluateExpression("field") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 1111) + + # Test if the self pointer is properly evaluated + + # Test retrieving of an objcClass's property through the self pointer + value = obj_val.EvaluateExpression("self.property") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 2222) + + # Test objcClass's methods evaluation through the self pointer + value = obj_val.EvaluateExpression("[self method]") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 3333) + + # Test if we can use a computation result reference object correctly + + obj_val = frame.EvaluateExpression("[ObjcClass createNew]") + self.assertTrue(obj_val.IsValid()) + obj_val = obj_val.Dereference() + self.assertTrue(obj_val.IsValid()) + + # Test an expression evaluation on it + value = obj_val.EvaluateExpression("1") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + + # Test retrieving of a field on it + value = obj_val.EvaluateExpression("field") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 1111) + + def setUp(self): + TestBase.setUp(self) + + self.main_source = "main.m" + self.main_source_spec = lldb.SBFileSpec(self.main_source) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object-objc/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object-objc/main.m new file mode 100644 index 00000000000..5c495b24894 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object-objc/main.m @@ -0,0 +1,47 @@ +#import <Foundation/Foundation.h> + +@interface ObjcClass : NSObject { + int field; +} + +@property int property; + ++(ObjcClass*)createNew; + +-(id)init; + +-(int)method; + +@end + +@implementation ObjcClass + ++(ObjcClass*)createNew { + return [ObjcClass new]; +} + +-(id)init { + self = [super init]; + if (self) { + field = 1111; + _property = 2222; + } + return self; +} + +-(int)method { + return 3333; +} + +@end + +int main() +{ + @autoreleasepool { + ObjcClass* objcClass = [ObjcClass new]; + + int field = 4444; + + return 0; // Break here + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object/TestContextObject.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object/TestContextObject.py new file mode 100644 index 00000000000..02b8162aad6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object/TestContextObject.py @@ -0,0 +1,145 @@ +""" +Tests expression evaluation in context of an object. +""" + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + +class ContextObjectTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_context_object(self): + """Tests expression evaluation in context of an object.""" + self.build() + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, '// Break here', self.main_source_spec) + frame = thread.GetFrameAtIndex(0) + + # + # Test C++ struct variable + # + + obj_val = frame.FindVariable("cpp_struct") + self.assertTrue(obj_val.IsValid()) + + # Test an empty expression evaluation + value = obj_val.EvaluateExpression("") + self.assertFalse(value.IsValid()) + self.assertFalse(value.GetError().Success()) + + # Test retrieveing of a field (not a local with the same name) + value = obj_val.EvaluateExpression("field") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 1111) + + # Test functions evaluation + value = obj_val.EvaluateExpression("function()") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 2222) + + # Test that we retrieve the right global + value = obj_val.EvaluateExpression("global.field") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 1111) + + # + # Test C++ union variable + # + + obj_val = frame.FindVariable("cpp_union") + self.assertTrue(obj_val.IsValid()) + + # Test retrieveing of a field + value = obj_val.EvaluateExpression("field_int") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 5555) + + # + # Test C++ scalar + # + + obj_val = frame.FindVariable("cpp_scalar") + self.assertTrue(obj_val.IsValid()) + + # Test an expression evaluation + value = obj_val.EvaluateExpression("1") + self.assertFalse(value.IsValid()) + self.assertFalse(value.GetError().Success()) + + # + # Test C++ array + # + + obj_val = frame.FindVariable("cpp_array") + self.assertTrue(obj_val.IsValid()) + + # Test an expression evaluation + value = obj_val.EvaluateExpression("1") + self.assertFalse(value.IsValid()) + self.assertFalse(value.GetError().Success()) + + # Test retrieveing of an element's field + value = obj_val.GetValueForExpressionPath("[7]").EvaluateExpression("field") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 1111) + + # + # Test C++ pointer + # + + obj_val = frame.FindVariable("cpp_pointer") + self.assertTrue(obj_val.IsValid()) + + # Test an expression evaluation + value = obj_val.EvaluateExpression("1") + self.assertFalse(value.IsValid()) + self.assertFalse(value.GetError().Success()) + + # Test retrieveing of a dereferenced object's field + value = obj_val.Dereference().EvaluateExpression("field") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 1111) + + # + # Test C++ computation result + # + + obj_val = frame.EvaluateExpression("cpp_namespace::GetCppStruct()") + self.assertTrue(obj_val.IsValid()) + + # Test an expression evaluation + value = obj_val.EvaluateExpression("1") + self.assertTrue(value.IsValid()) + self.assertFalse(value.GetError().Success()) + + # + # Test C++ computation result located in debuggee memory + # + + obj_val = frame.EvaluateExpression("cpp_namespace::GetCppStructPtr()") + self.assertTrue(obj_val.IsValid()) + + # Test an expression evaluation + value = obj_val.EvaluateExpression("1") + self.assertFalse(value.IsValid()) + self.assertFalse(value.GetError().Success()) + + # Test retrieveing of a dereferenced object's field + value = obj_val.Dereference().EvaluateExpression("field") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 1111) + + def setUp(self): + TestBase.setUp(self) + + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object/main.cpp new file mode 100644 index 00000000000..098b6089fce --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/context-object/main.cpp @@ -0,0 +1,46 @@ +namespace cpp_namespace { + struct CppStruct { + int field = 1111; + + int function() { + return 2222; + } + }; + + union CppUnion { + char field_char; + short field_short; + int field_int; + }; + + CppStruct GetCppStruct() { + return CppStruct(); + } + + CppStruct global; + + CppStruct *GetCppStructPtr() { + return &global; + } +} + +int global = 3333; + +int main() +{ + cpp_namespace::CppStruct cpp_struct = cpp_namespace::GetCppStruct(); + cpp_struct.function(); + + int field = 4444; + + cpp_namespace::CppUnion cpp_union; + cpp_union.field_int = 5555; + + int cpp_scalar = 6666; + + cpp_namespace::CppStruct cpp_array[16]; + + cpp_namespace::CppStruct *cpp_pointer = cpp_namespace::GetCppStructPtr(); + + return 0; // Break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/diagnostics/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/diagnostics/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/diagnostics/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/diagnostics/TestExprDiagnostics.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/diagnostics/TestExprDiagnostics.py new file mode 100644 index 00000000000..da29d7b2c1a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/diagnostics/TestExprDiagnostics.py @@ -0,0 +1,112 @@ +""" +Test the diagnostics emitted by our embeded Clang instance that parses expressions. +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +from lldbsuite.test.decorators import * + +class ExprDiagnosticsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + def test_source_and_caret_printing(self): + """Test that the source and caret positions LLDB prints are correct""" + self.build() + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + '// Break here', self.main_source_spec) + frame = thread.GetFrameAtIndex(0) + + # Test that source/caret are at the right position. + value = frame.EvaluateExpression("unknown_identifier") + self.assertFalse(value.GetError().Success()) + # We should get a nice diagnostic with a caret pointing at the start of + # the identifier. + self.assertIn("\nunknown_identifier\n^\n", value.GetError().GetCString()) + self.assertIn("<user expression 0>:1:1", value.GetError().GetCString()) + + # Same as above but with the identifier in the middle. + value = frame.EvaluateExpression("1 + unknown_identifier ") + self.assertFalse(value.GetError().Success()) + self.assertIn("\n1 + unknown_identifier", value.GetError().GetCString()) + self.assertIn("\n ^\n", value.GetError().GetCString()) + + # Multiline expressions. + value = frame.EvaluateExpression("int a = 0;\nfoobar +=1;\na") + self.assertFalse(value.GetError().Success()) + # We should still get the right line information and caret position. + self.assertIn("\nfoobar +=1;\n^\n", value.GetError().GetCString()) + # It's the second line of the user expression. + self.assertIn("<user expression 2>:2:1", value.GetError().GetCString()) + + # Top-level expressions. + top_level_opts = lldb.SBExpressionOptions(); + top_level_opts.SetTopLevel(True) + + value = frame.EvaluateExpression("void foo(unknown_type x) {}", top_level_opts) + self.assertFalse(value.GetError().Success()) + self.assertIn("\nvoid foo(unknown_type x) {}\n ^\n", value.GetError().GetCString()) + # Top-level expressions might use a different wrapper code, but the file name should still + # be the same. + self.assertIn("<user expression 3>:1:10", value.GetError().GetCString()) + + # Multiline top-level expressions. + value = frame.EvaluateExpression("void x() {}\nvoid foo(unknown_type x) {}", top_level_opts) + self.assertFalse(value.GetError().Success()) + self.assertIn("\nvoid foo(unknown_type x) {}\n ^\n", value.GetError().GetCString()) + self.assertIn("<user expression 4>:2:10", value.GetError().GetCString()) + + # Test that we render Clang's 'notes' correctly. + value = frame.EvaluateExpression("struct SFoo{}; struct SFoo { int x; };", top_level_opts) + self.assertFalse(value.GetError().Success()) + self.assertIn("<user expression 5>:1:8: previous definition is here\nstruct SFoo{}; struct SFoo { int x; };\n ^\n", value.GetError().GetCString()) + + # Declarations from the debug information currently have no debug information. It's not clear what + # we should do in this case, but we should at least not print anything that's wrong. + # In the future our declarations should have valid source locations. + value = frame.EvaluateExpression("struct FooBar { double x };", top_level_opts) + self.assertFalse(value.GetError().Success()) + self.assertEqual("error: <user expression 6>:1:8: redefinition of 'FooBar'\nstruct FooBar { double x };\n ^\n", value.GetError().GetCString()) + + value = frame.EvaluateExpression("foo(1, 2)") + self.assertFalse(value.GetError().Success()) + self.assertEqual("error: <user expression 7>:1:1: no matching function for call to 'foo'\nfoo(1, 2)\n^~~\nnote: candidate function not viable: requires single argument 'x', but 2 arguments were provided\n\n", value.GetError().GetCString()) + + # Redefine something that we defined in a user-expression. We should use the previous expression file name + # for the original decl. + value = frame.EvaluateExpression("struct Redef { double x; };", top_level_opts) + value = frame.EvaluateExpression("struct Redef { float y; };", top_level_opts) + self.assertFalse(value.GetError().Success()) + self.assertIn("error: <user expression 9>:1:8: redefinition of 'Redef'\nstruct Redef { float y; };\n ^\n<user expression 8>:1:8: previous definition is here\nstruct Redef { double x; };\n ^", value.GetError().GetCString()) + + @skipUnlessDarwin + def test_source_locations_from_objc_modules(self): + self.build() + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + '// Break here', self.main_source_spec) + frame = thread.GetFrameAtIndex(0) + + # Import foundation so that the Obj-C module is loaded (which contains source locations + # that can be used by LLDB). + self.runCmd("expr @import Foundation") + value = frame.EvaluateExpression("NSLog(1);") + self.assertFalse(value.GetError().Success()) + # LLDB should print the source line that defines NSLog. To not rely on any + # header paths/line numbers or the actual formatting of the Foundation headers, only look + # for a few tokens in the output. + # File path should come from Foundation framework. + self.assertIn("/Foundation.framework/", value.GetError().GetCString()) + # The NSLog definition source line should be printed. Return value and + # the first argument are probably stable enough that this test can check for them. + self.assertIn("void NSLog(NSString *format", value.GetError().GetCString()) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/diagnostics/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/diagnostics/main.cpp new file mode 100644 index 00000000000..f4ad1ad220c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/diagnostics/main.cpp @@ -0,0 +1,11 @@ +void foo(int x) {} + +struct FooBar { + int i; +}; + +int main() { + FooBar f; + foo(1); + return 0; // Break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dollar-in-variable/TestDollarInVariable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dollar-in-variable/TestDollarInVariable.py new file mode 100644 index 00000000000..7458867527d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dollar-in-variable/TestDollarInVariable.py @@ -0,0 +1,5 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + [lldbinline.expectedFailureAll(oslist=["windows"])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dollar-in-variable/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dollar-in-variable/main.c new file mode 100644 index 00000000000..e5fec25b35b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dollar-in-variable/main.c @@ -0,0 +1,21 @@ +// Make sure we correctly handle $ in variable names. + +int main() { + // Some variables that might conflict with our variables below. + int __lldb_expr_result = 2; + int $$foo = 1; + int R0 = 2; + + // Some variables with dollar signs that should work (and shadow + // any built-in LLDB variables). + int $__lldb_expr_result = 11; + int $foo = 12; + int $R0 = 13; + int $0 = 14; + + //%self.expect("expr $__lldb_expr_result", substrs=['(int) $0 = 11']) + //%self.expect("expr $foo", substrs=['(int)', ' = 12']) + //%self.expect("expr $R0", substrs=['(int)', ' = 13']) + //%self.expect("expr int $foo = 123", error=True, substrs=["declaration conflicts"]) + return 0; //%self.expect("expr $0", substrs=['(int)', ' = 14']) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dont_allow_jit/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dont_allow_jit/Makefile new file mode 100644 index 00000000000..695335e068c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dont_allow_jit/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dont_allow_jit/TestAllowJIT.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dont_allow_jit/TestAllowJIT.py new file mode 100644 index 00000000000..c70e90e7a26 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dont_allow_jit/TestAllowJIT.py @@ -0,0 +1,82 @@ +""" +Test that --allow-jit=false does disallow JITting: +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +class TestAllowJIT(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def test_allow_jit_expr_command(self): + """Test the --allow-jit command line flag""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.c") + self.expr_cmd_test() + + def test_allow_jit_options(self): + """Test the SetAllowJIT SBExpressionOption setting""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.c") + self.expr_options_test() + + def expr_cmd_test(self): + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", self.main_source_file) + + frame = thread.GetFrameAtIndex(0) + + # First make sure we can call the function with + interp = self.dbg.GetCommandInterpreter() + self.expect("expr --allow-jit 1 -- call_me(10)", + substrs = ["(int) $", "= 18"]) + # Now make sure it fails with the "can't IR interpret message" if allow-jit is false: + self.expect("expr --allow-jit 0 -- call_me(10)", + error=True, + substrs = ["Can't evaluate the expression without a running target"]) + + def expr_options_test(self): + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", self.main_source_file) + + frame = thread.GetFrameAtIndex(0) + + # First make sure we can call the function with the default option set. + options = lldb.SBExpressionOptions() + # Check that the default is to allow JIT: + self.assertEqual(options.GetAllowJIT(), True, "Default is true") + + # Now use the options: + result = frame.EvaluateExpression("call_me(10)", options) + self.assertTrue(result.GetError().Success(), "expression succeeded") + self.assertEqual(result.GetValueAsSigned(), 18, "got the right value.") + + # Now disallow JIT and make sure it fails: + options.SetAllowJIT(False) + # Check that we got the right value: + self.assertEqual(options.GetAllowJIT(), False, "Got False after setting to False") + + # Again use it and ensure we fail: + result = frame.EvaluateExpression("call_me(10)", options) + self.assertTrue(result.GetError().Fail(), "expression failed with no JIT") + self.assertTrue("Can't evaluate the expression without a running target" in result.GetError().GetCString(), "Got right error") + + # Finally set the allow JIT value back to true and make sure that works: + options.SetAllowJIT(True) + self.assertEqual(options.GetAllowJIT(), True, "Set back to True correctly") + + # And again, make sure this works: + result = frame.EvaluateExpression("call_me(10)", options) + self.assertTrue(result.GetError().Success(), "expression succeeded") + self.assertEqual(result.GetValueAsSigned(), 18, "got the right value.") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dont_allow_jit/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dont_allow_jit/main.c new file mode 100644 index 00000000000..ebd8ae11a73 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/dont_allow_jit/main.c @@ -0,0 +1,15 @@ +#include <stdio.h> + +int +call_me(int input) +{ + return printf("I was called: %d.\n", input); +} + +int +main() +{ + int test_var = 10; + printf ("Set a breakpoint here: %d.\n", test_var); + return call_me(100); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/entry-bp/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/entry-bp/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/entry-bp/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/entry-bp/TestExprEntryBP.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/entry-bp/TestExprEntryBP.py new file mode 100644 index 00000000000..b6e6b8ba051 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/entry-bp/TestExprEntryBP.py @@ -0,0 +1,32 @@ +""" +Tests expressions evaluation when the breakpoint on module's entry is set. +""" + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + +class ExprEntryBPTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test_expr_entry_bp(self): + """Tests expressions evaluation when the breakpoint on module's entry is set.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.c") + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, "Set a breakpoint here", self.main_source_file) + + self.assertEqual(1, bkpt.GetNumLocations()) + entry = bkpt.GetLocationAtIndex(0).GetAddress().GetModule().GetObjectFileEntryPointAddress() + self.assertTrue(entry.IsValid(), "Can't get a module entry point") + + entry_bp = target.BreakpointCreateBySBAddress(entry) + self.assertTrue(entry_bp.IsValid(), "Can't set a breakpoint on the module entry point") + + result = target.EvaluateExpression("sum(7, 1)") + self.assertTrue(result.IsValid(), "Can't evaluate expression") + self.assertEqual(8, result.GetValueAsSigned()) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/entry-bp/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/entry-bp/main.c new file mode 100644 index 00000000000..168fc9c8ccb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/entry-bp/main.c @@ -0,0 +1,10 @@ +#include <stdio.h> + +int sum(int x, int y) { + return x + y; +} + +int main() { + printf("Set a breakpoint here.\n"); + return sum(-1, 1); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/expr-in-syscall/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/expr-in-syscall/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/expr-in-syscall/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/expr-in-syscall/TestExpressionInSyscall.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/expr-in-syscall/TestExpressionInSyscall.py new file mode 100644 index 00000000000..a383f691120 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/expr-in-syscall/TestExpressionInSyscall.py @@ -0,0 +1,89 @@ +"""Test that we are able to evaluate expressions when the inferior is blocked in a syscall""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprSyscallTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21765, getpid() does not exist on Windows") + @expectedFailureNetBSD + def test_setpgid(self): + self.build() + self.expr_syscall() + + def expr_syscall(self): + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + listener = lldb.SBListener("my listener") + + # launch the inferior and don't wait for it to stop + self.dbg.SetAsync(True) + error = lldb.SBError() + process = target.Launch(listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error + + self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) + + event = lldb.SBEvent() + + # Give the child enough time to reach the syscall, + # while clearing out all the pending events. + # The last WaitForEvent call will time out after 2 seconds. + while listener.WaitForEvent(2, event): + pass + + # now the process should be running (blocked in the syscall) + self.assertEqual( + process.GetState(), + lldb.eStateRunning, + "Process is running") + + # send the process a signal + process.SendAsyncInterrupt() + while listener.WaitForEvent(2, event): + pass + + # as a result the process should stop + # in all likelihood we have stopped in the middle of the sleep() + # syscall + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + thread = process.GetSelectedThread() + + # try evaluating a couple of expressions in this state + self.expect("expr release_flag = 1", substrs=[" = 1"]) + self.expect("print (int)getpid()", + substrs=[str(process.GetProcessID())]) + + # and run the process to completion + process.Continue() + + # process all events + while listener.WaitForEvent(10, event): + new_state = lldb.SBProcess.GetStateFromEvent(event) + if new_state == lldb.eStateExited: + break + + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), 0) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/expr-in-syscall/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/expr-in-syscall/main.cpp new file mode 100644 index 00000000000..743b69434d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/expr-in-syscall/main.cpp @@ -0,0 +1,12 @@ +#include <chrono> +#include <thread> + +volatile int release_flag = 0; + +int main(int argc, char const *argv[]) +{ + while (! release_flag) // Wait for debugger to attach + std::this_thread::sleep_for(std::chrono::seconds(3)); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/fixits/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/fixits/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/fixits/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/fixits/TestFixIts.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/fixits/TestFixIts.py new file mode 100644 index 00000000000..c93a05abe89 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/fixits/TestFixIts.py @@ -0,0 +1,71 @@ +""" +Test calling an expression with errors that a FixIt can fix. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCommandWithFixits(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + @skipUnlessDarwin + def test_with_target(self): + """Test calling expressions with errors that can be fixed by the FixIts.""" + self.build() + self.try_expressions() + + def test_with_dummy_target(self): + """Test calling expressions in the dummy target with errors that can be fixed by the FixIts.""" + ret_val = lldb.SBCommandReturnObject() + result = self.dbg.GetCommandInterpreter().HandleCommand("expression ((1 << 16) - 1))", ret_val) + self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult, "The expression was successful.") + self.assertTrue("Fix-it applied" in ret_val.GetError(), "Found the applied FixIt.") + + def try_expressions(self): + """Test calling expressions with errors that can be fixed by the FixIts.""" + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + 'Stop here to evaluate expressions', self.main_source_spec) + + options = lldb.SBExpressionOptions() + options.SetAutoApplyFixIts(True) + + frame = self.thread.GetFrameAtIndex(0) + + # Try with one error: + value = frame.EvaluateExpression("my_pointer.first", options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsUnsigned() == 10) + + # Try with two errors: + two_error_expression = "my_pointer.second->a" + value = frame.EvaluateExpression(two_error_expression, options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsUnsigned() == 20) + + # Now turn off the fixits, and the expression should fail: + options.SetAutoApplyFixIts(False) + value = frame.EvaluateExpression(two_error_expression, options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Fail()) + error_string = value.GetError().GetCString() + self.assertTrue( + error_string.find("fixed expression suggested:") != -1, + "Fix was suggested") + self.assertTrue( + error_string.find("my_pointer->second.a") != -1, + "Fix was right") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/fixits/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/fixits/main.cpp new file mode 100644 index 00000000000..371d8333763 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/fixits/main.cpp @@ -0,0 +1,25 @@ +#include <stdio.h> + +struct SubStruct +{ + int a; + int b; +}; + +struct MyStruct +{ + int first; + struct SubStruct second; +}; + +int +main() +{ + struct MyStruct my_struct = {10, {20, 30}}; + struct MyStruct *my_pointer = &my_struct; + printf ("Stop here to evaluate expressions: %d %d %p\n", my_pointer->first, my_pointer->second.a, my_pointer); + return 0; +} + + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/TestFormatters.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/TestFormatters.py new file mode 100644 index 00000000000..98872dffca3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/TestFormatters.py @@ -0,0 +1,300 @@ +""" +Test using LLDB data formatters with frozen objects coming from the expression parser. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprFormattersTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.cpp. + self.line = line_number('main.cpp', + '// Stop here') + + @skipIfFreeBSD # llvm.org/pr24691 skipping to avoid crashing the test runner + @expectedFailureNetBSD + @expectedFailureAll( + oslist=['freebsd'], + bugnumber='llvm.org/pr19011 Newer Clang omits C1 complete object constructor') + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") + @skipIfTargetAndroid() # skipping to avoid crashing the test runner + @expectedFailureAndroid('llvm.org/pr24691') # we hit an assertion in clang + def test(self): + """Test expr + formatters for good interoperability.""" + self.build() + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type summary clear', check=False) + self.runCmd('type synthetic clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + """Test expr + formatters for good interoperability.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + self.runCmd("command script import formatters.py") + self.runCmd("command script import foosynth.py") + + if self.TraceOn(): + self.runCmd("frame variable foo1 --show-types") + self.runCmd("frame variable foo1.b --show-types") + self.runCmd("frame variable foo1.b.b_ref --show-types") + + self.filecheck("expression --show-types -- *(new foo(47))", __file__, + '-check-prefix=EXPR-TYPES-NEW-FOO') + # EXPR-TYPES-NEW-FOO: (foo) ${{.*}} = { + # EXPR-TYPES-NEW-FOO-NEXT: (int) a = 47 + # EXPR-TYPES-NEW-FOO-NEXT: (int *) a_ptr = 0x + # EXPR-TYPES-NEW-FOO-NEXT: (bar) b = { + # EXPR-TYPES-NEW-FOO-NEXT: (int) i = 94 + # EXPR-TYPES-NEW-FOO-NEXT: (int *) i_ptr = 0x + # EXPR-TYPES-NEW-FOO-NEXT: (baz) b = { + # EXPR-TYPES-NEW-FOO-NEXT: (int) h = 97 + # EXPR-TYPES-NEW-FOO-NEXT: (int) k = 99 + # EXPR-TYPES-NEW-FOO-NEXT: } + # EXPR-TYPES-NEW-FOO-NEXT: (baz &) b_ref = 0x + # EXPR-TYPES-NEW-FOO-NEXT: } + # EXPR-TYPES-NEW-FOO-NEXT: } + + + self.runCmd("type summary add -F formatters.foo_SummaryProvider3 foo") + self.filecheck("expression foo1", __file__, '-check-prefix=EXPR-FOO1opts') + # EXPR-FOO1opts: (foo) $ + # EXPR-FOO1opts-SAME: a = 12 + # EXPR-FOO1opts-SAME: a_ptr = {{[0-9]+}} -> 13 + # EXPR-FOO1opts-SAME: i = 24 + # EXPR-FOO1opts-SAME: i_ptr = {{[0-9]+}} -> 25 + # EXPR-FOO1opts-SAME: b_ref = {{[0-9]+}} + # EXPR-FOO1opts-SAME: h = 27 + # EXPR-FOO1opts-SAME: k = 29 + # EXPR-FOO1opts-SAME: WITH_OPTS + + self.runCmd("type summary delete foo") + + self.runCmd("type summary add -F formatters.foo_SummaryProvider foo") + + self.expect("expression new int(12)", + substrs=['(int *) $', ' = 0x']) + + self.runCmd( + "type summary add -s \"${var%pointer} -> ${*var%decimal}\" \"int *\"") + + self.expect("expression new int(12)", + substrs=['(int *) $', '= 0x', ' -> 12']) + + self.expect("expression foo1.a_ptr", + substrs=['(int *) $', '= 0x', ' -> 13']) + + self.filecheck("expression foo1", __file__, '-check-prefix=EXPR-FOO1') + # EXPR-FOO1: (foo) $ + # EXPR-FOO1-SAME: a = 12 + # EXPR-FOO1-SAME: a_ptr = {{[0-9]+}} -> 13 + # EXPR-FOO1-SAME: i = 24 + # EXPR-FOO1-SAME: i_ptr = {{[0-9]+}} -> 25 + # EXPR-FOO1-SAME: b_ref = {{[0-9]+}} + # EXPR-FOO1-SAME: h = 27 + # EXPR-FOO1-SAME: k = 29 + + self.filecheck("expression --ptr-depth=1 -- new foo(47)", __file__, + '-check-prefix=EXPR-PTR-DEPTH1') + # EXPR-PTR-DEPTH1: (foo *) $ + # EXPR-PTR-DEPTH1-SAME: a = 47 + # EXPR-PTR-DEPTH1-SAME: a_ptr = {{[0-9]+}} -> 48 + # EXPR-PTR-DEPTH1-SAME: i = 94 + # EXPR-PTR-DEPTH1-SAME: i_ptr = {{[0-9]+}} -> 95 + + self.filecheck("expression foo2", __file__, '-check-prefix=EXPR-FOO2') + # EXPR-FOO2: (foo) $ + # EXPR-FOO2-SAME: a = 121 + # EXPR-FOO2-SAME: a_ptr = {{[0-9]+}} -> 122 + # EXPR-FOO2-SAME: i = 242 + # EXPR-FOO2-SAME: i_ptr = {{[0-9]+}} -> 243 + # EXPR-FOO2-SAME: h = 245 + # EXPR-FOO2-SAME: k = 247 + + object_name = self.res.GetOutput() + object_name = object_name[7:] + object_name = object_name[0:object_name.find(' =')] + + self.filecheck("frame variable foo2", __file__, '-check-prefix=VAR-FOO2') + # VAR-FOO2: (foo) foo2 + # VAR-FOO2-SAME: a = 121 + # VAR-FOO2-SAME: a_ptr = {{[0-9]+}} -> 122 + # VAR-FOO2-SAME: i = 242 + # VAR-FOO2-SAME: i_ptr = {{[0-9]+}} -> 243 + # VAR-FOO2-SAME: h = 245 + # VAR-FOO2-SAME: k = 247 + + # The object is the same as foo2, so use the EXPR-FOO2 checks. + self.filecheck("expression $" + object_name, __file__, + '-check-prefix=EXPR-FOO2') + + self.runCmd("type summary delete foo") + self.runCmd( + "type synthetic add --python-class foosynth.FooSyntheticProvider foo") + + self.expect("expression --show-types -- $" + object_name, + substrs=['(foo) $', ' = {', '(int) *i_ptr = 243']) + + self.runCmd("n") + self.runCmd("n") + + self.runCmd("type synthetic delete foo") + self.runCmd("type summary add -F formatters.foo_SummaryProvider foo") + + self.expect( + "expression foo2", + substrs=[ + '(foo) $', + 'a = 7777', + 'a_ptr = ', + ' -> 122', + 'i = 242', + 'i_ptr = ', + ' -> 8888']) + + self.expect("expression $" + object_name + '.a', + substrs=['7777']) + + self.expect("expression *$" + object_name + '.b.i_ptr', + substrs=['8888']) + + self.expect( + "expression $" + + object_name, + substrs=[ + '(foo) $', + 'a = 121', + 'a_ptr = ', + ' -> 122', + 'i = 242', + 'i_ptr = ', + ' -> 8888', + 'h = 245', + 'k = 247']) + + self.runCmd("type summary delete foo") + self.runCmd( + "type synthetic add --python-class foosynth.FooSyntheticProvider foo") + + self.expect("expression --show-types -- $" + object_name, + substrs=['(foo) $', ' = {', '(int) *i_ptr = 8888']) + + self.runCmd("n") + + self.runCmd("type synthetic delete foo") + self.runCmd("type summary add -F formatters.foo_SummaryProvider foo") + + self.expect( + "expression $" + + object_name, + substrs=[ + '(foo) $', + 'a = 121', + 'a_ptr = ', + ' -> 122', + 'i = 242', + 'i_ptr = ', + ' -> 8888', + 'k = 247']) + + process = self.dbg.GetSelectedTarget().GetProcess() + thread = process.GetThreadAtIndex(0) + frame = thread.GetSelectedFrame() + + frozen = frame.EvaluateExpression("$" + object_name + ".a_ptr") + + a_data = frozen.GetPointeeData() + + error = lldb.SBError() + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 0) == 122, + '*a_ptr = 122') + + ret = line_number("main.cpp", "Done initializing") + self.runCmd("thread until " + str(ret)) + + self.expect("frame variable numbers", + substrs=['1', '2', '3', '4', '5']) + + self.expect("expression numbers", + substrs=['1', '2', '3', '4', '5']) + + frozen = frame.EvaluateExpression("&numbers") + + a_data = frozen.GetPointeeData(0, 1) + + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 0) == 1, + 'numbers[0] == 1') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 4) == 2, + 'numbers[1] == 2') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 8) == 3, + 'numbers[2] == 3') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 12) == 4, + 'numbers[3] == 4') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 16) == 5, + 'numbers[4] == 5') + + frozen = frame.EvaluateExpression("numbers") + + a_data = frozen.GetData() + + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 0) == 1, + 'numbers[0] == 1') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 4) == 2, + 'numbers[1] == 2') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 8) == 3, + 'numbers[2] == 3') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 12) == 4, + 'numbers[3] == 4') + self.assertTrue( + a_data.GetUnsignedInt32( + error, + 16) == 5, + 'numbers[4] == 5') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/foosynth.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/foosynth.py new file mode 100644 index 00000000000..7b1284d2a76 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/foosynth.py @@ -0,0 +1,33 @@ +import lldb + + +class FooSyntheticProvider: + + def __init__(self, valobj, dict): + self.valobj = valobj + self.update() + + def update(self): + self.adjust_for_architecture() + + def num_children(self): + return 1 + + def get_child_at_index(self, index): + if index != 0: + return None + return self.i_ptr.Dereference() + + def get_child_index(self, name): + if name == "*i_ptr": + return 0 + return None + + def adjust_for_architecture(self): + self.lp64 = ( + self.valobj.GetTarget().GetProcess().GetAddressByteSize() == 8) + self.is_little = (self.valobj.GetTarget().GetProcess( + ).GetByteOrder() == lldb.eByteOrderLittle) + self.pointer_size = self.valobj.GetTarget().GetProcess().GetAddressByteSize() + self.bar = self.valobj.GetChildMemberWithName('b') + self.i_ptr = self.bar.GetChildMemberWithName('i_ptr') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/formatters.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/formatters.py new file mode 100644 index 00000000000..ac2888bd203 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/formatters.py @@ -0,0 +1,24 @@ +import lldb + +def foo_SummaryProvider(valobj, dict): + a = valobj.GetChildMemberWithName('a') + a_ptr = valobj.GetChildMemberWithName('a_ptr') + bar = valobj.GetChildMemberWithName('b') + i = bar.GetChildMemberWithName('i') + i_ptr = bar.GetChildMemberWithName('i_ptr') + b_ref = bar.GetChildMemberWithName('b_ref') + b_ref_ptr = b_ref.AddressOf() + b_ref = b_ref_ptr.Dereference() + h = b_ref.GetChildMemberWithName('h') + k = b_ref.GetChildMemberWithName('k') + return 'a = ' + str(a.GetValueAsUnsigned(0)) + ', a_ptr = ' + \ + str(a_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(a_ptr.Dereference().GetValueAsUnsigned(0)) + \ + ', i = ' + str(i.GetValueAsUnsigned(0)) + \ + ', i_ptr = ' + str(i_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(i_ptr.Dereference().GetValueAsUnsigned(0)) + \ + ', b_ref = ' + str(b_ref.GetValueAsUnsigned(0)) + \ + ', h = ' + str(h.GetValueAsUnsigned(0)) + ' , k = ' + str(k.GetValueAsUnsigned(0)) + +def foo_SummaryProvider3(valobj, dict, options): + if not isinstance(options, lldb.SBTypeSummaryOptions): + raise Exception() + return foo_SummaryProvider(valobj, dict) + ", WITH_OPTS"
\ No newline at end of file diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/main.cpp new file mode 100644 index 00000000000..4ca2504ff8c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/formatters/main.cpp @@ -0,0 +1,48 @@ +#include <iostream> +#include <string> + +struct baz + { + int h; + int k; + baz(int a, int b) : h(a), k(b) {} + }; + +struct bar + { + int i; + int* i_ptr; + baz b; + baz& b_ref; + bar(int x) : i(x),i_ptr(new int(x+1)),b(i+3,i+5),b_ref(b) {} + }; + +struct foo + { + int a; + int* a_ptr; + bar b; + + foo(int x) : a(x), + a_ptr(new int(x+1)), + b(2*x) {} + + }; + +int main(int argc, char** argv) +{ + foo foo1(12); + foo foo2(121); + + foo2.a = 7777; // Stop here + *(foo2.b.i_ptr) = 8888; + foo2.b.b.h = 9999; + + *(foo1.a_ptr) = 9999; + foo1.b.i = 9999; + + int numbers[5] = {1,2,3,4,5}; + + return 0; // Done initializing + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/function_template_specialization_temp_args/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/function_template_specialization_temp_args/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/function_template_specialization_temp_args/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/function_template_specialization_temp_args/TestFunctionTemplateSpecializationTempArgs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/function_template_specialization_temp_args/TestFunctionTemplateSpecializationTempArgs.py new file mode 100644 index 00000000000..bd5bc0ec72a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/function_template_specialization_temp_args/TestFunctionTemplateSpecializationTempArgs.py @@ -0,0 +1,17 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestFunctionTemplateSpecializationTempArgs(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_function_template_specialization_temp_args(self): + self.build() + + (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + self.expect("expr p0", + substrs=['(VType) $0 = {}']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/function_template_specialization_temp_args/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/function_template_specialization_temp_args/main.cpp new file mode 100644 index 00000000000..6d01288259a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/function_template_specialization_temp_args/main.cpp @@ -0,0 +1,17 @@ +template <typename T> struct M {}; + +template <typename T> void f(T &t); + +template <> void f<int>(int &t) { + typedef M<int> VType; + + VType p0; // break here +} + +int main() { + int x; + + f(x); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ignore-artificial-constructors/TestIgnoreArtificialConstructors.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ignore-artificial-constructors/TestIgnoreArtificialConstructors.py new file mode 100644 index 00000000000..e33423ad7a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ignore-artificial-constructors/TestIgnoreArtificialConstructors.py @@ -0,0 +1,5 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), [lldbinline.expectedFailureAll( + oslist=["windows"], bugnumber="llvm.org/pr43707")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ignore-artificial-constructors/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ignore-artificial-constructors/main.cpp new file mode 100644 index 00000000000..41457ebe1da --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ignore-artificial-constructors/main.cpp @@ -0,0 +1,10 @@ +struct Foo { + // Triggers that we emit an artificial constructor for Foo. + virtual ~Foo() = default; +}; + +int main() { + Foo f; + // Try to construct foo in our expression. + return 0; //%self.expect("expr Foo()", substrs=["(Foo) $0 = {}"]) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/basic/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/basic/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/basic/TestImportStdModule.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/basic/TestImportStdModule.py new file mode 100644 index 00000000000..de0d796505e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/basic/TestImportStdModule.py @@ -0,0 +1,48 @@ +""" +Test importing the 'std' C++ module and evaluate expressions with it. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ImportStdModule(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + # Activate importing of std module. + self.runCmd("settings set target.import-std-module true") + # Calling some normal std functions that return non-template types. + self.expect("expr std::abs(-42)", substrs=['(int) $0 = 42']) + self.expect("expr std::div(2, 1).quot", substrs=['(int) $1 = 2']) + # Using types from std. + self.expect("expr (std::size_t)33U", substrs=['(size_t) $2 = 33']) + # Calling templated functions that return non-template types. + self.expect("expr char char_a = 'b'; char char_b = 'a'; std::swap(char_a, char_b); char_a", + substrs=["(char) $3 = 'a'"]) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test_non_cpp_language(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + # Activate importing of std module. + self.runCmd("settings set target.import-std-module true") + # These languages don't support C++ modules, so they shouldn't + # be able to evaluate the expression. + self.expect("expr -l C -- std::abs(-42)", error=True) + self.expect("expr -l C99 -- std::abs(-42)", error=True) + self.expect("expr -l C11 -- std::abs(-42)", error=True) + self.expect("expr -l ObjC -- std::abs(-42)", error=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/basic/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/basic/main.cpp new file mode 100644 index 00000000000..2f6d078daa3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/basic/main.cpp @@ -0,0 +1,7 @@ +// We need to import any std module. It doesn't matter which one. +#include <iostream> + +int main(int argc, char **argv) { + std::cout << "Test" << std::endl; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/conflicts/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/conflicts/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/conflicts/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/conflicts/TestStdModuleWithConflicts.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/conflicts/TestStdModuleWithConflicts.py new file mode 100644 index 00000000000..ad5322baab0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/conflicts/TestStdModuleWithConflicts.py @@ -0,0 +1,32 @@ +""" +Test importing the 'std' C++ module and check if we can handle +prioritizing the conflicting functions from debug info and std +module. + +See also import-std-module/basic/TestImportStdModule.py for +the same test on a 'clean' code base without conflicts. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestImportStdModuleConflicts(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + self.expect("expr std::abs(-42)", substrs=['(int) $0 = 42']) + self.expect("expr std::div(2, 1).quot", substrs=['(int) $1 = 2']) + self.expect("expr (std::size_t)33U", substrs=['(size_t) $2 = 33']) + self.expect("expr char char_a = 'b'; char char_b = 'a'; std::swap(char_a, char_b); char_a", + substrs=["(char) $3 = 'a'"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/conflicts/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/conflicts/main.cpp new file mode 100644 index 00000000000..e49b862a36c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/conflicts/main.cpp @@ -0,0 +1,10 @@ +#include <cstdlib> +#include <utility> + +int main(int argc, char **argv) { + std::size_t f = argc; + f = std::abs(argc); + f = std::div(argc * 2, argc).quot; + std::swap(f, f); + return f; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-basic/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-basic/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-basic/TestBasicDeque.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-basic/TestBasicDeque.py new file mode 100644 index 00000000000..4615d249bb1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-basic/TestBasicDeque.py @@ -0,0 +1,37 @@ +""" +Test basic std::list functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestBasicDeque(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)a.size()", substrs=['(size_t) $0 = 3']) + self.expect("expr (int)a.front()", substrs=['(int) $1 = 3']) + self.expect("expr (int)a.back()", substrs=['(int) $2 = 2']) + + self.expect("expr std::sort(a.begin(), a.end())") + self.expect("expr (int)a.front()", substrs=['(int) $3 = 1']) + self.expect("expr (int)a.back()", substrs=['(int) $4 = 3']) + + self.expect("expr std::reverse(a.begin(), a.end())") + self.expect("expr (int)a.front()", substrs=['(int) $5 = 3']) + self.expect("expr (int)a.back()", substrs=['(int) $6 = 1']) + + self.expect("expr (int)(*a.begin())", substrs=['(int) $7 = 3']) + self.expect("expr (int)(*a.rbegin())", substrs=['(int) $8 = 1']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-basic/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-basic/main.cpp new file mode 100644 index 00000000000..5bed55674bf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-basic/main.cpp @@ -0,0 +1,6 @@ +#include <deque> + +int main(int argc, char **argv) { + std::deque<int> a = {3, 1, 2}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-dbg-info-content/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-dbg-info-content/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-dbg-info-content/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-dbg-info-content/TestDbgInfoContentDeque.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-dbg-info-content/TestDbgInfoContentDeque.py new file mode 100644 index 00000000000..cde74af8e1f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-dbg-info-content/TestDbgInfoContentDeque.py @@ -0,0 +1,33 @@ +""" +Test std::deque functionality with a decl from dbg info as content. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestDbgInfoContentDeque(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)a.size()", substrs=['(size_t) $0 = 3']) + self.expect("expr (int)a.front().a", substrs=['(int) $1 = 3']) + self.expect("expr (int)a.back().a", substrs=['(int) $2 = 2']) + + self.expect("expr std::reverse(a.begin(), a.end())") + self.expect("expr (int)a.front().a", substrs=['(int) $3 = 2']) + self.expect("expr (int)a.back().a", substrs=['(int) $4 = 3']) + + self.expect("expr (int)(a.begin()->a)", substrs=['(int) $5 = 2']) + self.expect("expr (int)(a.rbegin()->a)", substrs=['(int) $6 = 3']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-dbg-info-content/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-dbg-info-content/main.cpp new file mode 100644 index 00000000000..f8fd1fb2dd9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/deque-dbg-info-content/main.cpp @@ -0,0 +1,10 @@ +#include <deque> + +struct Foo { + int a; +}; + +int main(int argc, char **argv) { + std::deque<Foo> a = {{3}, {1}, {2}}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/Makefile new file mode 100644 index 00000000000..533ff707023 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/Makefile @@ -0,0 +1,9 @@ +# We don't have any standard include directories, so we can't +# parse the test_common.h header we usually inject as it includes +# system headers. +NO_TEST_COMMON_H := 1 + +CXXFLAGS_EXTRAS = -I $(SRCDIR)/root/usr/include/c++/v1/ -I $(SRCDIR)/root/usr/include/ -nostdinc -nostdinc++ -DENABLE_STD_CONTENT=1 +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/TestEmptyStdModule.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/TestEmptyStdModule.py new file mode 100644 index 00000000000..76e79df5cd1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/TestEmptyStdModule.py @@ -0,0 +1,38 @@ +""" +Test that LLDB doesn't crash if the std module we load is empty. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import os + +class ImportStdModule(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # We only emulate a fake libc++ in this test and don't use the real libc++, + # but we still add the libc++ category so that this test is only run in + # test configurations where libc++ is actually supposed to be tested. + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + sysroot = os.path.join(os.getcwd(), "root") + + # Set the sysroot. + self.runCmd("platform select --sysroot '" + sysroot + "' host", CURRENT_EXECUTABLE_SET) + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + # Use the typedef that is only defined in our 'empty' module. If this fails, then LLDB + # somehow figured out the correct define for the header and compiled the right + # standard module that actually contains the std::vector template. + self.expect("expr MissingContent var = 3; var", substrs=['$0 = 3']) + # Try to access our mock std::vector. This should fail but not crash LLDB as the + # std::vector template should be missing from the std module. + self.expect("expr (size_t)v.size()", substrs=["Couldn't lookup symbols"], error=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/main.cpp new file mode 100644 index 00000000000..b01fe1a7853 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/main.cpp @@ -0,0 +1,8 @@ +#include <algorithm> + +int main(int argc, char **argv) { + // Makes sure we have the mock libc headers in the debug information. + libc_struct s; + std::vector<int> v; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/root/usr/include/c++/v1/algorithm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/root/usr/include/c++/v1/algorithm new file mode 100644 index 00000000000..a77c3d86739 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/root/usr/include/c++/v1/algorithm @@ -0,0 +1,22 @@ +// This is only defined when building, but LLDB is missing this flag when loading the standard +// library module so the actual contents of the module are missing. +#ifdef ENABLE_STD_CONTENT + +#include "libc_header.h" + +namespace std { + inline namespace __1 { + // Pretend to be a std::vector template we need to instantiate + // in LLDB. + template<typename T> + struct vector { T i; int size() { return 2; } }; + } +} +#else +// Unused typedef we can use to check that we actually loaded +// an empty module. Will be missing if LLDB somehow can get the +// ENABLE_STD_CONTENT define right and break this test silently +// (as with the define the module isn't empty anymore and this +// test always succeeds). +typedef int MissingContent; +#endif // ENABLE_STD_CONTENT diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/root/usr/include/c++/v1/module.modulemap b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/root/usr/include/c++/v1/module.modulemap new file mode 100644 index 00000000000..0eb48492a65 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/root/usr/include/c++/v1/module.modulemap @@ -0,0 +1,3 @@ +module std { + module "algorithm" { header "algorithm" export * } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/root/usr/include/libc_header.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/root/usr/include/libc_header.h new file mode 100644 index 00000000000..47525c9db34 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/empty-module/root/usr/include/libc_header.h @@ -0,0 +1 @@ +struct libc_struct {}; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-basic/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-basic/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-basic/TestBasicForwardList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-basic/TestBasicForwardList.py new file mode 100644 index 00000000000..9e45bf23c12 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-basic/TestBasicForwardList.py @@ -0,0 +1,30 @@ +""" +Test basic std::forward_list functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestBasicForwardList(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)std::distance(a.begin(), a.end())", substrs=['(size_t) $0 = 3']) + self.expect("expr (int)a.front()", substrs=['(int) $1 = 3']) + + self.expect("expr a.sort()") + self.expect("expr (int)a.front()", substrs=['(int) $2 = 1']) + + self.expect("expr (int)(*a.begin())", substrs=['(int) $3 = 1']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-basic/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-basic/main.cpp new file mode 100644 index 00000000000..4f5e30f0629 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-basic/main.cpp @@ -0,0 +1,6 @@ +#include <forward_list> + +int main(int argc, char **argv) { + std::forward_list<int> a = {3, 1, 2}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-dbg-info-content/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-dbg-info-content/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-dbg-info-content/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-dbg-info-content/TestDbgInfoContentForwardList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-dbg-info-content/TestDbgInfoContentForwardList.py new file mode 100644 index 00000000000..290a0450fc8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-dbg-info-content/TestDbgInfoContentForwardList.py @@ -0,0 +1,27 @@ +""" +Test std::forward_list functionality with a decl from debug info as content. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestDbgInfoContentForwardList(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)std::distance(a.begin(), a.end())", substrs=['(size_t) $0 = 3']) + self.expect("expr (int)a.front().a", substrs=['(int) $1 = 3']) + + self.expect("expr (int)(a.begin()->a)", substrs=['(int) $2 = 3']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-dbg-info-content/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-dbg-info-content/main.cpp new file mode 100644 index 00000000000..b1ffc4b24cd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/forward_list-dbg-info-content/main.cpp @@ -0,0 +1,10 @@ +#include <forward_list> + +struct Foo { + int a; +}; + +int main(int argc, char **argv) { + std::forward_list<Foo> a = {{3}, {1}, {2}}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-basic/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-basic/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-basic/TestBasicList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-basic/TestBasicList.py new file mode 100644 index 00000000000..e8dfc884739 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-basic/TestBasicList.py @@ -0,0 +1,37 @@ +""" +Test basic std::list functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestBasicList(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)a.size()", substrs=['(size_t) $0 = 3']) + self.expect("expr (int)a.front()", substrs=['(int) $1 = 3']) + self.expect("expr (int)a.back()", substrs=['(int) $2 = 2']) + + self.expect("expr a.sort()") + self.expect("expr (int)a.front()", substrs=['(int) $3 = 1']) + self.expect("expr (int)a.back()", substrs=['(int) $4 = 3']) + + self.expect("expr std::reverse(a.begin(), a.end())") + self.expect("expr (int)a.front()", substrs=['(int) $5 = 3']) + self.expect("expr (int)a.back()", substrs=['(int) $6 = 1']) + + self.expect("expr (int)(*a.begin())", substrs=['(int) $7 = 3']) + self.expect("expr (int)(*a.rbegin())", substrs=['(int) $8 = 1']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-basic/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-basic/main.cpp new file mode 100644 index 00000000000..e54719a02fb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-basic/main.cpp @@ -0,0 +1,6 @@ +#include <list> + +int main(int argc, char **argv) { + std::list<int> a = {3, 1, 2}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-dbg-info-content/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-dbg-info-content/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-dbg-info-content/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-dbg-info-content/TestDbgInfoContentList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-dbg-info-content/TestDbgInfoContentList.py new file mode 100644 index 00000000000..fa8be7cabee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-dbg-info-content/TestDbgInfoContentList.py @@ -0,0 +1,34 @@ +""" +Test basic std::list functionality but with a declaration from +the debug info (the Foo struct) as content. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestDbgInfoContentList(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)a.size()", substrs=['(size_t) $0 = 3']) + self.expect("expr (int)a.front().a", substrs=['(int) $1 = 3']) + self.expect("expr (int)a.back().a", substrs=['(int) $2 = 2']) + + self.expect("expr std::reverse(a.begin(), a.end())") + self.expect("expr (int)a.front().a", substrs=['(int) $3 = 2']) + self.expect("expr (int)a.back().a", substrs=['(int) $4 = 3']) + + self.expect("expr (int)(a.begin()->a)", substrs=['(int) $5 = 2']) + self.expect("expr (int)(a.rbegin()->a)", substrs=['(int) $6 = 3']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-dbg-info-content/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-dbg-info-content/main.cpp new file mode 100644 index 00000000000..3cfb35f8c6b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/list-dbg-info-content/main.cpp @@ -0,0 +1,10 @@ +#include <list> + +struct Foo { + int a; +}; + +int main(int argc, char **argv) { + std::list<Foo> a = {{3}, {1}, {2}}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/no-std-module/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/no-std-module/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/no-std-module/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/no-std-module/TestMissingStdModule.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/no-std-module/TestMissingStdModule.py new file mode 100644 index 00000000000..83d672fb1fd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/no-std-module/TestMissingStdModule.py @@ -0,0 +1,36 @@ +""" +Test that importing the std module on a compile unit +that doesn't use the std module will not break LLDB. + +It's not really specified at the moment what kind of +error we should report back to the user in this +situation. Currently Clang will just complain that +the std module doesn't exist or can't be loaded. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class STLTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + # Activate importing of std module. + self.runCmd("settings set target.import-std-module true") + + # Run some commands that should all fail without our std module. + self.expect("expr std::abs(-42)", error=True) + self.expect("expr std::div(2, 1).quot", error=True) + self.expect("expr (std::size_t)33U", error=True) + self.expect("expr char a = 'b'; char b = 'a'; std::swap(a, b); a", + error=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/no-std-module/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/no-std-module/main.cpp new file mode 100644 index 00000000000..c93e9d0ec8a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/no-std-module/main.cpp @@ -0,0 +1,5 @@ +// We don't import any std module here. + +int main(int argc, char **argv) { + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/queue/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/queue/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/queue/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/queue/TestQueue.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/queue/TestQueue.py new file mode 100644 index 00000000000..42e5f8d8c43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/queue/TestQueue.py @@ -0,0 +1,43 @@ +""" +Tests std::queue functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestQueue(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + # Test std::queue functionality with a std::deque. + self.expect("expr q_deque.pop()") + self.expect("expr q_deque.push({4})") + self.expect("expr (size_t)q_deque.size()", substrs=['(size_t) $0 = 1']) + self.expect("expr (int)q_deque.front().i", substrs=['(int) $1 = 4']) + self.expect("expr (int)q_deque.back().i", substrs=['(int) $2 = 4']) + self.expect("expr q_deque.empty()", substrs=['(bool) $3 = false']) + self.expect("expr q_deque.pop()") + self.expect("expr q_deque.emplace(5)") + self.expect("expr (int)q_deque.front().i", substrs=['(int) $4 = 5']) + + # Test std::queue functionality with a std::list. + self.expect("expr q_list.pop()") + self.expect("expr q_list.push({4})") + self.expect("expr (size_t)q_list.size()", substrs=['(size_t) $5 = 1']) + self.expect("expr (int)q_list.front().i", substrs=['(int) $6 = 4']) + self.expect("expr (int)q_list.back().i", substrs=['(int) $7 = 4']) + self.expect("expr q_list.empty()", substrs=['(bool) $8 = false']) + self.expect("expr q_list.pop()") + self.expect("expr q_list.emplace(5)") + self.expect("expr (int)q_list.front().i", substrs=['(int) $9 = 5']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/queue/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/queue/main.cpp new file mode 100644 index 00000000000..66e8f02c273 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/queue/main.cpp @@ -0,0 +1,16 @@ +#include <deque> +#include <list> +#include <queue> + +struct C { + // Constructor for testing emplace. + C(int i) : i(i) {}; + int i; +}; + +int main(int argc, char **argv) { + // std::deque is the default container. + std::queue<C> q_deque({{1}}); + std::queue<C, std::list<C>> q_list({{1}}); + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr-dbg-info-content/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr-dbg-info-content/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr-dbg-info-content/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr-dbg-info-content/TestSharedPtrDbgInfoContent.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr-dbg-info-content/TestSharedPtrDbgInfoContent.py new file mode 100644 index 00000000000..ec39651b815 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr-dbg-info-content/TestSharedPtrDbgInfoContent.py @@ -0,0 +1,29 @@ +""" +Test std::shared_ptr functionality with a class from debug info as content. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestSharedPtrDbgInfoContent(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (int)s->a", substrs=['(int) $0 = 3']) + self.expect("expr (int)(s->a = 5)", substrs=['(int) $1 = 5']) + self.expect("expr (int)s->a", substrs=['(int) $2 = 5']) + self.expect("expr (bool)s", substrs=['(bool) $3 = true']) + self.expect("expr s.reset()") + self.expect("expr (bool)s", substrs=['(bool) $4 = false']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr-dbg-info-content/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr-dbg-info-content/main.cpp new file mode 100644 index 00000000000..73664f1c83a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr-dbg-info-content/main.cpp @@ -0,0 +1,11 @@ +#include <memory> + +struct Foo { + int a; +}; + +int main(int argc, char **argv) { + std::shared_ptr<Foo> s(new Foo); + s->a = 3; + return s->a; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr/TestSharedPtr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr/TestSharedPtr.py new file mode 100644 index 00000000000..7e05bcca477 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr/TestSharedPtr.py @@ -0,0 +1,29 @@ +""" +Test basic std::shared_ptr functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestSharedPtr(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (int)*s", substrs=['(int) $0 = 3']) + self.expect("expr (int)(*s = 5)", substrs=['(int) $1 = 5']) + self.expect("expr (int)*s", substrs=['(int) $2 = 5']) + self.expect("expr (bool)s", substrs=['(bool) $3 = true']) + self.expect("expr s.reset()") + self.expect("expr (bool)s", substrs=['(bool) $4 = false']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr/main.cpp new file mode 100644 index 00000000000..cb81754087f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/shared_ptr/main.cpp @@ -0,0 +1,7 @@ +#include <memory> + +int main(int argc, char **argv) { + std::shared_ptr<int> s(new int); + *s = 3; + return *s; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/TestStack.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/TestStack.py new file mode 100644 index 00000000000..fe19a4e5f1b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/TestStack.py @@ -0,0 +1,45 @@ +""" +Tests std::stack functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestStack(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + # Test std::stack functionality with a std::deque. + self.expect("expr s_deque.pop()") + self.expect("expr s_deque.push({4})") + self.expect("expr (size_t)s_deque.size()", substrs=['(size_t) $0 = 3']) + self.expect("expr (int)s_deque.top().i", substrs=['(int) $1 = 4']) + self.expect("expr s_deque.emplace(5)") + self.expect("expr (int)s_deque.top().i", substrs=['(int) $2 = 5']) + + # Test std::stack functionality with a std::vector. + self.expect("expr s_vector.pop()") + self.expect("expr s_vector.push({4})") + self.expect("expr (size_t)s_vector.size()", substrs=['(size_t) $3 = 3']) + self.expect("expr (int)s_vector.top().i", substrs=['(int) $4 = 4']) + self.expect("expr s_vector.emplace(5)") + self.expect("expr (int)s_vector.top().i", substrs=['(int) $5 = 5']) + + # Test std::stack functionality with a std::list. + self.expect("expr s_list.pop()") + self.expect("expr s_list.push({4})") + self.expect("expr (size_t)s_list.size()", substrs=['(size_t) $6 = 3']) + self.expect("expr (int)s_list.top().i", substrs=['(int) $7 = 4']) + self.expect("expr s_list.emplace(5)") + self.expect("expr (int)s_list.top().i", substrs=['(int) $8 = 5']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/main.cpp new file mode 100644 index 00000000000..0ce94990733 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/stack/main.cpp @@ -0,0 +1,17 @@ +#include <list> +#include <stack> +#include <vector> + +struct C { + // Constructor for testing emplace. + C(int i) : i(i) {}; + int i; +}; + +int main(int argc, char **argv) { + // std::deque is the default container. + std::stack<C> s_deque({{1}, {2}, {3}}); + std::stack<C, std::vector<C>> s_vector({{1}, {2}, {3}}); + std::stack<C, std::list<C>> s_list({{1}, {2}, {3}}); + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/Makefile new file mode 100644 index 00000000000..4915cdae876 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/Makefile @@ -0,0 +1,9 @@ +# We don't have any standard include directories, so we can't +# parse the test_common.h header we usually inject as it includes +# system headers. +NO_TEST_COMMON_H := 1 + +CXXFLAGS_EXTRAS = -I $(SRCDIR)/root/usr/include/c++/v1/ -I $(SRCDIR)/root/usr/include/ -nostdinc -nostdinc++ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/TestStdModuleSysroot.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/TestStdModuleSysroot.py new file mode 100644 index 00000000000..684e287a69e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/TestStdModuleSysroot.py @@ -0,0 +1,36 @@ +""" +Test that we respect the sysroot when building the std module. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import os + +class ImportStdModule(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # We only emulate a fake libc++ in this test and don't use the real libc++, + # but we still add the libc++ category so that this test is only run in + # test configurations where libc++ is actually supposed to be tested. + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + sysroot = os.path.join(os.getcwd(), "root") + + # Set the sysroot. + self.runCmd("platform select --sysroot '" + sysroot + "' host", CURRENT_EXECUTABLE_SET) + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + # Call our custom function in our sysroot std module. + # If this gives us the correct result, then we used the sysroot. + # We rely on the default argument of -123 to make sure we actually have the C++ module. + # (We don't have default arguments in the debug information). + self.expect("expr std::myabs()", substrs=['(int) $0 = 123']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/main.cpp new file mode 100644 index 00000000000..c01fadc5d8e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/main.cpp @@ -0,0 +1,7 @@ +#include <algorithm> + +int main(int argc, char **argv) { + libc_struct s; + std::vector v; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/root/usr/include/c++/v1/algorithm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/root/usr/include/c++/v1/algorithm new file mode 100644 index 00000000000..a0cb2f15a19 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/root/usr/include/c++/v1/algorithm @@ -0,0 +1,12 @@ +#include "libc_header.h" + +namespace std { + // Makes sure we get a support file for this header. + struct vector { int i; }; + + __attribute__((__nodebug__)) + inline int myabs(int i = -123) { + double nil; + return i < 0 ? -i : i; + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/root/usr/include/c++/v1/module.modulemap b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/root/usr/include/c++/v1/module.modulemap new file mode 100644 index 00000000000..0eb48492a65 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/root/usr/include/c++/v1/module.modulemap @@ -0,0 +1,3 @@ +module std { + module "algorithm" { header "algorithm" export * } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/root/usr/include/libc_header.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/root/usr/include/libc_header.h new file mode 100644 index 00000000000..47525c9db34 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/sysroot/root/usr/include/libc_header.h @@ -0,0 +1 @@ +struct libc_struct {}; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr-dbg-info-content/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr-dbg-info-content/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr-dbg-info-content/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr-dbg-info-content/TestUniquePtrDbgInfoContent.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr-dbg-info-content/TestUniquePtrDbgInfoContent.py new file mode 100644 index 00000000000..9389de97128 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr-dbg-info-content/TestUniquePtrDbgInfoContent.py @@ -0,0 +1,29 @@ +""" +Test std::unique_ptr functionality with a decl from debug info as content. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestUniquePtrDbgInfoContent(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (int)s->a", substrs=['(int) $0 = 3']) + self.expect("expr (int)(s->a = 5)", substrs=['(int) $1 = 5']) + self.expect("expr (int)s->a", substrs=['(int) $2 = 5']) + self.expect("expr (bool)s", substrs=['(bool) $3 = true']) + self.expect("expr s.reset()") + self.expect("expr (bool)s", substrs=['(bool) $4 = false']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr-dbg-info-content/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr-dbg-info-content/main.cpp new file mode 100644 index 00000000000..73664f1c83a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr-dbg-info-content/main.cpp @@ -0,0 +1,11 @@ +#include <memory> + +struct Foo { + int a; +}; + +int main(int argc, char **argv) { + std::shared_ptr<Foo> s(new Foo); + s->a = 3; + return s->a; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr/TestUniquePtr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr/TestUniquePtr.py new file mode 100644 index 00000000000..a0e05b2c420 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr/TestUniquePtr.py @@ -0,0 +1,29 @@ +""" +Test basic std::unique_ptr functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestUniquePtr(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (int)*s", substrs=['(int) $0 = 3']) + self.expect("expr (int)(*s = 5)", substrs=['(int) $1 = 5']) + self.expect("expr (int)*s", substrs=['(int) $2 = 5']) + self.expect("expr (bool)s", substrs=['(bool) $3 = true']) + self.expect("expr s.reset()") + self.expect("expr (bool)s", substrs=['(bool) $4 = false']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr/main.cpp new file mode 100644 index 00000000000..cb81754087f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/unique_ptr/main.cpp @@ -0,0 +1,7 @@ +#include <memory> + +int main(int argc, char **argv) { + std::shared_ptr<int> s(new int); + *s = 3; + return *s; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-basic/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-basic/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-basic/TestBasicVector.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-basic/TestBasicVector.py new file mode 100644 index 00000000000..840bacb86b3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-basic/TestBasicVector.py @@ -0,0 +1,53 @@ +""" +Test basic std::vector functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestBasicVector(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)a.size()", substrs=['(size_t) $0 = 3']) + self.expect("expr (int)a.front()", substrs=['(int) $1 = 3']) + self.expect("expr (int)a[1]", substrs=['(int) $2 = 1']) + self.expect("expr (int)a.back()", substrs=['(int) $3 = 2']) + + self.expect("expr std::sort(a.begin(), a.end())") + self.expect("expr (int)a.front()", substrs=['(int) $4 = 1']) + self.expect("expr (int)a[1]", substrs=['(int) $5 = 2']) + self.expect("expr (int)a.back()", substrs=['(int) $6 = 3']) + + self.expect("expr std::reverse(a.begin(), a.end())") + self.expect("expr (int)a.front()", substrs=['(int) $7 = 3']) + self.expect("expr (int)a[1]", substrs=['(int) $8 = 2']) + self.expect("expr (int)a.back()", substrs=['(int) $9 = 1']) + + self.expect("expr (int)(*a.begin())", substrs=['(int) $10 = 3']) + self.expect("expr (int)(*a.rbegin())", substrs=['(int) $11 = 1']) + + self.expect("expr a.pop_back()") + self.expect("expr (int)a.back()", substrs=['(int) $12 = 2']) + self.expect("expr (size_t)a.size()", substrs=['(size_t) $13 = 2']) + + self.expect("expr (int)a.at(0)", substrs=['(int) $14 = 3']) + + self.expect("expr a.push_back(4)") + self.expect("expr (int)a.back()", substrs=['(int) $15 = 4']) + self.expect("expr (size_t)a.size()", substrs=['(size_t) $16 = 3']) + + self.expect("expr a.emplace_back(5)") + self.expect("expr (int)a.back()", substrs=['(int) $17 = 5']) + self.expect("expr (size_t)a.size()", substrs=['(size_t) $18 = 4']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-basic/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-basic/main.cpp new file mode 100644 index 00000000000..edf130d4748 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-basic/main.cpp @@ -0,0 +1,6 @@ +#include <vector> + +int main(int argc, char **argv) { + std::vector<int> a = {3, 1, 2}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-bool/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-bool/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-bool/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-bool/TestBoolVector.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-bool/TestBoolVector.py new file mode 100644 index 00000000000..45a2507f776 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-bool/TestBoolVector.py @@ -0,0 +1,30 @@ +""" +Test basic std::vector<bool> functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestBoolVector(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)a.size()", substrs=['(size_t) $0 = 4']) + self.expect("expr (bool)a.front()", substrs=['(bool) $1 = false']) + self.expect("expr (bool)a[1]", substrs=['(bool) $2 = true']) + self.expect("expr (bool)a.back()", substrs=['(bool) $3 = true']) + + self.expect("expr (bool)(*a.begin())", substrs=['(bool) $4 = false']) + self.expect("expr (bool)(*a.rbegin())", substrs=['(bool) $5 = true']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-bool/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-bool/main.cpp new file mode 100644 index 00000000000..9554401cf50 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-bool/main.cpp @@ -0,0 +1,6 @@ +#include <vector> + +int main(int argc, char **argv) { + std::vector<bool> a = {0, 1, 0, 1}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/TestDbgInfoContentVector.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/TestDbgInfoContentVector.py new file mode 100644 index 00000000000..4d51f1ba3b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/TestDbgInfoContentVector.py @@ -0,0 +1,43 @@ +""" +Test basic std::vector functionality but with a declaration from +the debug info (the Foo struct) as content. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestDbgInfoContentVector(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)a.size()", substrs=['(size_t) $0 = 3']) + self.expect("expr (int)a.front().a", substrs=['(int) $1 = 3']) + self.expect("expr (int)a[1].a", substrs=['(int) $2 = 1']) + self.expect("expr (int)a.back().a", substrs=['(int) $3 = 2']) + + self.expect("expr std::reverse(a.begin(), a.end())") + self.expect("expr (int)a.front().a", substrs=['(int) $4 = 2']) + + self.expect("expr (int)(a.begin()->a)", substrs=['(int) $5 = 2']) + self.expect("expr (int)(a.rbegin()->a)", substrs=['(int) $6 = 3']) + + self.expect("expr a.pop_back()") + self.expect("expr (int)a.back().a", substrs=['(int) $7 = 1']) + self.expect("expr (size_t)a.size()", substrs=['(size_t) $8 = 2']) + + self.expect("expr (int)a.at(0).a", substrs=['(int) $9 = 2']) + + self.expect("expr a.push_back({4})") + self.expect("expr (int)a.back().a", substrs=['(int) $10 = 4']) + self.expect("expr (size_t)a.size()", substrs=['(size_t) $11 = 3']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/main.cpp new file mode 100644 index 00000000000..24c3fec75d2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-dbg-info-content/main.cpp @@ -0,0 +1,10 @@ +#include <vector> + +struct Foo { + int a; +}; + +int main(int argc, char **argv) { + std::vector<Foo> a = {{3}, {1}, {2}}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-of-vectors/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-of-vectors/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-of-vectors/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectors.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectors.py new file mode 100644 index 00000000000..feaeac9be5e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectors.py @@ -0,0 +1,26 @@ +""" +Test std::vector functionality when it's contents are vectors. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestVectorOfVectors(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (size_t)a.size()", substrs=['(size_t) $0 = 2']) + self.expect("expr (int)a.front().front()", substrs=['(int) $1 = 1']) + self.expect("expr (int)a[1][1]", substrs=['(int) $2 = 2']) + self.expect("expr (int)a.back().at(0)", substrs=['(int) $3 = 3']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-of-vectors/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-of-vectors/main.cpp new file mode 100644 index 00000000000..b5ada909e43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/vector-of-vectors/main.cpp @@ -0,0 +1,6 @@ +#include <vector> + +int main(int argc, char **argv) { + std::vector<std::vector<int> > a = {{1, 2, 3}, {3, 2, 1}}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr-dbg-info-content/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr-dbg-info-content/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr-dbg-info-content/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr-dbg-info-content/TestDbgInfoContentWeakPtr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr-dbg-info-content/TestDbgInfoContentWeakPtr.py new file mode 100644 index 00000000000..5ed30312ea7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr-dbg-info-content/TestDbgInfoContentWeakPtr.py @@ -0,0 +1,29 @@ +""" +Test std::weak_ptr functionality with a decl from debug info as content. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestDbgInfoContentWeakPtr(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (int)w.lock()->a", substrs=['(int) $0 = 3']) + self.expect("expr (int)(w.lock()->a = 5)", substrs=['(int) $1 = 5']) + self.expect("expr (int)w.lock()->a", substrs=['(int) $2 = 5']) + self.expect("expr w.use_count()", substrs=['(long) $3 = 1']) + self.expect("expr w.reset()") + self.expect("expr w.use_count()", substrs=['(long) $4 = 0']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr-dbg-info-content/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr-dbg-info-content/main.cpp new file mode 100644 index 00000000000..d2c5a6258a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr-dbg-info-content/main.cpp @@ -0,0 +1,12 @@ +#include <memory> + +struct Foo { + int a; +}; + +int main(int argc, char **argv) { + std::shared_ptr<Foo> s(new Foo); + s->a = 3; + std::weak_ptr<Foo> w = s; + return s->a; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr/Makefile new file mode 100644 index 00000000000..f938f742846 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr/Makefile @@ -0,0 +1,3 @@ +USE_LIBCPP := 1 +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr/TestWeakPtr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr/TestWeakPtr.py new file mode 100644 index 00000000000..76241740b68 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr/TestWeakPtr.py @@ -0,0 +1,29 @@ +""" +Test basic std::weak_ptr functionality. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestSharedPtr(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + @skipIf(compiler=no_match("clang")) + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.runCmd("settings set target.import-std-module true") + + self.expect("expr (int)*w.lock()", substrs=['(int) $0 = 3']) + self.expect("expr (int)(*w.lock() = 5)", substrs=['(int) $1 = 5']) + self.expect("expr (int)*w.lock()", substrs=['(int) $2 = 5']) + self.expect("expr w.use_count()", substrs=['(long) $3 = 1']) + self.expect("expr w.reset()") + self.expect("expr w.use_count()", substrs=['(long) $4 = 0']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr/main.cpp new file mode 100644 index 00000000000..13479eb9496 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import-std-module/weak_ptr/main.cpp @@ -0,0 +1,8 @@ +#include <memory> + +int main(int argc, char **argv) { + std::shared_ptr<int> s(new int); + *s = 3; + std::weak_ptr<int> w = s; + return *s; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import_builtin_fileid/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import_builtin_fileid/Makefile new file mode 100644 index 00000000000..b46bd7f39a9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import_builtin_fileid/Makefile @@ -0,0 +1,3 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -framework Cocoa +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import_builtin_fileid/TestImportBuiltinFileID.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import_builtin_fileid/TestImportBuiltinFileID.py new file mode 100644 index 00000000000..08b6a8c90f5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import_builtin_fileid/TestImportBuiltinFileID.py @@ -0,0 +1,27 @@ +""" +They may be cases where an expression will import SourceLocation and if the +SourceLocation ends up with a FileID that is a built-in we need to copy that +buffer over correctly. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestImportBuiltinFileID(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded + @add_test_categories(["gmodules"]) + def test_import_builtin_fileid(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.m", False)) + + self.expect("expr int (*DBG_CGImageGetRenderingIntent)(void *) = ((int (*)(void *))CGImageGetRenderingIntent); DBG_CGImageGetRenderingIntent((void *)0x00000000000000);", + substrs=['$0 = 0']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import_builtin_fileid/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import_builtin_fileid/main.m new file mode 100644 index 00000000000..ef74940b0ac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/import_builtin_fileid/main.m @@ -0,0 +1,6 @@ +#import <Cocoa/Cocoa.h> + +int main(int argc, const char * argv[]) { + + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/inline-namespace/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/inline-namespace/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/inline-namespace/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/inline-namespace/TestInlineNamespace.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/inline-namespace/TestInlineNamespace.py new file mode 100644 index 00000000000..b17115be292 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/inline-namespace/TestInlineNamespace.py @@ -0,0 +1,26 @@ +""" +Test that we correctly handle inline namespaces. +""" + +import lldb + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestInlineNamespace(TestBase): + mydir = TestBase.compute_mydir(__file__) + + def test(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + # The 'A::B::f' function must be found via 'A::f' as 'B' is an inline + # namespace. + self.expect("expr A::f()", substrs=['$0 = 3']) + # But we should still find the function when we pretend the inline + # namespace is not inline. + self.expect("expr A::B::f()", substrs=['$1 = 3']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/inline-namespace/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/inline-namespace/main.cpp new file mode 100644 index 00000000000..c10b361a0cd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/inline-namespace/main.cpp @@ -0,0 +1,10 @@ +namespace A { + inline namespace B { + int f() { return 3; } + }; +} + +int main(int argc, char **argv) { + // Set break point at this line. + return A::f(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/invalid-args/TestInvalidArgsExpression.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/invalid-args/TestInvalidArgsExpression.py new file mode 100644 index 00000000000..e0ede0a4e2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/invalid-args/TestInvalidArgsExpression.py @@ -0,0 +1,45 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +class InvalidArgsExpressionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_invalid_lang(self): + self.expect("expression -l foo --", error=True, + substrs=["error: unknown language type: 'foo' for expression"]) + + @no_debug_info_test + def test_invalid_all_thread(self): + self.expect("expression -a foo --", error=True, + substrs=['error: invalid all-threads value setting: "foo"']) + + @no_debug_info_test + def test_invalid_ignore_br(self): + self.expect("expression -i foo --", error=True, + substrs=['error: could not convert "foo" to a boolean value.']) + + @no_debug_info_test + def test_invalid_allow_jit(self): + self.expect("expression -j foo --", error=True, + substrs=['error: could not convert "foo" to a boolean value.']) + + @no_debug_info_test + def test_invalid_timeout(self): + self.expect("expression -t foo --", error=True, + substrs=['error: invalid timeout setting "foo"']) + + self.expect("expression -t \"\" --", error=True, + substrs=['error: invalid timeout setting ""']) + + @no_debug_info_test + def test_invalid_unwind(self): + self.expect("expression -u foo --", error=True, + substrs=['error: could not convert "foo" to a boolean value.']) + + @no_debug_info_test + def test_invalid_fixits(self): + self.expect("expression -X foo --", error=True, + substrs=['error: could not convert "foo" to a boolean value.']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter-phi-nodes/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter-phi-nodes/Makefile new file mode 100644 index 00000000000..a1f689e07c7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter-phi-nodes/Makefile @@ -0,0 +1,4 @@ +
+CXX_SOURCES := main.cpp
+
+include Makefile.rules
diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py new file mode 100644 index 00000000000..20a9477b1f7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter-phi-nodes/TestIRInterpreterPHINodes.py @@ -0,0 +1,41 @@ +""" +Test PHI nodes work in the IR interpreter. +""" + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class IRInterpreterPHINodesTestCase(TestBase): + mydir = TestBase.compute_mydir(__file__) + + def test_phi_node_support(self): + """Test support for PHI nodes in the IR interpreter.""" + + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd('file ' + exe, CURRENT_EXECUTABLE_SET) + + # Break on the first assignment to i + line = line_number('main.cpp', 'i = 5') + lldbutil.run_break_set_by_file_and_line( + self, 'main.cpp', line, num_expected_locations=1, loc_exact=True) + + self.runCmd('run', RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint + self.expect('thread list', STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.runCmd('s') + + # The logical 'or' causes a PHI node to be generated. Execute without JIT + # to test that the interpreter can handle this + self.expect('expr -j 0 -- i == 3 || i == 5', substrs=['true']) + + self.runCmd('s') + self.expect('expr -j 0 -- i == 3 || i == 5', substrs=['false']) + self.runCmd('s') + self.expect('expr -j 0 -- i == 3 || i == 5', substrs=['true']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter-phi-nodes/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter-phi-nodes/main.cpp new file mode 100644 index 00000000000..8e181aeba3b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter-phi-nodes/main.cpp @@ -0,0 +1,16 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main() +{ + int i; + i = 5; + i = 2; + i = 3; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter/Makefile new file mode 100644 index 00000000000..00a9da08656 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter/Makefile @@ -0,0 +1,5 @@ +default: a.out + +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter/TestIRInterpreter.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter/TestIRInterpreter.py new file mode 100644 index 00000000000..dd1308ba58f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter/TestIRInterpreter.py @@ -0,0 +1,93 @@ +""" +Test the IR interpreter +""" + + +import unittest2 + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class IRInterpreterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number('main.c', + '// Set breakpoint here') + + # Disable confirmation prompt to avoid infinite wait + self.runCmd("settings set auto-confirm true") + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) + + def build_and_run(self): + """Test the IR interpreter""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=False) + + self.runCmd("run", RUN_SUCCEEDED) + + @add_test_categories(['pyapi']) + # getpid() is POSIX, among other problems, see bug + @expectedFailureAll( + oslist=['windows'], + bugnumber="http://llvm.org/pr21765") + @expectedFailureNetBSD + @expectedFailureAll( + oslist=['linux'], + archs=['arm'], + bugnumber="llvm.org/pr27868") + def test_ir_interpreter(self): + self.build_and_run() + + options = lldb.SBExpressionOptions() + options.SetLanguage(lldb.eLanguageTypeC_plus_plus) + + set_up_expressions = ["int $i = 9", "int $j = 3", "int $k = 5"] + + expressions = ["$i + $j", + "$i - $j", + "$i * $j", + "$i / $j", + "$i % $k", + "$i << $j", + "$i & $j", + "$i | $j", + "$i ^ $j"] + + for expression in set_up_expressions: + self.frame().EvaluateExpression(expression, options) + + for expression in expressions: + interp_expression = expression + jit_expression = "(int)getpid(); " + expression + + interp_result = self.frame().EvaluateExpression( + interp_expression, options).GetValueAsSigned() + jit_result = self.frame().EvaluateExpression( + jit_expression, options).GetValueAsSigned() + + self.assertEqual( + interp_result, + jit_result, + "While evaluating " + + expression) + + def test_type_conversions(self): + target = self.dbg.GetDummyTarget() + short_val = target.EvaluateExpression("(short)-1") + self.assertEqual(short_val.GetValueAsSigned(), -1) + long_val = target.EvaluateExpression("(long) "+ short_val.GetName()) + self.assertEqual(long_val.GetValueAsSigned(), -1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter/main.c new file mode 100644 index 00000000000..31204b21d97 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/ir-interpreter/main.c @@ -0,0 +1,7 @@ +#include <stdio.h> + +int main() +{ + printf("This is a dummy\n"); // Set breakpoint here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/Test11588.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/Test11588.py new file mode 100644 index 00000000000..abff18f3fa1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/Test11588.py @@ -0,0 +1,66 @@ +""" +Test the solution to issue 11581. +valobj.AddressOf() returns None when an address is +expected in a SyntheticChildrenProvider +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class Issue11581TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_11581_commands(self): + # This is the function to remove the custom commands in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type synthetic clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + """valobj.AddressOf() should return correct values.""" + self.build() + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + 'Set breakpoint here.', + lldb.SBFileSpec("main.cpp", False)) + self.runCmd("command script import --allow-reload s11588.py") + self.runCmd( + "type synthetic add --python-class s11588.Issue11581SyntheticProvider StgClosure") + + self.expect("expr --show-types -- *((StgClosure*)(r14-1))", + substrs=["(StgClosure) $", + "(StgClosure *) &$", "0x", + "addr = ", + "load_address = "]) + + # register r14 is an x86_64 extension let's skip this part of the test + # if we are on a different architecture + if self.getArchitecture() == 'x86_64': + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + frame = process.GetSelectedThread().GetSelectedFrame() + pointer = frame.FindVariable("r14") + addr = pointer.GetValueAsUnsigned(0) + self.assertTrue(addr != 0, "could not read pointer to StgClosure") + addr = addr - 1 + self.runCmd("register write r14 %d" % addr) + self.expect( + "register read r14", substrs=[ + "0x", hex(addr)[ + 2:].rstrip("L")]) # Remove trailing 'L' if it exists + self.expect("expr --show-types -- *(StgClosure*)$r14", + substrs=["(StgClosure) $", + "(StgClosure *) &$", "0x", + "addr = ", + "load_address = ", + hex(addr)[2:].rstrip("L"), + str(addr)]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/main.cpp new file mode 100644 index 00000000000..4f9ea3abf18 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/main.cpp @@ -0,0 +1,54 @@ +// +// 11588.cpp +// + +#include <iostream> + +class StgInfoTable {}; + +class StgHeader +{ +private: + StgInfoTable* info; +public: + StgHeader() + { + info = new StgInfoTable(); + } + ~StgHeader() + { + delete info; + } +}; + +class StgClosure +{ +private: + StgHeader header; + StgClosure* payload[1]; +public: + StgClosure(bool make_payload = true) + { + if (make_payload) + payload[0] = new StgClosure(false); + else + payload[0] = NULL; + } + ~StgClosure() + { + if (payload[0]) + delete payload[0]; + } +}; + +typedef unsigned long long int ptr_type; + +int main() +{ + StgClosure* r14_ = new StgClosure(); + r14_ = (StgClosure*)(((ptr_type)r14_ | 0x01)); // set the LSB to 1 for tagging + ptr_type r14 = (ptr_type)r14_; + int x = 0; + x = 3; + return (x-1); // Set breakpoint here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/s11588.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/s11588.py new file mode 100644 index 00000000000..51c20423ed3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/issue_11588/s11588.py @@ -0,0 +1,28 @@ +class Issue11581SyntheticProvider(object): + + def __init__(self, valobj, dict): + self.valobj = valobj + self.addrOf = valobj.AddressOf() + self.addr = valobj.GetAddress() + self.load_address = valobj.GetLoadAddress() + + def num_children(self): + return 3 + + def get_child_at_index(self, index): + if index == 0: + return self.addrOf + if index == 1: + return self.valobj.CreateValueFromExpression( + "addr", str(self.addr)) + if index == 2: + return self.valobj.CreateValueFromExpression( + "load_address", str(self.load_address)) + + def get_child_index(self, name): + if name == "addrOf": + return 0 + if name == "addr": + return 1 + if name == "load_address": + return 2 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/Makefile new file mode 100644 index 00000000000..a2af5c4ce70 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/Makefile @@ -0,0 +1,9 @@ +CXX_SOURCES := main.cpp + +DEBUG_INFO_FLAG = -g3 -gdwarf-5 + +# GCC produces incorrect .debug_macro section when "-include" option is used: +# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93075. +NO_TEST_COMMON_H := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/TestMacros.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/TestMacros.py new file mode 100644 index 00000000000..aed83e224e5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/TestMacros.py @@ -0,0 +1,133 @@ + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestMacros(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + compiler="clang", + bugnumber="clang does not emit .debug_macro[.dwo] sections.") + @expectedFailureAll( + debug_info="dwo", + bugnumber="GCC produces multiple .debug_macro.dwo sections and the spec is unclear as to what it means") + @expectedFailureAll( + hostoslist=["windows"], + compiler="gcc", + triple='.*-android') + @expectedFailureAll( + compiler="gcc", compiler_version=['<', '5.1'], + bugnumber=".debug_macro was introduced in DWARF 5, GCC supports it since version 5.1") + def test_expr_with_macros(self): + self.build() + + # Get main source file + src_file = "main.cpp" + hdr_file = "macro1.h" + src_file_spec = lldb.SBFileSpec(src_file) + self.assertTrue(src_file_spec.IsValid(), "Main source file") + + (target, process, thread, bp1) = lldbutil.run_to_source_breakpoint( + self, "Break here", src_file_spec) + + # Get frame for current thread + frame = thread.GetSelectedFrame() + + result = frame.EvaluateExpression("MACRO_1") + self.assertTrue( + result.IsValid() and result.GetValue() == "100", + "MACRO_1 = 100") + + result = frame.EvaluateExpression("MACRO_2") + self.assertTrue( + result.IsValid() and result.GetValue() == "200", + "MACRO_2 = 200") + + result = frame.EvaluateExpression("ONE") + self.assertTrue( + result.IsValid() and result.GetValue() == "1", + "ONE = 1") + + result = frame.EvaluateExpression("TWO") + self.assertTrue( + result.IsValid() and result.GetValue() == "2", + "TWO = 2") + + result = frame.EvaluateExpression("THREE") + self.assertTrue( + result.IsValid() and result.GetValue() == "3", + "THREE = 3") + + result = frame.EvaluateExpression("FOUR") + self.assertTrue( + result.IsValid() and result.GetValue() == "4", + "FOUR = 4") + + result = frame.EvaluateExpression("HUNDRED") + self.assertTrue( + result.IsValid() and result.GetValue() == "100", + "HUNDRED = 100") + + result = frame.EvaluateExpression("THOUSAND") + self.assertTrue( + result.IsValid() and result.GetValue() == "1000", + "THOUSAND = 1000") + + result = frame.EvaluateExpression("MILLION") + self.assertTrue(result.IsValid() and result.GetValue() + == "1000000", "MILLION = 1000000") + + result = frame.EvaluateExpression("MAX(ONE, TWO)") + self.assertTrue( + result.IsValid() and result.GetValue() == "2", + "MAX(ONE, TWO) = 2") + + result = frame.EvaluateExpression("MAX(THREE, TWO)") + self.assertTrue( + result.IsValid() and result.GetValue() == "3", + "MAX(THREE, TWO) = 3") + + # Get the thread of the process + thread.StepOver() + + # Get frame for current thread + frame = thread.GetSelectedFrame() + + result = frame.EvaluateExpression("MACRO_2") + self.assertTrue( + result.GetError().Fail(), + "Printing MACRO_2 fails in the mail file") + + result = frame.EvaluateExpression("FOUR") + self.assertTrue( + result.GetError().Fail(), + "Printing FOUR fails in the main file") + + thread.StepInto() + + # Get frame for current thread + frame = thread.GetSelectedFrame() + + result = frame.EvaluateExpression("ONE") + self.assertTrue( + result.IsValid() and result.GetValue() == "1", + "ONE = 1") + + result = frame.EvaluateExpression("MAX(ONE, TWO)") + self.assertTrue( + result.IsValid() and result.GetValue() == "2", + "MAX(ONE, TWO) = 2") + + # This time, MACRO_1 and MACRO_2 are not visible. + result = frame.EvaluateExpression("MACRO_1") + self.assertTrue(result.GetError().Fail(), + "Printing MACRO_1 fails in the header file") + + result = frame.EvaluateExpression("MACRO_2") + self.assertTrue(result.GetError().Fail(), + "Printing MACRO_2 fails in the header file") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/macro1.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/macro1.h new file mode 100644 index 00000000000..e026bc018ac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/macro1.h @@ -0,0 +1,17 @@ + +#include "macro2.h" + +#define ONE 1 +#define TWO 2 +#define THREE 3 +#define FOUR 4 + +class Simple +{ +public: + int + Method() + { + return ONE + TWO; + }; +}; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/macro2.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/macro2.h new file mode 100644 index 00000000000..cec6efbba99 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/macro2.h @@ -0,0 +1,8 @@ +#define HUNDRED 100 +#define THOUSAND 1000 +#define MILLION 1000000 + +#define MAX(a, b)\ +((a) > (b) ?\ + (a):\ + (b)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/main.cpp new file mode 100644 index 00000000000..f2c2c101fa1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/macros/main.cpp @@ -0,0 +1,15 @@ +#include "macro1.h" + +#define MACRO_1 100 +#define MACRO_2 200 + +int +main () +{ + int a = ONE + TWO; // Break here + + #undef MACRO_2 + #undef FOUR + + return Simple().Method(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-completion/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-completion/Makefile new file mode 100644 index 00000000000..c9319d6e688 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-completion/Makefile @@ -0,0 +1,2 @@ +C_SOURCES := main.c +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-completion/TestMultilineCompletion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-completion/TestMultilineCompletion.py new file mode 100644 index 00000000000..9b2b71230e5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-completion/TestMultilineCompletion.py @@ -0,0 +1,35 @@ +""" +Test completion for multiline expressions. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test.lldbpexpect import PExpectTest + +class MultilineCompletionTest(PExpectTest): + + mydir = TestBase.compute_mydir(__file__) + + # PExpect uses many timeouts internally and doesn't play well + # under ASAN on a loaded machine.. + @skipIfAsan + @skipIfRemote # test is written to explicitly "run" the binary + @skipIfEditlineSupportMissing + def test_basic_completion(self): + """Test that we can complete a simple multiline expression""" + self.build() + + self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100,500)) + self.expect("b main", substrs=["Breakpoint 1", "address ="]) + self.expect("run", substrs=["stop reason ="]) + + self.child.sendline("expr") + self.child.expect_exact("terminate with an empty line to evaluate") + self.child.send("to_\t") + self.child.expect_exact("to_complete") + + self.child.send("\n\n") + self.expect_prompt() + + self.quit() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-completion/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-completion/main.c new file mode 100644 index 00000000000..6dd3616c1ae --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-completion/main.c @@ -0,0 +1,4 @@ +int main(int argc, char **argv) { + int to_complete = 0; + return to_complete; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-navigation/TestMultilineNavigation.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-navigation/TestMultilineNavigation.py new file mode 100644 index 00000000000..743e7994536 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/multiline-navigation/TestMultilineNavigation.py @@ -0,0 +1,69 @@ +""" +Tests navigating in the multiline expression editor. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test.lldbpexpect import PExpectTest + +class TestCase(PExpectTest): + + mydir = TestBase.compute_mydir(__file__) + + arrow_up = "\033[A" + arrow_down = "\033[B" + + # PExpect uses many timeouts internally and doesn't play well + # under ASAN on a loaded machine.. + @skipIfAsan + @skipIfEditlineSupportMissing + def test_nav_arrow_up(self): + """Tests that we can navigate back to the previous line with the up arrow""" + self.launch() + + # Start multiline expression mode by just running 'expr' + self.child.sendline("expr") + self.child.expect_exact("terminate with an empty line to evaluate") + # Create a simple integer expression '123' and press enter. + self.child.send("123\n") + # We should see the prompt for the second line of our expression. + self.child.expect_exact("2: ") + # Go back to the first line and change 123 to 124. + # Then press enter twice to evaluate our expression. + self.child.send(self.arrow_up + "\b4\n\n") + # The result of our expression should be 124 (our edited expression) + # and not 123 (the one we initially typed). + self.child.expect_exact("(int) $0 = 124") + + self.quit() + + @skipIfAsan + @skipIfEditlineSupportMissing + def test_nav_arrow_down(self): + """Tests that we can navigate to the next line with the down arrow""" + self.launch() + + # Start multiline expression mode by just running 'expr' + self.child.sendline("expr") + self.child.expect_exact("terminate with an empty line to evaluate") + # Create a simple integer expression '111' and press enter. + self.child.send("111\n") + # We should see the prompt for the second line of our expression. + self.child.expect_exact("2: ") + # Create another simple integer expression '222'. + self.child.send("222") + # Go back to the first line and change '111' to '111+' to make + # an addition operation that spans two lines. We need to go up to + # test that we can go back down again. + self.child.send(self.arrow_up + "+") + # Go back down to our second line and change '222' to '223' + # so that the full expression is now '111+\n223'. + # Then press enter twice to evaluate the expression. + self.child.send(self.arrow_down + "\b3\n\n") + # The result of our expression '111 + 223' should be '334'. + # If the expression is '333' then arrow down failed to get + # us back to the second line. + self.child.expect_exact("(int) $0 = 334") + + self.quit() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_cpp_and_c/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_cpp_and_c/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_cpp_and_c/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_cpp_and_c/TestNamespaceLocalVarSameNameCppAndC.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_cpp_and_c/TestNamespaceLocalVarSameNameCppAndC.py new file mode 100644 index 00000000000..ab2ddd07480 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_cpp_and_c/TestNamespaceLocalVarSameNameCppAndC.py @@ -0,0 +1,24 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestNamespaceLocalVarSameNameCppAndC(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @add_test_categories(["gmodules"]) + def test_namespace_local_var_same_name_cpp_and_c(self): + self.build() + + (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + self.expect("expr error", + substrs=['(int) $0 = 1']) + + lldbutil.continue_to_breakpoint(self.process, bkpt) + + self.expect("expr error", + substrs=['(int) $1 = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_cpp_and_c/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_cpp_and_c/main.cpp new file mode 100644 index 00000000000..5e8237ed190 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_cpp_and_c/main.cpp @@ -0,0 +1,21 @@ +namespace error { +int x; +} + +struct A { + void foo() { + int error = 1; + + return; // break here + } +}; + +int main() { + int error = 1; + + A a; + + a.foo(); + + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/Makefile new file mode 100644 index 00000000000..4d12ff1b43e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/Makefile @@ -0,0 +1,5 @@ +OBJCXX_SOURCES := main.mm util.mm + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/TestNamespaceLocalVarSameNameObjC.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/TestNamespaceLocalVarSameNameObjC.py new file mode 100644 index 00000000000..eb894cc37e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/TestNamespaceLocalVarSameNameObjC.py @@ -0,0 +1,24 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestNamespaceLocalVarSameNameObjC(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @add_test_categories(["gmodules"]) + def test_namespace_local_var_same_name_obj_c(self): + self.build() + + (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("util.mm", False)) + + self.expect("expr error", + substrs=['(NSError *) $0 =']) + + lldbutil.continue_to_breakpoint(self.process, bkpt) + + self.expect("expr error", + substrs=['(NSError *) $1 =']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/main.mm new file mode 100644 index 00000000000..70e9598eefb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/main.mm @@ -0,0 +1,16 @@ +#import <Foundation/Foundation.h> +@interface Util : NSObject ++ (void)debugPrintErrorStatic; +- (void)debugPrintError; +@end + +int main(int argc, const char * argv[]) { + [Util debugPrintErrorStatic]; + + Util *u = [[Util alloc] init]; + + [u debugPrintError]; + + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/util.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/util.mm new file mode 100644 index 00000000000..11c9c141df0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/namespace_local_var_same_name_obj_c/util.mm @@ -0,0 +1,22 @@ +#import <Foundation/Foundation.h> + +namespace error { +int blah; +} + +@interface Util : NSObject ++ (void)debugPrintErrorStatic; +- (void)debugPrintError; +@end + +@implementation Util ++ (void)debugPrintErrorStatic { + NSError* error = [NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:nil]; + NSLog(@"xxx, error = %@", error); // break here +} + +- (void)debugPrintError { + NSError* error = [NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:nil]; + NSLog(@"xxx, error = %@", error); // break here +} +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/no-deadlock/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/no-deadlock/Makefile new file mode 100644 index 00000000000..4b3467bc4e8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/no-deadlock/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := locking.cpp +CXXFLAGS_EXTRAS := -std=c++11 +ENABLE_THREADS := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/no-deadlock/TestExprDoesntBlock.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/no-deadlock/TestExprDoesntBlock.py new file mode 100644 index 00000000000..d7d963390b0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/no-deadlock/TestExprDoesntBlock.py @@ -0,0 +1,57 @@ +""" +Test that expr will time out and allow other threads to run if it blocks. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprDoesntDeadlockTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr17946') + @add_test_categories(["basic_process"]) + def test_with_run_command(self): + """Test that expr will time out and allow other threads to run if it blocks.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint at source line before call_me_to_get_lock + # gets called. + + main_file_spec = lldb.SBFileSpec("locking.cpp") + breakpoint = target.BreakpointCreateBySourceRegex( + 'Break here', main_file_spec) + if self.TraceOn(): + print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.line1 and the break condition should hold. + from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + + frame0 = thread.GetFrameAtIndex(0) + + var = frame0.EvaluateExpression("call_me_to_get_lock(get_int())") + self.assertTrue(var.IsValid()) + self.assertEqual(var.GetValueAsSigned(0), 567) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/no-deadlock/locking.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/no-deadlock/locking.cpp new file mode 100644 index 00000000000..8288a668fe8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/no-deadlock/locking.cpp @@ -0,0 +1,78 @@ +#include <stdio.h> +#include <thread> +#include <mutex> +#include <condition_variable> + +std::mutex contended_mutex; + +std::mutex control_mutex; +std::condition_variable control_condition; + +std::mutex thread_started_mutex; +std::condition_variable thread_started_condition; + +// This function runs in a thread. The locking dance is to make sure that +// by the time the main thread reaches the pthread_join below, this thread +// has for sure acquired the contended_mutex. So then the call_me_to_get_lock +// function will block trying to get the mutex, and only succeed once it +// signals this thread, then lets it run to wake up from the cond_wait and +// release the mutex. + +void +lock_acquirer_1 (void) +{ + std::unique_lock<std::mutex> contended_lock(contended_mutex); + + // Grab this mutex, that will ensure that the main thread + // is in its cond_wait for it (since that's when it drops the mutex. + + thread_started_mutex.lock(); + thread_started_mutex.unlock(); + + // Now signal the main thread that it can continue, we have the contended lock + // so the call to call_me_to_get_lock won't make any progress till this + // thread gets a chance to run. + + std::unique_lock<std::mutex> control_lock(control_mutex); + + thread_started_condition.notify_all(); + + control_condition.wait(control_lock); + +} + +int +call_me_to_get_lock (int ret_val) +{ + control_condition.notify_all(); + contended_mutex.lock(); + return ret_val; +} + +int +get_int() { + return 567; +} + +int main () +{ + std::unique_lock<std::mutex> thread_started_lock(thread_started_mutex); + + std::thread thread_1(lock_acquirer_1); + + thread_started_condition.wait(thread_started_lock); + + control_mutex.lock(); + control_mutex.unlock(); + + // Break here. At this point the other thread will have the contended_mutex, + // and be sitting in its cond_wait for the control condition. So there is + // no way that our by-hand calling of call_me_to_get_lock will proceed + // without running the first thread at least somewhat. + + int result = call_me_to_get_lock(get_int()); + thread_1.join(); + + return 0; + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/Makefile new file mode 100644 index 00000000000..7df22699c57 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp foo.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/TestExprOptions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/TestExprOptions.py new file mode 100644 index 00000000000..833833a866f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/TestExprOptions.py @@ -0,0 +1,90 @@ +""" +Test expression command options. + +Test cases: + +o test_expr_options: + Test expression command options. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class ExprOptionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + self.line = line_number('main.cpp', '// breakpoint_in_main') + self.exe = self.getBuildArtifact("a.out") + + def test_expr_options(self): + """These expression command options should work as expected.""" + self.build() + + # Set debugger into synchronous mode + self.dbg.SetAsync(False) + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, '// breakpoint_in_main', self.main_source_spec) + + frame = thread.GetFrameAtIndex(0) + options = lldb.SBExpressionOptions() + + # test --language on C++ expression using the SB API's + + # Make sure we can evaluate a C++11 expression. + val = frame.EvaluateExpression('foo != nullptr') + self.assertTrue(val.IsValid()) + self.assertTrue(val.GetError().Success()) + self.DebugSBValue(val) + + # Make sure it still works if language is set to C++11: + options.SetLanguage(lldb.eLanguageTypeC_plus_plus_11) + val = frame.EvaluateExpression('foo != nullptr', options) + self.assertTrue(val.IsValid()) + self.assertTrue(val.GetError().Success()) + self.DebugSBValue(val) + + # Make sure it fails if language is set to C: + options.SetLanguage(lldb.eLanguageTypeC) + val = frame.EvaluateExpression('foo != nullptr', options) + self.assertTrue(val.IsValid()) + self.assertFalse(val.GetError().Success()) + + @skipIfDarwin + def test_expr_options_lang(self): + """These expression language options should work as expected.""" + self.build() + + # Set debugger into synchronous mode + self.dbg.SetAsync(False) + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, '// breakpoint_in_main', self.main_source_spec) + + frame = thread.GetFrameAtIndex(0) + options = lldb.SBExpressionOptions() + + # Make sure we can retrieve `id` variable if language is set to C++11: + options.SetLanguage(lldb.eLanguageTypeC_plus_plus_11) + val = frame.EvaluateExpression('id == 0', options) + self.assertTrue(val.IsValid()) + self.assertTrue(val.GetError().Success()) + self.DebugSBValue(val) + + # Make sure we can't retrieve `id` variable if language is set to ObjC: + options.SetLanguage(lldb.eLanguageTypeObjC) + val = frame.EvaluateExpression('id == 0', options) + self.assertTrue(val.IsValid()) + self.assertFalse(val.GetError().Success()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/foo.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/foo.cpp new file mode 100644 index 00000000000..8a5a6a2b541 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/foo.cpp @@ -0,0 +1,11 @@ +namespace ns { + int func(void) + { + return 0; + } +} + +extern "C" int foo(void) +{ + return ns::func(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/main.cpp new file mode 100644 index 00000000000..0d30c79bd22 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/options/main.cpp @@ -0,0 +1,17 @@ +extern "C" int foo(void); +static int static_value = 0; +static int id = 1234; + +int +bar() +{ + static_value++; + id++; + return static_value + id; +} + +int main (int argc, char const *argv[]) +{ + bar(); // breakpoint_in_main + return foo(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persist_objc_pointeetype/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persist_objc_pointeetype/Makefile new file mode 100644 index 00000000000..69a2ad6b8d8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persist_objc_pointeetype/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + + +LD_EXTRAS := -framework Foundation -framework CloudKit + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persist_objc_pointeetype/TestPersistObjCPointeeType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persist_objc_pointeetype/TestPersistObjCPointeeType.py new file mode 100644 index 00000000000..577753c0497 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persist_objc_pointeetype/TestPersistObjCPointeeType.py @@ -0,0 +1,50 @@ +""" +Test that we can p *objcObject +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PersistObjCPointeeType(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.cpp. + self.line = line_number('main.m', '// break here') + + @skipUnlessDarwin + @skipIf(archs=["i386", "i686"]) + @skipIf(debug_info="gmodules", archs=['arm64', 'armv7', 'armv7k', 'arm64e', 'arm64_32']) # compile error with gmodules for iOS + def test_with(self): + """Test that we can p *objcObject""" + self.build() + + def cleanup(): + pass + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + self.expect("p *self", substrs=['_sc_name = nil', + '_sc_name2 = nil', + '_sc_name3 = nil', + '_sc_name4 = nil', + '_sc_name5 = nil', + '_sc_name6 = nil', + '_sc_name7 = nil', + '_sc_name8 = nil']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persist_objc_pointeetype/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persist_objc_pointeetype/main.m new file mode 100644 index 00000000000..a2b6b703d6c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persist_objc_pointeetype/main.m @@ -0,0 +1,80 @@ +/* +clang -g ExtendSuperclass.m -o ExtendSuperclass -framework Foundation -framework ProtectedCloudStorage -F/System/Library/PrivateFrameworks/ -framework CloudKit && ./ExtendSuperclass +*/ +#include <assert.h> +#import <Foundation/Foundation.h> +#import <CloudKit/CloudKit.h> + +#define SuperClass CKDatabase + +@interface SubClass : SuperClass +@end + +// class extension +@interface SuperClass () +@property (nonatomic, strong) NSString *_sc_name; +@property (nonatomic, strong) NSString *_sc_name2; +@property (nonatomic, strong) NSString *_sc_name3; +@property (nonatomic, strong) NSString *_sc_name4; +@property (nonatomic, strong) NSString *_sc_name5; +@property (nonatomic, strong) NSString *_sc_name6; +@property (nonatomic, strong) NSString *_sc_name7; +@property (nonatomic, strong) NSString *_sc_name8; +@end + +@implementation SuperClass (MySuperClass) +- (id)initThatDoesNotAssert +{ + return [super init]; +} +@end + +@implementation SubClass +- (id)initThatDoesNotAssert +{ + assert(_sc_name == nil); + assert(_sc_name2 == nil); + assert(_sc_name3 == nil); + assert(_sc_name4 == nil); + assert(_sc_name5 == nil); + assert(_sc_name6 == nil); + assert(_sc_name7 == nil); + assert(_sc_name8 == nil); // break here + + if ((self = [super _initWithContainer:(CKContainer*)@"foo" scope:0xff])) { + assert(_sc_name == nil); + assert(_sc_name2 == nil); + assert(_sc_name3 == nil); + assert(_sc_name4 == nil); + assert(_sc_name5 == nil); + assert(_sc_name6 == nil); + assert(_sc_name7 == nil); + assert(_sc_name8 == nil); + + _sc_name = @"empty"; + } + return self; +} +@synthesize _sc_name; +@synthesize _sc_name2; +@synthesize _sc_name3; +@synthesize _sc_name4; +@synthesize _sc_name5; +@synthesize _sc_name6; +@synthesize _sc_name7; +@synthesize _sc_name8; +- (void)foo:(NSString*)bar { self._sc_name = bar; } +- (NSString*)description { return [NSString stringWithFormat:@"%p: %@", self, self._sc_name]; } +@end + +int main() +{ + SubClass *sc = [[SubClass alloc] initThatDoesNotAssert]; + NSLog(@"%@", sc); + [sc foo:@"bar"]; + NSLog(@"%@", sc); + sc._sc_name = @"bar2"; + NSLog(@"%@", sc); + NSLog(@"%@", sc._sc_name); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_ptr_update/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_ptr_update/Makefile new file mode 100644 index 00000000000..549336d0223 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_ptr_update/Makefile @@ -0,0 +1,5 @@ +C_SOURCES := main.c + +include Makefile.rules + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_ptr_update/TestPersistentPtrUpdate.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_ptr_update/TestPersistentPtrUpdate.py new file mode 100644 index 00000000000..5660113b8b4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_ptr_update/TestPersistentPtrUpdate.py @@ -0,0 +1,36 @@ +""" +Test that we can have persistent pointer variables +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class PersistentPtrUpdateTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test(self): + """Test that we can have persistent pointer variables""" + self.build() + + def cleanup(): + pass + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + self.runCmd('break set -p here') + + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("expr void* $foo = 0") + + self.runCmd("continue") + + self.expect("expr $foo", substrs=['$foo', '0x0']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_ptr_update/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_ptr_update/main.c new file mode 100644 index 00000000000..73346969ecc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_ptr_update/main.c @@ -0,0 +1,11 @@ +void* foo(void *p) +{ + return p; // break here +} + +int main() { + while (1) { + foo(0); + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/TestNestedPersistentTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/TestNestedPersistentTypes.py new file mode 100644 index 00000000000..973eade3e56 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/TestNestedPersistentTypes.py @@ -0,0 +1,41 @@ +""" +Test that nested persistent types work. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NestedPersistentTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_persistent_types(self): + """Test that nested persistent types work.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + self.runCmd("breakpoint set --name main") + + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("expression struct $foo { int a; int b; };") + + self.runCmd( + "expression struct $bar { struct $foo start; struct $foo end; };") + + self.runCmd("expression struct $bar $my_bar = {{ 2, 3 }, { 4, 5 }};") + + self.expect("expression $my_bar", + substrs=['a = 2', 'b = 3', 'a = 4', 'b = 5']) + + self.expect("expression $my_bar.start.b", + substrs=['(int)', '3']) + + self.expect("expression $my_bar.end.b", + substrs=['(int)', '5']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/TestPersistentTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/TestPersistentTypes.py new file mode 100644 index 00000000000..e60a76861b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/TestPersistentTypes.py @@ -0,0 +1,92 @@ +""" +Test that lldb persistent types works correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PersistenttypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_persistent_types(self): + """Test that lldb persistent types works correctly.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + self.runCmd("breakpoint set --name main") + + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("expression struct $foo { int a; int b; };") + + self.expect( + "expression struct $foo $my_foo; $my_foo.a = 2; $my_foo.b = 3;", + startstr="(int) $0 = 3") + + self.expect("expression $my_foo", + substrs=['a = 2', 'b = 3']) + + self.runCmd("expression typedef int $bar") + + self.expect("expression $bar i = 5; i", + startstr="($bar) $1 = 5") + + self.runCmd( + "expression struct $foobar { char a; char b; char c; char d; };") + self.runCmd("next") + + self.expect( + "memory read foo -t $foobar", + substrs=[ + '($foobar) 0x', + ' = ', + "a = 'H'", + "b = 'e'", + "c = 'l'", + "d = 'l'"]) # persistent types are OK to use for memory read + + self.expect( + "memory read foo -t $foobar -x c", + substrs=[ + '($foobar) 0x', + ' = ', + "a = 'H'", + "b = 'e'", + "c = 'l'", + "d = 'l'"]) # persistent types are OK to use for memory read + + self.expect( + "memory read foo -t foobar", + substrs=[ + '($foobar) 0x', + ' = ', + "a = 'H'", + "b = 'e'", + "c = 'l'", + "d = 'l'"], + matching=False, + error=True) # the type name is $foobar, make sure we settle for nothing less + + self.expect("expression struct { int a; int b; } x = { 2, 3 }; x", + substrs=['a = 2', 'b = 3']) + + self.expect( + "expression struct { int x; int y; int z; } object; object.y = 1; object.z = 3; object.x = 2; object", + substrs=[ + 'x = 2', + 'y = 1', + 'z = 3']) + + self.expect( + "expression struct A { int x; int y; }; struct { struct A a; int z; } object; object.a.y = 1; object.z = 3; object.a.x = 2; object", + substrs=[ + 'x = 2', + 'y = 1', + 'z = 3']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/main.c new file mode 100644 index 00000000000..9425c8b1cec --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_types/main.c @@ -0,0 +1,13 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main (int argc, char const *argv[]) +{ + const char* foo = "Hello world"; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_variables/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_variables/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_variables/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_variables/TestPersistentVariables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_variables/TestPersistentVariables.py new file mode 100644 index 00000000000..57c04b215e9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_variables/TestPersistentVariables.py @@ -0,0 +1,52 @@ +""" +Test that lldb persistent variables works correctly. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * + + +class PersistentVariablesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_persistent_variables(self): + """Test that lldb persistent variables works correctly.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + self.runCmd("breakpoint set --source-pattern-regexp break") + + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("expression int $i = i") + + self.expect("expression $i == i", + startstr="(bool) $0 = true") + + self.expect("expression $i + 1", + startstr="(int) $1 = 6") + + self.expect("expression $i + 3", + startstr="(int) $2 = 8") + + self.expect("expression $2 + $1", + startstr="(int) $3 = 14") + + self.expect("expression $3", + startstr="(int) $3 = 14") + + self.expect("expression $2", + startstr="(int) $2 = 8") + + self.expect("expression (int)-2", + startstr="(int) $4 = -2") + + self.expect("expression $4 > (int)31", + startstr="(bool) $5 = false") + + self.expect("expression (long)$4", + startstr="(long) $6 = -2") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_variables/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_variables/main.c new file mode 100644 index 00000000000..771bf4ad342 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/persistent_variables/main.c @@ -0,0 +1,13 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main (int argc, char const *argv[]) +{ + int i = 5; + return 0; // Set breakpoint here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/po_verbosity/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/po_verbosity/Makefile new file mode 100644 index 00000000000..9e812e1cf78 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/po_verbosity/Makefile @@ -0,0 +1,5 @@ +OBJC_SOURCES := main.m + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/po_verbosity/TestPoVerbosity.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/po_verbosity/TestPoVerbosity.py new file mode 100644 index 00000000000..e203b386d5b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/po_verbosity/TestPoVerbosity.py @@ -0,0 +1,62 @@ +""" +Test that the po command acts correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PoVerbosityTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.cpp. + self.line = line_number('main.m', + '// Stop here') + + @skipUnlessDarwin + def test(self): + """Test that the po command acts correctly.""" + self.build() + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type summary clear', check=False) + self.runCmd('type synthetic clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + """Test expr + formatters for good interoperability.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + self.expect("expr -O -v -- foo", + substrs=['(id) $', ' = 0x', '1 = 2', '2 = 3;']) + self.expect("expr -O -vfull -- foo", + substrs=['(id) $', ' = 0x', '1 = 2', '2 = 3;']) + self.expect("expr -O -- foo", matching=False, + substrs=['(id) $']) + + self.expect("expr -O -- 22", matching=False, + substrs=['(int) $']) + self.expect("expr -O -- 22", + substrs=['22']) + + self.expect("expr -O -vfull -- 22", + substrs=['(int) $', ' = 22']) + + self.expect("expr -O -v -- 22", + substrs=['(int) $', ' = 22']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/po_verbosity/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/po_verbosity/main.m new file mode 100644 index 00000000000..9c79f850bf2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/po_verbosity/main.m @@ -0,0 +1,9 @@ +#import <Foundation/Foundation.h> + +int main() +{ + [NSString initialize]; + id foo = @{@1 : @2, @2 : @3}; + int x = 34; + return 0; // Stop here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/pr35310/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/pr35310/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/pr35310/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/pr35310/TestExprsBug35310.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/pr35310/TestExprsBug35310.py new file mode 100644 index 00000000000..23dbce9227e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/pr35310/TestExprsBug35310.py @@ -0,0 +1,38 @@ + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class ExprBug35310(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + def test_issue35310(self): + """Test invoking functions with non-standard linkage names. + + The GNU abi_tag extension used by libstdc++ is a common source + of these, but they could originate from other reasons as well. + """ + self.build() + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + '// Break here', self.main_source_spec) + frame = thread.GetFrameAtIndex(0) + + value = frame.EvaluateExpression("a.test_abi_tag()") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(0), 1) + + value = frame.EvaluateExpression("a.test_asm_name()") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(0), 2) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/pr35310/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/pr35310/main.cpp new file mode 100644 index 00000000000..a8e8a5c737a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/pr35310/main.cpp @@ -0,0 +1,19 @@ +#include <stdio.h> + +class A { +public: + int __attribute__((abi_tag("cxx11"))) test_abi_tag() { + return 1; + } + int test_asm_name() asm("A_test_asm") { + return 2; + } +}; + +int main(int argc, char **argv) { + A a; + // Break here + a.test_abi_tag(); + a.test_asm_name(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_8638051/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_8638051/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_8638051/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_8638051/Test8638051.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_8638051/Test8638051.py new file mode 100644 index 00000000000..b0da7e798ed --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_8638051/Test8638051.py @@ -0,0 +1,37 @@ +""" +Test the robustness of lldb expression parser. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * + + +class Radar8638051TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_expr_commands(self): + """The following expression commands should not crash.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + self.runCmd("breakpoint set -n c") + + self.runCmd("run", RUN_SUCCEEDED) + + self.expect("expression val", + startstr="(int) $0 = 1") + # (int) $0 = 1 + + self.expect("expression *(&val)", + startstr="(int) $1 = 1") + # (int) $1 = 1 + + # rdar://problem/8638051 + # lldb expression command: Could this crash be avoided + self.expect("expression &val", + startstr="(int *) $2 = ") + # (int *) $2 = 0x.... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_8638051/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_8638051/main.c new file mode 100644 index 00000000000..dc528a458b3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_8638051/main.c @@ -0,0 +1,53 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to demonstrate the capability of the lldb command +// "breakpoint command add" to add a set of commands to a breakpoint to be +// executed when the breakpoint is hit. +// +// In particular, we want to break within c(), but only if the immediate caller +// is a(). + +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); // Find the line number where c's parent frame is a here. + + return val; +} + +int b(int val) +{ + return c(val); +} + +int c(int val) +{ + return val + 3; +} + +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; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9531204/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9531204/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9531204/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9531204/TestPrintfAfterUp.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9531204/TestPrintfAfterUp.py new file mode 100644 index 00000000000..56e7186ace3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9531204/TestPrintfAfterUp.py @@ -0,0 +1,42 @@ +""" +The evaluating printf(...) after break stop and then up a stack frame. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class Radar9531204TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # rdar://problem/9531204 + @expectedFailureNetBSD + def test_expr_commands(self): + """The evaluating printf(...) after break stop and then up a stack frame.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_symbol( + self, 'foo', sym_exact=True, num_expected_locations=1) + + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("frame variable") + + # This works fine. + self.runCmd('expression (int)printf("value is: %d.\\n", value);') + + # rdar://problem/9531204 + # "Error dematerializing struct" error when evaluating expressions "up" on the stack + self.runCmd('up') # frame select -r 1 + + self.runCmd("frame variable") + + # This does not currently. + self.runCmd('expression (int)printf("argc is: %d.\\n", argc)') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9531204/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9531204/main.c new file mode 100644 index 00000000000..43200d31745 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9531204/main.c @@ -0,0 +1,24 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// breakpoint set -n foo +// +// +int foo (int value) +{ + printf ("I got the value: %d.\n", value); + return 0; +} + +int main (int argc, char **argv) +{ + foo (argc); + printf ("Hello there: %d.\n", argc); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9673664/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9673664/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9673664/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9673664/TestExprHelpExamples.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9673664/TestExprHelpExamples.py new file mode 100644 index 00000000000..3eb3a86adf2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9673664/TestExprHelpExamples.py @@ -0,0 +1,44 @@ +""" +Test example snippets from the lldb 'help expression' output. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class Radar9673644TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.main_source = "main.c" + self.line = line_number(self.main_source, '// Set breakpoint here.') + + def test_expr_commands(self): + """The following expression commands should just work.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # rdar://problem/9673664 lldb expression evaluation problem + + self.expect('expr char str[] = "foo"; str[0]', + substrs=["'f'"]) + # runCmd: expr char c[] = "foo"; c[0] + # output: (char) $0 = 'f' diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9673664/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9673664/main.c new file mode 100644 index 00000000000..c765cf2a83a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/radar_9673664/main.c @@ -0,0 +1,15 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int main (int argc, char const *argv[]) +{ + printf("Hello, world.\n"); // Set breakpoint here. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar42038760/TestScalarURem.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar42038760/TestScalarURem.py new file mode 100644 index 00000000000..03424658f3e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar42038760/TestScalarURem.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), None) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar42038760/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar42038760/main.c new file mode 100644 index 00000000000..98a957faf8b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar42038760/main.c @@ -0,0 +1,19 @@ +// Make sure we IR-interpret the expression correctly. + +typedef unsigned int uint32_t; +struct S0 { + signed f2; +}; +static g_463 = 0x1561983AL; +void func_1(void) +{ + struct S0 l_19; + l_19.f2 = 419; + uint32_t l_4037 = 4294967295UL; + l_19.f2 = g_463; //%self.expect("expr ((l_4037 % (-(g_463))) | l_19.f2)", substrs=['(unsigned int) $0 = 358717883']) +} +int main() +{ + func_1(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar44436068/Test128BitsInteger.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar44436068/Test128BitsInteger.py new file mode 100644 index 00000000000..433c275fb58 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar44436068/Test128BitsInteger.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + decorators.skipIf(archs=["armv7k"])) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar44436068/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar44436068/main.c new file mode 100644 index 00000000000..156dbf04a1b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/rdar44436068/main.c @@ -0,0 +1,8 @@ +int main(void) +{ + __int128_t n = 1; + n = n + n; + return n; //%self.expect("p n", substrs=['(__int128_t) $0 = 2']) + //%self.expect("p n + 6", substrs=['(__int128) $1 = 8']) + //%self.expect("p n + n", substrs=['(__int128) $2 = 4']) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/regression-access-function-template-in-record/TestRegressionAccessFunctionTemplateInRecord.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/regression-access-function-template-in-record/TestRegressionAccessFunctionTemplateInRecord.py new file mode 100644 index 00000000000..f08c0dcbda9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/regression-access-function-template-in-record/TestRegressionAccessFunctionTemplateInRecord.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), []) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/regression-access-function-template-in-record/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/regression-access-function-template-in-record/main.cpp new file mode 100644 index 00000000000..02f15c295c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/regression-access-function-template-in-record/main.cpp @@ -0,0 +1,11 @@ +namespace n { +template <class> class a {}; +template <class b> struct shared_ptr { + template <class...> + static void make_shared() { //%self.dbg.GetCommandInterpreter().HandleCompletion("e ", len("e "), 0, -1, lldb.SBStringList()) + typedef a<b> c; + c d; + } +}; +} // namespace n +int main() { n::shared_ptr<int>::make_shared(); } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/save_jit_objects/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/save_jit_objects/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/save_jit_objects/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/save_jit_objects/TestSaveJITObjects.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/save_jit_objects/TestSaveJITObjects.py new file mode 100644 index 00000000000..62925c6f94f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/save_jit_objects/TestSaveJITObjects.py @@ -0,0 +1,52 @@ +""" +Test that LLDB can emit JIT objects when the appropriate setting is enabled +""" + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class SaveJITObjectsTestCase(TestBase): + mydir = TestBase.compute_mydir(__file__) + + def enumerateJITFiles(self): + return [f for f in os.listdir(self.getBuildDir()) if f.startswith("jit")] + + def countJITFiles(self): + return len(self.enumerateJITFiles()) + + def cleanJITFiles(self): + for j in self.enumerateJITFiles(): + os.remove(j) + return + + @expectedFailureAll(oslist=["windows"]) + @expectedFailureNetBSD + def test_save_jit_objects(self): + self.build() + os.chdir(self.getBuildDir()) + src_file = "main.c" + src_file_spec = lldb.SBFileSpec(src_file) + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "break", src_file_spec) + + frame = thread.frames[0] + + self.cleanJITFiles() + frame.EvaluateExpression("(void*)malloc(0x1)") + self.assertTrue(self.countJITFiles() == 0, + "No files emitted with save-jit-objects=false") + + self.runCmd("settings set target.save-jit-objects true") + frame.EvaluateExpression("(void*)malloc(0x1)") + jit_files_count = self.countJITFiles() + self.cleanJITFiles() + self.assertTrue(jit_files_count != 0, + "At least one file emitted with save-jit-objects=true") + + process.Kill() + os.chdir(self.getSourceDir()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/save_jit_objects/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/save_jit_objects/main.c new file mode 100644 index 00000000000..c9775b6e989 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/save_jit_objects/main.c @@ -0,0 +1,13 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main (int argc, char const *argv[]) +{ + const char* foo = "Hello world"; // break here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/scoped_enums/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/scoped_enums/Makefile new file mode 100644 index 00000000000..4eb417eeb57 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/scoped_enums/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp +CXXFLAGS_EXTRAS := -std=c++11 + + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/scoped_enums/TestScopedEnumType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/scoped_enums/TestScopedEnumType.py new file mode 100644 index 00000000000..dd40e87d68d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/scoped_enums/TestScopedEnumType.py @@ -0,0 +1,44 @@ + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ScopedEnumType(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(dwarf_version=['<', '4']) + def test(self): + self.build() + + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + '// Set break point at this line.', self.main_source_spec) + frame = thread.GetFrameAtIndex(0) + + self.expect("expr f == Foo::FooBar", + substrs=['(bool) $0 = true']) + + value = frame.EvaluateExpression("f == Foo::FooBar") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsUnsigned(), 1) + + value = frame.EvaluateExpression("b == BarBar") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsUnsigned(), 1) + + ## b is not a Foo + value = frame.EvaluateExpression("b == Foo::FooBar") + self.assertTrue(value.IsValid()) + self.assertFalse(value.GetError().Success()) + + ## integral is not implicitly convertible to a scoped enum + value = frame.EvaluateExpression("1 == Foo::FooBar") + self.assertTrue(value.IsValid()) + self.assertFalse(value.GetError().Success()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/scoped_enums/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/scoped_enums/main.cpp new file mode 100644 index 00000000000..b0d67d23dc5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/scoped_enums/main.cpp @@ -0,0 +1,16 @@ +enum class Foo { + FooBar = 42 +}; + +enum Bar { + BarBar = 3, + BarBarBar = 42 +}; + +int main(int argc, const char **argv) { + Foo f = Foo::FooBar; + Bar b = BarBar; + bool b1 = f == Foo::FooBar; + bool b2 = b == BarBar; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/static-initializers/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/static-initializers/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/static-initializers/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/static-initializers/TestStaticInitializers.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/static-initializers/TestStaticInitializers.py new file mode 100644 index 00000000000..61107077f9c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/static-initializers/TestStaticInitializers.py @@ -0,0 +1,33 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class StaticInitializers(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(archs="aarch64", oslist="linux", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=44053") + def test(self): + """ Test a static initializer. """ + self.build() + + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + # We use counter to observe if the initializer was called. + self.expect("expr counter", substrs=["(int) $", " = 0"]) + self.expect("expr -p -- struct Foo { Foo() { inc_counter(); } }; Foo f;") + self.expect("expr counter", substrs=["(int) $", " = 1"]) + + def test_failing_init(self): + """ Test a static initializer that fails to execute. """ + self.build() + + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + # FIXME: This error message is not even remotely helpful. + self.expect("expr -p -- struct Foo2 { Foo2() { do_abort(); } }; Foo2 f;", error=True, + substrs=["error: couldn't run static initializers: couldn't run static initializer:"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/static-initializers/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/static-initializers/main.cpp new file mode 100644 index 00000000000..0bcf1eb3eda --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/static-initializers/main.cpp @@ -0,0 +1,11 @@ +#include <cstdlib> + +int counter = 0; + +void inc_counter() { ++counter; } + +void do_abort() { abort(); } + +int main() { + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/TestExprs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/TestExprs.py new file mode 100644 index 00000000000..8437eac250b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/TestExprs.py @@ -0,0 +1,252 @@ +""" +Test many basic expression commands and SBFrame.EvaluateExpression() API. + +Test cases: + +o test_many_expr_commands: + Test many basic expression commands. +o test_evaluate_expression_python: + Use Python APIs (SBFrame.EvaluateExpression()) to evaluate expressions. +o test_expr_commands_can_handle_quotes: + Throw some expression commands with quotes at lldb. +""" + + + +import unittest2 + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BasicExprCommandsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number( + 'main.cpp', + '// Please test many expressions while stopped at this line:') + + # Disable confirmation prompt to avoid infinite wait + self.runCmd("settings set auto-confirm true") + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) + + def build_and_run(self): + """These basic expression commands should work as expected.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + + self.runCmd("run", RUN_SUCCEEDED) + + @unittest2.expectedFailure( + "llvm.org/pr17135 <rdar://problem/14874559> APFloat::toString does not identify the correct (i.e. least) precision.") + def test_floating_point_expr_commands(self): + self.build_and_run() + + self.expect("expression 2.234f", + patterns=["\(float\) \$.* = 2\.234"]) + # (float) $2 = 2.234 + + def test_many_expr_commands(self): + self.build_and_run() + + self.expect("expression 2", + patterns=["\(int\) \$.* = 2"]) + # (int) $0 = 1 + + self.expect("expression 2ull", + patterns=["\(unsigned long long\) \$.* = 2"]) + # (unsigned long long) $1 = 2 + + self.expect("expression 0.5f", + patterns=["\(float\) \$.* = 0\.5"]) + # (float) $2 = 0.5 + + self.expect("expression 2.234", + patterns=["\(double\) \$.* = 2\.234"]) + # (double) $3 = 2.234 + + self.expect("expression 2+3", + patterns=["\(int\) \$.* = 5"]) + # (int) $4 = 5 + + self.expect("expression argc", + patterns=["\(int\) \$.* = 1"]) + # (int) $5 = 1 + + self.expect("expression argc + 22", + patterns=["\(int\) \$.* = 23"]) + # (int) $6 = 23 + + self.expect("expression argv", + patterns=["\(const char \*\*\) \$.* = 0x"]) + # (const char *) $7 = ... + + self.expect("expression argv[0]", + substrs=["(const char *)", + "a.out"]) + # (const char *) $8 = 0x... "/Volumes/data/lldb/svn/trunk/test/expression_command/test/a.out" + + @add_test_categories(['pyapi']) + @expectedFlakeyNetBSD + def test_evaluate_expression_python(self): + """Test SBFrame.EvaluateExpression() API for evaluating an expression.""" + self.build() + + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint. + filespec = lldb.SBFileSpec("main.cpp", False) + breakpoint = target.BreakpointCreateByLocation(filespec, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Verify the breakpoint just created. + self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False, + substrs=['main.cpp', + str(self.line)]) + + # Launch the process, and do not stop at the entry point. + # Pass 'X Y Z' as the args, which makes argc == 4. + process = target.LaunchSimple( + ['X', 'Y', 'Z'], None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.LaunchProcess() failed") + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, breakpoint) + self.assertIsNotNone( + thread, "Expected one thread to be stopped at the breakpoint") + + # The filename of frame #0 should be 'main.cpp' and function is main. + self.expect(lldbutil.get_filenames(thread)[0], + "Break correctly at main.cpp", exe=False, + startstr="main.cpp") + self.expect(lldbutil.get_function_names(thread)[0], + "Break correctly at main()", exe=False, + startstr="main") + + # We should be stopped on the breakpoint with a hit count of 1. + self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE) + + # + # Use Python API to evaluate expressions while stopped in a stack frame. + # + frame = thread.GetFrameAtIndex(0) + + val = frame.EvaluateExpression("2.234") + self.expect(val.GetValue(), "2.345 evaluated correctly", exe=False, + startstr="2.234") + self.expect(val.GetTypeName(), "2.345 evaluated correctly", exe=False, + startstr="double") + self.DebugSBValue(val) + + val = frame.EvaluateExpression("argc") + self.expect(val.GetValue(), "Argc evaluated correctly", exe=False, + startstr="4") + self.DebugSBValue(val) + + val = frame.EvaluateExpression("*argv[1]") + self.expect(val.GetValue(), "Argv[1] evaluated correctly", exe=False, + startstr="'X'") + self.DebugSBValue(val) + + val = frame.EvaluateExpression("*argv[2]") + self.expect(val.GetValue(), "Argv[2] evaluated correctly", exe=False, + startstr="'Y'") + self.DebugSBValue(val) + + val = frame.EvaluateExpression("*argv[3]") + self.expect(val.GetValue(), "Argv[3] evaluated correctly", exe=False, + startstr="'Z'") + self.DebugSBValue(val) + + callee_break = target.BreakpointCreateByName( + "a_function_to_call", None) + self.assertTrue(callee_break.GetNumLocations() > 0) + + # Make sure ignoring breakpoints works from the command line: + self.expect("expression -i true -- a_function_to_call()", + substrs=['(int) $', ' 1']) + self.assertTrue(callee_break.GetHitCount() == 1) + + # Now try ignoring breakpoints using the SB API's: + options = lldb.SBExpressionOptions() + options.SetIgnoreBreakpoints(True) + value = frame.EvaluateExpression('a_function_to_call()', options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetValueAsSigned(0) == 2) + self.assertTrue(callee_break.GetHitCount() == 2) + + # rdar://problem/8686536 + # CommandInterpreter::HandleCommand is stripping \'s from input for + # WantsRawCommand commands + @expectedFailureNetBSD + def test_expr_commands_can_handle_quotes(self): + """Throw some expression commands with quotes at lldb.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + + self.runCmd("run", RUN_SUCCEEDED) + + # runCmd: expression 'a' + # output: (char) $0 = 'a' + self.expect("expression 'a'", + substrs=['(char) $', + "'a'"]) + + # runCmd: expression (int) printf ("\n\n\tHello there!\n") + # output: (int) $1 = 16 + self.expect(r'''expression (int) printf ("\n\n\tHello there!\n")''', + substrs=['(int) $', + '16']) + + # runCmd: expression (int) printf("\t\x68\n") + # output: (int) $2 = 3 + self.expect(r'''expression (int) printf("\t\x68\n")''', + substrs=['(int) $', + '3']) + + # runCmd: expression (int) printf("\"\n") + # output: (int) $3 = 2 + self.expect(r'''expression (int) printf("\"\n")''', + substrs=['(int) $', + '2']) + + # runCmd: expression (int) printf("'\n") + # output: (int) $4 = 2 + self.expect(r'''expression (int) printf("'\n")''', + substrs=['(int) $', + '2']) + + # runCmd: command alias print_hi expression (int) printf ("\n\tHi!\n") + # output: + self.runCmd( + r'''command alias print_hi expression (int) printf ("\n\tHi!\n")''') + # This fails currently. + self.expect('print_hi', + substrs=['(int) $', + '6']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/TestExprs2.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/TestExprs2.py new file mode 100644 index 00000000000..cd02f89b461 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/TestExprs2.py @@ -0,0 +1,73 @@ +""" +Test some more expression commands. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCommands2TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number( + 'main.cpp', + '// Please test many expressions while stopped at this line:') + + def test_more_expr_commands(self): + """Test some more expression commands.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + + self.runCmd("run", RUN_SUCCEEDED) + + # Does static casting work? + self.expect("expression (int*)argv", + startstr="(int *) $0 = 0x") + # (int *) $0 = 0x00007fff5fbff258 + + # Do return values containing the contents of expression locals work? + self.expect("expression int i = 5; i", + startstr="(int) $1 = 5") + # (int) $2 = 5 + self.expect("expression $1 + 1", + startstr="(int) $2 = 6") + # (int) $3 = 6 + + # Do return values containing the results of static expressions work? + self.expect("expression 20 + 3", + startstr="(int) $3 = 23") + # (int) $4 = 5 + self.expect("expression $3 + 1", + startstr="(int) $4 = 24") + # (int) $5 = 6 + + @skipIfLinux + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489") + def test_expr_symbols(self): + """Test symbols.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + + self.runCmd("run", RUN_SUCCEEDED) + + # Do anonymous symbols work? + self.expect("expression ((char**)environ)[0]", + startstr="(char *) $0 = 0x") + # (char *) $1 = 0x00007fff5fbff298 "Apple_PubSub_Socket_Render=/tmp/launch-7AEsUD/Render" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/main.cpp new file mode 100644 index 00000000000..22208a87cb4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/test/main.cpp @@ -0,0 +1,44 @@ +#include <stdio.h> + +static int static_value = 0; + +int +a_function_to_call() +{ + static_value++; + return static_value; +} + +int main (int argc, char const *argv[]) +{ + printf ("Hello world!\n"); + puts ("hello"); + // Please test many expressions while stopped at this line: +#if 0 + expression 'a' // make sure character constant makes it down (this is broken: <rdar://problem/8686536>) + expression 2 // Test int + expression 2ull // Test unsigned long long + expression 2.234f // Test float constants + expression 2.234 // Test double constants + expression 2+3 + expression argc + expression argc + 22 + expression argv + expression argv[0] + expression argv[1] + expression argv[-1] + expression puts("bonjour") // Test constant strings... + expression printf("\t\x68\n") // Test constant strings that contain the \xXX (TAB, 'h', '\n' should be printed) (this is broken: <rdar://problem/8686536>) + expression printf("\"\n") // Test constant strings that contains an escaped double quote char (this is broken: <rdar://problem/8686536>) + expression printf("\'\n") // Test constant strings that contains an escaped single quote char (this is broken: <rdar://problem/8686536>) + expression printf ("one: %i\n", 1) + expression printf ("1.234 as float: %f\n", 1.234f) + expression printf ("1.234 as double: %g\n", 1.234) + expression printf ("one: %i, two: %llu\n", 1, 2ull) + expression printf ("two: %llu, one: %i\n", 2ull, 1) + expression random() % 255l +#endif + + a_function_to_call(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/timeout/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/timeout/Makefile new file mode 100644 index 00000000000..06a21f5b8b4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/timeout/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := wait-a-while.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/timeout/TestCallWithTimeout.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/timeout/TestCallWithTimeout.py new file mode 100644 index 00000000000..a64167ef55c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/timeout/TestCallWithTimeout.py @@ -0,0 +1,79 @@ +""" +Test calling a function that waits a while, and make sure the timeout option to expr works. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprCommandWithTimeoutsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.main_source = "wait-a-while.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + @expectedFlakeyFreeBSD("llvm.org/pr19605") + @expectedFailureAll( + oslist=[ + "windows"], + bugnumber="llvm.org/pr21765") + def test(self): + """Test calling std::String member function.""" + self.build() + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, 'stop here in main.', self.main_source_spec) + + # First set the timeout too short, and make sure we fail. + options = lldb.SBExpressionOptions() + options.SetTimeoutInMicroSeconds(10) + options.SetUnwindOnError(True) + + frame = thread.GetFrameAtIndex(0) + + value = frame.EvaluateExpression("wait_a_while(1000000)", options) + self.assertTrue(value.IsValid()) + self.assertFalse(value.GetError().Success()) + + # Now do the same thing with the command line command, and make sure it + # works too. + interp = self.dbg.GetCommandInterpreter() + + result = lldb.SBCommandReturnObject() + return_value = interp.HandleCommand( + "expr -t 100 -u true -- wait_a_while(1000000)", result) + self.assertTrue(return_value == lldb.eReturnStatusFailed) + + # Okay, now do it again with long enough time outs: + + options.SetTimeoutInMicroSeconds(1000000) + value = frame.EvaluateExpression("wait_a_while (1000)", options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + + # Now do the same thingwith the command line command, and make sure it + # works too. + interp = self.dbg.GetCommandInterpreter() + + result = lldb.SBCommandReturnObject() + return_value = interp.HandleCommand( + "expr -t 1000000 -u true -- wait_a_while(1000)", result) + self.assertTrue(return_value == lldb.eReturnStatusSuccessFinishResult) + + # Finally set the one thread timeout and make sure that doesn't change + # things much: + + options.SetTimeoutInMicroSeconds(1000000) + options.SetOneThreadTimeoutInMicroSeconds(500000) + value = frame.EvaluateExpression("wait_a_while (1000)", options) + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/timeout/wait-a-while.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/timeout/wait-a-while.cpp new file mode 100644 index 00000000000..ac37c5d243b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/timeout/wait-a-while.cpp @@ -0,0 +1,35 @@ +#include <stdio.h> +#include <stdint.h> + +#include <chrono> +#include <thread> + + +int +wait_a_while (int microseconds) +{ + int num_times = 0; + auto end_time = std::chrono::system_clock::now() + std::chrono::microseconds(microseconds); + + while (1) + { + num_times++; + auto wait_time = end_time - std::chrono::system_clock::now(); + + std::this_thread::sleep_for(wait_time); + if (std::chrono::system_clock::now() > end_time) + break; + } + return num_times; +} + +int +main (int argc, char **argv) +{ + printf ("stop here in main.\n"); + int num_times = wait_a_while (argc * 1000); + printf ("Done, took %d times.\n", num_times); + + return 0; + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/Makefile new file mode 100644 index 00000000000..e5e9e78d4ea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/Makefile @@ -0,0 +1,10 @@ +CXX_SOURCES := main.cpp test.cpp + +all: dummy + +include Makefile.rules + +dummy: dummy.cpp + $(MAKE) -f $(MAKEFILE_RULES) \ + CXX_SOURCES=dummy.cpp EXE=dummy + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/TestTopLevelExprs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/TestTopLevelExprs.py new file mode 100644 index 00000000000..4e1a3779cfc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/TestTopLevelExprs.py @@ -0,0 +1,93 @@ +""" +Test top-level expressions. +""" + + + +import unittest2 + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TopLevelExpressionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number('main.cpp', + '// Set breakpoint here') + self.dummy_line = line_number('dummy.cpp', + '// Set breakpoint here') + + # Disable confirmation prompt to avoid infinite wait + self.runCmd("settings set auto-confirm true") + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) + + def build_and_run(self): + """Test top-level expressions.""" + self.build() + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False) + + self.runCmd("run", RUN_SUCCEEDED) + + def run_dummy(self): + self.runCmd("file " + self.getBuildArtifact("dummy"), + CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "dummy.cpp", + self.dummy_line, + num_expected_locations=1, + loc_exact=False) + + self.runCmd("run", RUN_SUCCEEDED) + + @add_test_categories(['pyapi']) + @skipIf(debug_info="gmodules") # not relevant + @skipIf(oslist=["windows"]) # Error in record layout on Windows + def test_top_level_expressions(self): + self.build_and_run() + + resultFromCode = self.frame().EvaluateExpression("doTest()").GetValueAsUnsigned() + + self.runCmd("kill") + + self.run_dummy() + + codeFile = open('test.cpp', 'r') + + expressions = [] + current_expression = "" + + for line in codeFile: + if line.startswith("// --"): + expressions.append(current_expression) + current_expression = "" + else: + current_expression += line + + options = lldb.SBExpressionOptions() + options.SetLanguage(lldb.eLanguageTypeC_plus_plus) + options.SetTopLevel(True) + + for expression in expressions: + self.frame().EvaluateExpression(expression, options) + + resultFromTopLevel = self.frame().EvaluateExpression("doTest()") + + self.assertTrue(resultFromTopLevel.IsValid()) + self.assertEqual( + resultFromCode, + resultFromTopLevel.GetValueAsUnsigned()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/dummy.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/dummy.cpp new file mode 100644 index 00000000000..fa49bd4bda7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/dummy.cpp @@ -0,0 +1,15 @@ +#include <stdio.h> + +// These are needed to make sure that the linker does not strip the parts of the +// C++ abi library that are necessary to execute the expressions in the +// debugger. It would be great if we did not need to do this, but the fact that +// LLDB cannot conjure up the abi library on demand is not relevant for testing +// top level expressions. +struct DummyA {}; +struct DummyB : public virtual DummyA {}; + +int main() { + DummyB b; + printf("This is a dummy\n"); // Set breakpoint here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/main.cpp new file mode 100644 index 00000000000..f9b2dd4c6d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/main.cpp @@ -0,0 +1,9 @@ +#include <stdio.h> + +extern int doTest(); + +int main() +{ + printf("%d\n", doTest()); // Set breakpoint here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/test.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/test.cpp new file mode 100644 index 00000000000..5a978743596 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/top-level/test.cpp @@ -0,0 +1,107 @@ +class MyClass +{ +public: + int memberResult() + { + return 1; + } + static int staticResult() + { + return 1; + } + int externResult(); +}; + +// -- + +int MyClass::externResult() +{ + return 1; +} + +// -- + +MyClass m; + +// -- + +enum MyEnum { + myEnumOne = 1, + myEnumTwo, + myEnumThree +}; + +// -- + +class AnotherClass +{ +public: + __attribute__ ((always_inline)) int complicatedFunction() + { + struct { + int i; + } s = { 15 }; + + int numbers[4] = { 2, 3, 4, 5 }; + + for (signed char number: numbers) + { + s.i -= number; + } + + return s.i; + } +}; + +// -- + +class DiamondA +{ +private: + struct { + int m_i; + }; +public: + DiamondA(int i) : m_i(i) { } + int accessor() { return m_i; } +}; + +// -- + +class DiamondB : public virtual DiamondA +{ +public: + DiamondB(int i) : DiamondA(i) { } +}; + +// -- + +class DiamondC : public virtual DiamondA +{ +public: + DiamondC(int i) : DiamondA(i) { } +}; + +// -- + +class DiamondD : public DiamondB, public DiamondC +{ +public: + DiamondD(int i) : DiamondA(i), DiamondB(i), DiamondC(i) { } +}; + +// -- + +int doTest() +{ + int accumulator = m.memberResult(); + accumulator += MyClass::staticResult(); + accumulator += m.externResult(); + accumulator += MyEnum::myEnumThree; + accumulator += myEnumOne; + accumulator += AnotherClass().complicatedFunction(); + accumulator += DiamondD(3).accessor(); + return accumulator; +} + +// -- diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/Makefile new file mode 100644 index 00000000000..c82383d9400 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m foo.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/TestObjCTypeQueryFromOtherCompileUnit.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/TestObjCTypeQueryFromOtherCompileUnit.py new file mode 100644 index 00000000000..c518bf0559f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/TestObjCTypeQueryFromOtherCompileUnit.py @@ -0,0 +1,40 @@ +""" +Regression test for <rdar://problem/8981098>: + +The expression parser's type search only looks in the current compilation unit for types. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCTypeQueryTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.m. + self.line = line_number( + 'main.m', "// Set breakpoint here, then do 'expr (NSArray*)array_token'.") + + @skipUnlessDarwin + def test(self): + """The expression parser's type search should be wider than the current compilation unit.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # Now do a NSArry type query from the 'main.m' compile uint. + self.expect("expression (NSArray*)array_token", + substrs=['(NSArray *) $0 = 0x']) + # (NSArray *) $0 = 0x00007fff70118398 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/foo.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/foo.m new file mode 100644 index 00000000000..1609ebd838f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/foo.m @@ -0,0 +1,28 @@ +#import <Foundation/Foundation.h> + +NSMutableArray * +GetArray () +{ + static NSMutableArray *the_array = NULL; + if (the_array == NULL) + the_array = [[NSMutableArray alloc] init]; + return the_array; +} + +int +AddElement (char *value) +{ + NSString *element = [NSString stringWithUTF8String: value]; + int cur_elem = [GetArray() count]; + [GetArray() addObject: element]; + return cur_elem; +} + +const char * +GetElement (int idx) +{ + if (idx >= [GetArray() count]) + return NULL; + else + return [[GetArray() objectAtIndex: idx] UTF8String]; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/main.m new file mode 100644 index 00000000000..3f5738314e6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/two-files/main.m @@ -0,0 +1,22 @@ +#import <Foundation/Foundation.h> +#include <stdio.h> + +extern int AddElement (char *value); +extern char *GetElement (int idx); +extern void *GetArray(); + +int +main () +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + int idx = AddElement ("some string"); + void *array_token = GetArray(); + + char *string = GetElement (0); // Set breakpoint here, then do 'expr (NSArray*)array_token'. + if (string) + printf ("This: %s.\n", string); + + [pool release]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unicode-in-variable/TestUnicodeInVariable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unicode-in-variable/TestUnicodeInVariable.py new file mode 100644 index 00000000000..03424658f3e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unicode-in-variable/TestUnicodeInVariable.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), None) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unicode-in-variable/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unicode-in-variable/main.cpp new file mode 100644 index 00000000000..82e38b1ef4c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unicode-in-variable/main.cpp @@ -0,0 +1,17 @@ +// Make sure we correctly handle unicode in variable names. + +struct A { + // We need a member variable in the context that could shadow our local + // variable. If our optimization code fails to handle this, then we won't + // correctly inject our local variable so that it won't get shadowed. + int foob\u00E1r = 2; + int foo() { + int foob\u00E1r = 3; + return foob\u00E1r; //%self.expect("expr foobár", substrs=['(int)', ' = 3']) + } +}; + +int main() { + A a; + return a.foo(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unwind_expression/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unwind_expression/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unwind_expression/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unwind_expression/TestUnwindExpression.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unwind_expression/TestUnwindExpression.py new file mode 100644 index 00000000000..de883f47f93 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unwind_expression/TestUnwindExpression.py @@ -0,0 +1,100 @@ +""" +Test stopping at a breakpoint in an expression, and unwinding from there. +""" + + + +import unittest2 + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class UnwindFromExpressionTest(TestBase): + + mydir = TestBase.compute_mydir(__file__) + main_spec = lldb.SBFileSpec("main.cpp", False) + + def build_and_run_to_bkpt(self): + self.build() + + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "// Set a breakpoint here to get started", self.main_spec) + + # Next set a breakpoint in this function, set up Expression options to stop on + # breakpoint hits, and call the function. + self.fun_bkpt = self.target().BreakpointCreateBySourceRegex( + "// Stop inside the function here.", self.main_spec) + self.assertTrue(self.fun_bkpt, VALID_BREAKPOINT) + + + @no_debug_info_test + @expectedFailureAll(bugnumber="llvm.org/pr33164") + def test_conditional_bktp(self): + """ + Test conditional breakpoint handling in the IgnoreBreakpoints = False case + """ + self.build_and_run_to_bkpt() + + self.fun_bkpt.SetCondition("0") # Should not get hit + options = lldb.SBExpressionOptions() + options.SetIgnoreBreakpoints(False) + options.SetUnwindOnError(False) + + main_frame = self.thread.GetFrameAtIndex(0) + val = main_frame.EvaluateExpression("second_function(47)", options) + self.assertTrue( + val.GetError().Success(), + "We did complete the execution.") + self.assertEquals(47, val.GetValueAsSigned()) + + + @add_test_categories(['pyapi']) + @expectedFlakeyNetBSD + def test_unwind_expression(self): + """Test unwinding from an expression.""" + self.build_and_run_to_bkpt() + + # Run test with varying one thread timeouts to also test the halting + # logic in the IgnoreBreakpoints = False case + self.do_unwind_test(self.thread, self.fun_bkpt, 1000) + self.do_unwind_test(self.thread, self.fun_bkpt, 100000) + + def do_unwind_test(self, thread, bkpt, timeout): + # + # Use Python API to evaluate expressions while stopped in a stack frame. + # + main_frame = thread.GetFrameAtIndex(0) + + options = lldb.SBExpressionOptions() + options.SetIgnoreBreakpoints(False) + options.SetUnwindOnError(False) + options.SetOneThreadTimeoutInMicroSeconds(timeout) + + val = main_frame.EvaluateExpression("a_function_to_call()", options) + + self.assertTrue( + val.GetError().Fail(), + "We did not complete the execution.") + error_str = val.GetError().GetCString() + self.assertTrue( + "Execution was interrupted, reason: breakpoint" in error_str, + "And the reason was right.") + + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + self.process(), bkpt) + self.assertTrue( + thread.IsValid(), + "We are indeed stopped at our breakpoint") + + # Now unwind the expression, and make sure we got back to where we + # started. + error = thread.UnwindInnermostExpression() + self.assertTrue(error.Success(), "We succeeded in unwinding") + + cur_frame = thread.GetFrameAtIndex(0) + self.assertTrue( + cur_frame.IsEqual(main_frame), + "We got back to the main frame.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unwind_expression/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unwind_expression/main.cpp new file mode 100644 index 00000000000..56b06f31ecc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/unwind_expression/main.cpp @@ -0,0 +1,22 @@ +static int static_value = 0; + +int +a_function_to_call() +{ + static_value++; // Stop inside the function here. + return static_value; +} + +int second_function(int x){ + for(int i=0; i<10; ++i) { + a_function_to_call(); + } + return x; +} + +int main (int argc, char const *argv[]) +{ + a_function_to_call(); // Set a breakpoint here to get started + second_function(1); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/vector_of_enums/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/vector_of_enums/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/vector_of_enums/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/vector_of_enums/TestVectorOfEnums.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/vector_of_enums/TestVectorOfEnums.py new file mode 100644 index 00000000000..2da95460e24 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/vector_of_enums/TestVectorOfEnums.py @@ -0,0 +1,29 @@ +""" +Test Expression Parser regression test to ensure that we handle enums +correctly, in this case specifically std::vector of enums. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestVectorOfEnums(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + def test_vector_of_enums(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + self.expect("expr v", substrs=[ + 'size=3', + '[0] = a', + '[1] = b', + '[2] = c', + '}' + ]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/vector_of_enums/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/vector_of_enums/main.cpp new file mode 100644 index 00000000000..10d3ae569a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/vector_of_enums/main.cpp @@ -0,0 +1,14 @@ +#include <vector> + +enum E { +a, +b, +c, +d +} ; + +int main() { + std::vector<E> v = {E::a, E::b, E::c}; + + return v.size(); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/Makefile new file mode 100644 index 00000000000..6fd8133312a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/Makefile @@ -0,0 +1,20 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 -fmodules +LD_EXTRAS := -ldylib -L. + +all: a.out hidden/libdylib.dylib + +a.out: libdylib.dylib + +include Makefile.rules + +libdylib.dylib: dylib.c + $(MAKE) -C $(BUILDDIR) -f $(MAKEFILE_RULES) \ + C_SOURCES= DYLIB_C_SOURCES=dylib.c DYLIB_NAME=dylib \ + CFLAGS_EXTRAS=-DHAS_THEM LD_EXTRAS=-dynamiclib + +hidden/libdylib.dylib: + mkdir hidden + $(MAKE) -C $(BUILDDIR)/hidden -f $(MAKEFILE_RULES) \ + C_SOURCES= DYLIB_C_SOURCES=dylib.c DYLIB_NAME=dylib \ + LD_EXTRAS=-dynamiclib diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/TestWeakSymbols.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/TestWeakSymbols.py new file mode 100644 index 00000000000..b58d838b14b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/TestWeakSymbols.py @@ -0,0 +1,79 @@ +""" +Test that we can compile expressions referring to +absent weak symbols from a dylib. +""" + + + +import os +import lldb +from lldbsuite.test import decorators +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class TestWeakSymbolsInExpressions(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @decorators.skipUnlessDarwin + def test_weak_symbol_in_expr(self): + """Tests that we can refer to weak symbols in expressions.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.c") + self.do_test() + + def run_weak_var_check (self, weak_varname, present): + # The expression will modify present_weak_int to signify which branch + # was taken. Set it to so we don't get confused by a previous run. + value = self.target.FindFirstGlobalVariable("present_weak_int") + value.SetValueFromCString("0") + if present: + correct_value = 10 + else: + correct_value = 20 + + # Note, I'm adding the "; 10" at the end of the expression to work around + # the bug that expressions with no result currently return False for Success()... + expr = "if (&" + weak_varname + " != NULL) { present_weak_int = 10; } else { present_weak_int = 20;}; 10" + result = self.frame.EvaluateExpression(expr) + self.assertTrue(result.GetError().Success(), "absent_weak_int expr failed: %s"%(result.GetError().GetCString())) + self.assertEqual(value.GetValueAsSigned(), correct_value, "Didn't change present_weak_int correctly.") + + def do_test(self): + hidden_dir = os.path.join(self.getBuildDir(), "hidden") + hidden_dylib = os.path.join(hidden_dir, "libdylib.dylib") + + launch_info = lldb.SBLaunchInfo(None) + launch_info.SetWorkingDirectory(self.getBuildDir()) + # We have to point to the hidden directory to pick up the + # version of the dylib without the weak symbols: + env_expr = self.platformContext.shlib_environment_var + "=" + hidden_dir + launch_info.SetEnvironmentEntries([env_expr], True) + + (self.target, _, thread, _) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", + self.main_source_file, + launch_info = launch_info, + extra_images = [hidden_dylib]) + # First we have to import the Dylib module so we get the type info + # for the weak symbol. We need to add the source dir to the module + # search paths, and then run @import to introduce it into the expression + # context: + self.dbg.HandleCommand("settings set target.clang-module-search-paths " + self.getSourceDir()) + + self.frame = thread.frames[0] + self.assertTrue(self.frame.IsValid(), "Got a good frame") + options = lldb.SBExpressionOptions() + options.SetLanguage(lldb.eLanguageTypeObjC) + result = self.frame.EvaluateExpression("@import Dylib", options) + + # Now run an expression that references an absent weak symbol: + self.run_weak_var_check("absent_weak_int", False) + self.run_weak_var_check("absent_weak_function", False) + + # Make sure we can do the same thing with present weak symbols + self.run_weak_var_check("present_weak_int", True) + self.run_weak_var_check("present_weak_function", True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/dylib.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/dylib.c new file mode 100644 index 00000000000..dc513e5c5fb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/dylib.c @@ -0,0 +1,14 @@ +#include "dylib.h" + +int present_weak_int = 10; +int present_weak_function() +{ + return present_weak_int; +} + +#if defined HAS_THEM +int absent_weak_int = 10; +int absent_weak_function() { + return absent_weak_int; +} +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/dylib.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/dylib.h new file mode 100644 index 00000000000..f668ec0a784 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/dylib.h @@ -0,0 +1,8 @@ +extern int absent_weak_int __attribute__((weak_import)); + +extern int present_weak_int __attribute__((weak_import)); + +extern int absent_weak_function() __attribute__((weak_import)); + +extern int present_weak_function() __attribute__((weak_import)); + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/main.c new file mode 100644 index 00000000000..5ea257bae5b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/main.c @@ -0,0 +1,23 @@ +#include "dylib.h" +#include <stdio.h> + +int +doSomething() +{ + // Set a breakpoint here. + if (&absent_weak_int != NULL) + printf("In absent_weak_int: %d\n", absent_weak_int); + if (absent_weak_function != NULL) + printf("In absent_weak_func: %p\n", absent_weak_function); + if (&present_weak_int != NULL) + printf("In present_weak_int: %d\n", present_weak_int); + if (present_weak_function != NULL) + printf("In present_weak_func: %p\n", present_weak_function); + +} + +int +main() +{ + return doSomething(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/module.modulemap b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/module.modulemap new file mode 100644 index 00000000000..6f7671400bc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/weak_symbols/module.modulemap @@ -0,0 +1,3 @@ +module Dylib { + header "dylib.h" +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/xvalue/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/xvalue/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/xvalue/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/xvalue/TestXValuePrinting.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/xvalue/TestXValuePrinting.py new file mode 100644 index 00000000000..3a394d781f0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/xvalue/TestXValuePrinting.py @@ -0,0 +1,36 @@ + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExprXValuePrintingTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + def do_test(self, dictionary=None): + """Printing an xvalue should work.""" + self.build(dictionary=dictionary) + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + '// Break here', self.main_source_spec) + frame = thread.GetFrameAtIndex(0) + + value = frame.EvaluateExpression("foo().data") + self.assertTrue(value.IsValid()) + self.assertTrue(value.GetError().Success()) + self.assertEqual(value.GetValueAsSigned(), 1234) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") + def test(self): + self.do_test() + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/xvalue/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/xvalue/main.cpp new file mode 100644 index 00000000000..556c63f2b44 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/expression/xvalue/main.cpp @@ -0,0 +1,12 @@ +struct Tmp +{ + int data = 1234; +}; + +Tmp foo() { return Tmp(); } + +int main(int argc, char const *argv[]) +{ + int something = foo().data; + return 0; // Break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/array/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/array/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/array/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/array/TestArray.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/array/TestArray.py new file mode 100644 index 00000000000..9b049a2bf2a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/array/TestArray.py @@ -0,0 +1,27 @@ +""" +Test the output of `frame diagnose` for an array access +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestArray(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/33842388> frame diagnose doesn't work for armv7 or arm64 + def test_array(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", "Thread should be stopped", + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + substrs=["a[10]"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/array/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/array/main.c new file mode 100644 index 00000000000..95c6515e5f5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/array/main.c @@ -0,0 +1,9 @@ +struct Foo { + int b; + int c; +}; + +int main() { + struct Foo *a = 0; + return a[10].c; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/bad-reference/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/bad-reference/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/bad-reference/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/bad-reference/TestBadReference.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/bad-reference/TestBadReference.py new file mode 100644 index 00000000000..8650484f12a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/bad-reference/TestBadReference.py @@ -0,0 +1,25 @@ +""" +Test the output of `frame diagnose` for dereferencing a bad reference +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestBadReference(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/33842388> frame diagnose doesn't work for armv7 or arm64 + def test_bad_reference(self): + TestBase.setUp(self) + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", "Thread should be stopped", + substrs=['stopped']) + self.expect("frame diagnose", "Crash diagnosis was accurate", "f->b") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/bad-reference/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/bad-reference/main.cpp new file mode 100644 index 00000000000..2f61152e398 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/bad-reference/main.cpp @@ -0,0 +1,22 @@ +struct Bar { + int c; + int d; +}; + +struct Foo { + int a; + struct Bar &b; +}; + +struct Foo *GetAFoo() { + static struct Foo f = { 0, *((Bar*)0) }; + return &f; +} + +int GetSum(struct Foo *f) { + return f->a + f->b.d; +} + +int main() { + return GetSum(GetAFoo()); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/complicated-expression/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/complicated-expression/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/complicated-expression/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/complicated-expression/TestComplicatedExpression.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/complicated-expression/TestComplicatedExpression.py new file mode 100644 index 00000000000..ccc0f88efe0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/complicated-expression/TestComplicatedExpression.py @@ -0,0 +1,28 @@ +""" +Test the output of `frame diagnose` for a subexpression of a complicated expression +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDiagnoseDereferenceArgument(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/33842388> frame diagnose doesn't work for armv7 or arm64 + def test_diagnose_dereference_argument(self): + TestBase.setUp(self) + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", "Thread should be stopped", + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + "f->b->d") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/complicated-expression/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/complicated-expression/main.c new file mode 100644 index 00000000000..147aae94614 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/complicated-expression/main.c @@ -0,0 +1,26 @@ +struct Bar { + int c; + int d; +}; + +struct Foo { + int a; + struct Bar *b; +}; + +struct Foo *GetAFoo() { + static struct Foo f = { 0, 0 }; + return &f; +} + +int SumTwoIntegers(int x, int y) { + return x + y; +} + +int GetSum(struct Foo *f) { + return SumTwoIntegers(f->a, f->b->d ? 0 : 1); +} + +int main() { + return GetSum(GetAFoo()); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-argument/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-argument/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-argument/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py new file mode 100644 index 00000000000..bdc89a6ed83 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-argument/TestDiagnoseDereferenceArgument.py @@ -0,0 +1,28 @@ +""" +Test the output of `frame diagnose` for dereferencing a function argument +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDiagnoseDereferenceArgument(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/33842388> frame diagnose doesn't work for armv7 or arm64 + def test_diagnose_dereference_argument(self): + TestBase.setUp(self) + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", "Thread should be stopped", + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + "f->b->d") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-argument/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-argument/main.c new file mode 100644 index 00000000000..0ec23b13be1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-argument/main.c @@ -0,0 +1,22 @@ +struct Bar { + int c; + int d; +}; + +struct Foo { + int a; + struct Bar *b; +}; + +struct Foo *GetAFoo() { + static struct Foo f = { 0, 0 }; + return &f; +} + +int GetSum(struct Foo *f) { + return f->a + f->b->d; +} + +int main() { + return GetSum(GetAFoo()); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-function-return/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-function-return/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-function-return/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py new file mode 100644 index 00000000000..c49c80791af --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-function-return/TestDiagnoseDereferenceFunctionReturn.py @@ -0,0 +1,31 @@ +""" +Test the output of `frame diagnose` for dereferencing a function's return value +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDiagnoseDereferenceFunctionReturn(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/33842388> frame diagnose doesn't work for armv7 or arm64 + @expectedFailureAll(oslist=['macosx'], archs=['i386'], bugnumber="rdar://28656408") + def test_diagnose_dereference_function_return(self): + TestBase.setUp(self) + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", "Thread should be stopped", + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + substrs=[ + "GetAFoo", + "->b"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-function-return/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-function-return/main.c new file mode 100644 index 00000000000..420e6f21de6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-function-return/main.c @@ -0,0 +1,12 @@ +struct Foo { + int a; + int b; +}; + +struct Foo *GetAFoo() { + return 0; +} + +int main() { + return GetAFoo()->b; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-this/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-this/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-this/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-this/TestDiagnoseDereferenceThis.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-this/TestDiagnoseDereferenceThis.py new file mode 100644 index 00000000000..85de511e56d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-this/TestDiagnoseDereferenceThis.py @@ -0,0 +1,28 @@ +""" +Test the output of `frame diagnose` for dereferencing `this` +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDiagnoseDereferenceThis(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/33842388> frame diagnose doesn't work for armv7 or arm64 + def test_diagnose_dereference_this(self): + TestBase.setUp(self) + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", "Thread should be stopped", + substrs=['stopped']) + self.expect( + "frame diagnose", + "Crash diagnosis was accurate", + "this->a") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-this/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-this/main.cpp new file mode 100644 index 00000000000..1f177230ed9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/dereference-this/main.cpp @@ -0,0 +1,15 @@ +struct Foo { + int a; + int b; + int Sum() { return a + b; } +}; + +struct Foo *GetAFoo() { + return (struct Foo*)0; +} + +int main() { + struct Foo *foo = GetAFoo(); + return foo->Sum(); +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/inheritance/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/inheritance/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/inheritance/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/inheritance/TestDiagnoseInheritance.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/inheritance/TestDiagnoseInheritance.py new file mode 100644 index 00000000000..54d44f0cb3c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/inheritance/TestDiagnoseInheritance.py @@ -0,0 +1,25 @@ +""" +Test the output of `frame diagnose` for calling virtual methods +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDiagnoseInheritance(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/33842388> frame diagnose doesn't work for armv7 or arm64 + def test_diagnose_inheritance(self): + TestBase.setUp(self) + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", "Thread should be stopped", + substrs=['stopped']) + self.expect("frame diagnose", "Crash diagnosis was accurate", "d") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/inheritance/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/inheritance/main.cpp new file mode 100644 index 00000000000..78cac2c8965 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/inheritance/main.cpp @@ -0,0 +1,69 @@ +#include <stdio.h> +#include <stdint.h> + +class A +{ +public: + A(int a) : + m_a(a) + { + } + virtual ~A(){} + virtual int get2() const { return m_a; } + virtual int get() const { return m_a; } +protected: + int m_a; +}; + +class B : public A +{ +public: + B(int a, int b) : + A(a), + m_b(b) + { + } + + ~B() override + { + } + + int get2() const override + { + return m_b; + } + int get() const override + { + return m_b; + } + +protected: + int m_b; +}; + +struct C +{ + C(int c) : m_c(c){} + virtual ~C(){} + int m_c; +}; + +class D : public C, public B +{ +public: + D(int a, int b, int c, int d) : + C(c), + B(a, b), + m_d(d) + { + } +protected: + int m_d; +}; +int main (int argc, char const *argv[], char const *envp[]) +{ + D *good_d = new D(1, 2, 3, 4); + D *d = nullptr; + return d->get(); +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/local-variable/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/local-variable/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/local-variable/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/local-variable/TestLocalVariable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/local-variable/TestLocalVariable.py new file mode 100644 index 00000000000..8d49d30b5e7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/local-variable/TestLocalVariable.py @@ -0,0 +1,25 @@ +""" +Test the output of `frame diagnose` for dereferencing a local variable +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestLocalVariable(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/33842388> frame diagnose doesn't work for armv7 or arm64 + def test_local_variable(self): + TestBase.setUp(self) + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", "Thread should be stopped", + substrs=['stopped']) + self.expect("frame diagnose", "Crash diagnosis was accurate", "myInt") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/local-variable/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/local-variable/main.c new file mode 100644 index 00000000000..33307beb070 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/local-variable/main.c @@ -0,0 +1,4 @@ +int main() { + int *myInt = 0; + return *myInt; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/virtual-method-call/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/virtual-method-call/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/virtual-method-call/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py new file mode 100644 index 00000000000..7ea42dea49c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/virtual-method-call/TestDiagnoseDereferenceVirtualMethodCall.py @@ -0,0 +1,25 @@ +""" +Test the output of `frame diagnose` for calling virtual methods +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDiagnoseVirtualMethodCall(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/33842388> frame diagnose doesn't work for armv7 or arm64 + def test_diagnose_virtual_method_call(self): + TestBase.setUp(self) + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", "Thread should be stopped", + substrs=['stopped']) + self.expect("frame diagnose", "Crash diagnosis was accurate", "foo") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/virtual-method-call/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/virtual-method-call/main.cpp new file mode 100644 index 00000000000..2a03dc11bf2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/diagnose/virtual-method-call/main.cpp @@ -0,0 +1,16 @@ +class Foo { +public: + int a; + int b; + virtual int Sum() { return a + b; } +}; + +struct Foo *GetAFoo() { + return (struct Foo*)0; +} + +int main() { + struct Foo *foo = GetAFoo(); + return foo->Sum(); +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/Makefile new file mode 100644 index 00000000000..993dc3f71a8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/Makefile @@ -0,0 +1,10 @@ +CXX_SOURCES := main.cpp other.cpp other-2.cpp +C_SOURCES := somefunc.c + +include Makefile.rules + +other-2.o: other-2.cpp + $(CXX) $(CFLAGS_NO_DEBUG) -c $(SRCDIR)/other-2.cpp + +somefunc.o: somefunc.c + $(CC) $(CFLAGS) -std=c99 -c $(SRCDIR)/somefunc.c diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/TestGuessLanguage.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/TestGuessLanguage.py new file mode 100644 index 00000000000..2c8d1dd4709 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/TestGuessLanguage.py @@ -0,0 +1,84 @@ +""" +Test the SB API SBFrame::GuessLanguage. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class TestFrameGuessLanguage(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + @skipIf(compiler="clang", compiler_version=['<', '10.0']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37658") + def test_guess_language(self): + """Test GuessLanguage for C and C++.""" + self.build() + self.do_test() + + def check_language(self, thread, frame_no, test_lang): + frame = thread.frames[frame_no] + self.assertTrue(frame.IsValid(), "Frame %d was not valid."%(frame_no)) + lang = frame.GuessLanguage() + self.assertEqual(lang, test_lang) + + def do_test(self): + """Test GuessLanguage for C & C++.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint in main.c at the source matching + # "Set a breakpoint here" + breakpoint = target.BreakpointCreateBySourceRegex( + "Set breakpoint here", lldb.SBFileSpec("somefunc.c")) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + error = lldb.SBError() + # This is the launch info. If you want to launch with arguments or + # environment variables, add them using SetArguments or + # SetEnvironmentEntries + + launch_info = lldb.SBLaunchInfo(None) + process = target.Launch(launch_info, error) + self.assertTrue(process, PROCESS_IS_VALID) + + # Did we hit our breakpoint? + from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) + self.assertTrue( + len(threads) == 1, + "There should be a thread stopped at our breakpoint") + + # The hit count for the breakpoint should be 1. + self.assertTrue(breakpoint.GetHitCount() == 1) + + thread = threads[0] + + c_frame_language = lldb.eLanguageTypeC99 + cxx_frame_language = lldb.eLanguageTypeC_plus_plus_11 + # gcc emits DW_LANG_C89 even if -std=c99 was specified + if "gcc" in self.getCompiler(): + c_frame_language = lldb.eLanguageTypeC89 + cxx_frame_language = lldb.eLanguageTypeC_plus_plus + + self.check_language(thread, 0, c_frame_language) + self.check_language(thread, 1, cxx_frame_language) + self.check_language(thread, 2, lldb.eLanguageTypeC_plus_plus) + + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/main.cpp new file mode 100644 index 00000000000..f5449f21790 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/main.cpp @@ -0,0 +1,10 @@ +#include <stdio.h> +#include "other.h" + +int +main() +{ + int test_var = 10; + Other::DoSomethingElse(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/other-2.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/other-2.cpp new file mode 100644 index 00000000000..77632de3ceb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/other-2.cpp @@ -0,0 +1,7 @@ +#include "other.h" + +void +Other::DoSomethingElse() +{ + DoSomething(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/other.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/other.cpp new file mode 100644 index 00000000000..41f4f26079a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/other.cpp @@ -0,0 +1,10 @@ +#include "other.h" + +extern "C" void some_func(); + +void +Other::DoSomething() +{ + some_func(); +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/other.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/other.h new file mode 100644 index 00000000000..0a2c125e6b4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/other.h @@ -0,0 +1,7 @@ +class Other +{ + public: + static void DoSomething(); + static void DoSomethingElse(); +}; + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/somefunc.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/somefunc.c new file mode 100644 index 00000000000..a4b4f47f32e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/language/somefunc.c @@ -0,0 +1,7 @@ +#include <stdio.h> + +void +some_func() +{ + printf("Set breakpoint here."); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/Makefile new file mode 100644 index 00000000000..8248c01fe6a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/Makefile @@ -0,0 +1,9 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -g0 # No debug info. +MAKE_DSYM := NO + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/TestFrameRecognizer.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/TestFrameRecognizer.py new file mode 100644 index 00000000000..2ecbe1e4c15 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/TestFrameRecognizer.py @@ -0,0 +1,119 @@ +# encoding: utf-8 +""" +Test lldb's frame recognizers. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +import recognizer + +class FrameRecognizerTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipUnlessDarwin + def test_frame_recognizer_1(self): + self.build() + + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + self.runCmd("command script import " + os.path.join(self.getSourceDir(), "recognizer.py")) + + self.expect("frame recognizer list", + substrs=['no matching results found.']) + + self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo") + + self.expect("frame recognizer list", + substrs=['0: recognizer.MyFrameRecognizer, module a.out, function foo']) + + self.runCmd("frame recognizer add -l recognizer.MyOtherFrameRecognizer -s a.out -n bar -x") + + self.expect("frame recognizer list", + substrs=['0: recognizer.MyFrameRecognizer, module a.out, function foo', + '1: recognizer.MyOtherFrameRecognizer, module a.out, function bar (regexp)' + ]) + + self.runCmd("frame recognizer delete 0") + + self.expect("frame recognizer list", + substrs=['1: recognizer.MyOtherFrameRecognizer, module a.out, function bar (regexp)']) + + self.runCmd("frame recognizer clear") + + self.expect("frame recognizer list", + substrs=['no matching results found.']) + + self.runCmd("frame recognizer add -l recognizer.MyFrameRecognizer -s a.out -n foo") + + lldbutil.run_break_set_by_symbol(self, "foo") + self.runCmd("r") + + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + process = target.GetProcess() + thread = process.GetSelectedThread() + frame = thread.GetSelectedFrame() + + self.assertEqual(frame.GetSymbol().GetName(), "foo") + self.assertFalse(frame.GetLineEntry().IsValid()) + + self.expect("frame variable", + substrs=['(int) a = 42', '(int) b = 56']) + + # Recognized arguments don't show up by default... + variables = frame.GetVariables(lldb.SBVariablesOptions()) + self.assertEqual(variables.GetSize(), 0) + + # ...unless you set target.display-recognized-arguments to 1... + self.runCmd("settings set target.display-recognized-arguments 1") + variables = frame.GetVariables(lldb.SBVariablesOptions()) + self.assertEqual(variables.GetSize(), 2) + + # ...and you can reset it back to 0 to hide them again... + self.runCmd("settings set target.display-recognized-arguments 0") + variables = frame.GetVariables(lldb.SBVariablesOptions()) + self.assertEqual(variables.GetSize(), 0) + + # ... or explicitly ask for them with SetIncludeRecognizedArguments(True). + opts = lldb.SBVariablesOptions() + opts.SetIncludeRecognizedArguments(True) + variables = frame.GetVariables(opts) + + self.assertEqual(variables.GetSize(), 2) + self.assertEqual(variables.GetValueAtIndex(0).name, "a") + self.assertEqual(variables.GetValueAtIndex(0).signed, 42) + self.assertEqual(variables.GetValueAtIndex(0).GetValueType(), lldb.eValueTypeVariableArgument) + self.assertEqual(variables.GetValueAtIndex(1).name, "b") + self.assertEqual(variables.GetValueAtIndex(1).signed, 56) + self.assertEqual(variables.GetValueAtIndex(1).GetValueType(), lldb.eValueTypeVariableArgument) + + self.expect("frame recognizer info 0", + substrs=['frame 0 is recognized by recognizer.MyFrameRecognizer']) + + self.expect("frame recognizer info 999", error=True, + substrs=['no frame with index 999']) + + self.expect("frame recognizer info 1", + substrs=['frame 1 not recognized by any recognizer']) + + # FIXME: The following doesn't work yet, but should be fixed. + """ + lldbutil.run_break_set_by_symbol(self, "bar") + self.runCmd("c") + + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect("frame variable -t", + substrs=['(int *) a = ']) + + self.expect("frame variable -t *a", + substrs=['*a = 78']) + """ diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/main.m new file mode 100644 index 00000000000..9c6ce9d2102 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/main.m @@ -0,0 +1,27 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +void foo(int a, int b) +{ + printf("%d %d\n", a, b); +} + +void bar(int *ptr) +{ + printf("%d\n", *ptr); +} + +int main (int argc, const char * argv[]) +{ + foo(42, 56); + int i = 78; + bar(&i); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/recognizer.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/recognizer.py new file mode 100644 index 00000000000..548676c0a4c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/recognizer/recognizer.py @@ -0,0 +1,21 @@ +# encoding: utf-8 + +import lldb + +class MyFrameRecognizer(object): + def get_recognized_arguments(self, frame): + if frame.name == "foo": + arg1 = frame.EvaluateExpression("$arg1").signed + arg2 = frame.EvaluateExpression("$arg2").signed + val1 = frame.GetThread().GetProcess().GetTarget().CreateValueFromExpression("a", "%d" % arg1) + val2 = frame.GetThread().GetProcess().GetTarget().CreateValueFromExpression("b", "%d" % arg2) + return [val1, val2] + elif frame.name == "bar": + arg1 = frame.EvaluateExpression("$arg1").signed + val1 = frame.GetThread().GetProcess().GetTarget().CreateValueFromExpression("a", "(int *)%d" % arg1) + return [val1] + return [] + +class MyOtherFrameRecognizer(object): + def get_recognized_arguments(self, frame): + return [] diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/select/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/select/Makefile new file mode 100644 index 00000000000..3d0b98f13f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/select/Makefile @@ -0,0 +1,2 @@ +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/select/TestFrameSelect.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/select/TestFrameSelect.py new file mode 100644 index 00000000000..2f2dd5aa493 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/select/TestFrameSelect.py @@ -0,0 +1,77 @@ +""" +Test 'frame select' command. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestFrameSelect(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + @skipIfWindows + def test_relative(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + self.expect("frame select -r 1", substrs=["nested2() at"]) + self.expect("frame select -r -1", substrs=["nested3() at"]) + + self.expect("frame select -r -1", error=True, substrs=["Already at the bottom of the stack."]) + self.expect("frame select -r -2147483647", error=True, substrs=["Already at the bottom of the stack."]) + self.expect("frame select -r -2147483648", error=True, substrs=["error: invalid frame offset argument '-2147483648'"]) + self.expect("frame select -r -2147483649", error=True, substrs=["error: invalid frame offset argument '-2147483649'"]) + + self.expect("frame select -r 1", substrs=["nested2() at"]) + self.expect("frame select -r -2", substrs=["nested3() at"]) + self.expect("frame select -r 1", substrs=["nested2() at"]) + self.expect("frame select -r -2147483647", substrs=["nested3() at"]) + self.expect("frame select -r 1", substrs=["nested2() at"]) + self.expect("frame select -r -2147483648", error=True, substrs=["error: invalid frame offset argument '-2147483648'"]) + self.expect("frame select -r -2147483649", error=True, substrs=["error: invalid frame offset argument '-2147483649'"]) + + self.expect("frame select -r 100") + self.expect("frame select -r 1", error=True, substrs=["Already at the top of the stack."]) + + @no_debug_info_test + @skipIfWindows + def test_mixing_relative_and_abs(self): + self.build() + + lldbutil.run_to_source_breakpoint(self, + "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) + + # The function associated with each frame index can change depending + # on the function calling main (e.g. `start`), so this only tests that + # the frame index number is correct. We test the actual functions + # in the relative test. + + # Jump to the top of the stack. + self.expect("frame select 0", substrs=["frame #0"]) + + # Run some relative commands. + self.expect("up", substrs=["frame #1"]) + self.expect("frame select -r 1", substrs=["frame #2"]) + self.expect("frame select -r -1", substrs=["frame #1"]) + + # Test that absolute indices still work. + self.expect("frame select 2", substrs=["frame #2"]) + self.expect("frame select 1", substrs=["frame #1"]) + self.expect("frame select 3", substrs=["frame #3"]) + self.expect("frame select 0", substrs=["frame #0"]) + self.expect("frame select 1", substrs=["frame #1"]) + + # Run some other relative frame select commands. + self.expect("down", substrs=["frame #0"]) + self.expect("frame select -r 1", substrs=["frame #1"]) + self.expect("frame select -r -1", substrs=["frame #0"]) + + # Test that absolute indices still work. + self.expect("frame select 2", substrs=["frame #2"]) + self.expect("frame select 1", substrs=["frame #1"]) + self.expect("frame select 3", substrs=["frame #3"]) + self.expect("frame select 0", substrs=["frame #0"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/select/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/select/main.cpp new file mode 100644 index 00000000000..c852bdb7e64 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/select/main.cpp @@ -0,0 +1,16 @@ +int nested3() { + return 3; // Set break point at this line. +} + +int nested2() { + return 2 + nested3(); +} + +int nested1() { + return 1 + nested2(); +} + + +int main(int argc, char **argv) { + return nested1(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var-scope/TestFrameVariableScope.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var-scope/TestFrameVariableScope.py new file mode 100644 index 00000000000..48e49ed009b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var-scope/TestFrameVariableScope.py @@ -0,0 +1,5 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), []) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var-scope/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var-scope/main.c new file mode 100644 index 00000000000..71f4cb234e3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var-scope/main.c @@ -0,0 +1,20 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int foo(int x, int y) { + int z = 3 + x; + return z + y; //% self.expect("frame variable -s", substrs=['ARG: (int) x = -3','ARG: (int) y = 0']) + //% self.expect("frame variable -s x", substrs=['ARG: (int) x = -3']) + //% self.expect("frame variable -s y", substrs=['ARG: (int) y = 0']) + //% self.expect("frame variable -s z", substrs=['LOCAL: (int) z = 0']) +} + +int main (int argc, char const *argv[]) +{ + return foo(-3,0); //% self.expect("frame variable -s argc argv", substrs=['ARG: (int) argc =']) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var/Makefile new file mode 100644 index 00000000000..695335e068c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var/TestFrameVar.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var/TestFrameVar.py new file mode 100644 index 00000000000..aa0f6b7e130 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var/TestFrameVar.py @@ -0,0 +1,91 @@ +""" +Make sure the frame variable -g, -a, and -l flags work. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class TestFrameVar(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def test_frame_var(self): + self.build() + self.do_test() + + def do_test(self): + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint in main.c at the source matching + # "Set a breakpoint here" + breakpoint = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here", lldb.SBFileSpec("main.c")) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + error = lldb.SBError() + # This is the launch info. If you want to launch with arguments or + # environment variables, add them using SetArguments or + # SetEnvironmentEntries + + launch_info = lldb.SBLaunchInfo(None) + process = target.Launch(launch_info, error) + self.assertTrue(process, PROCESS_IS_VALID) + + # Did we hit our breakpoint? + from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) + self.assertTrue( + len(threads) == 1, + "There should be a thread stopped at our breakpoint") + + # The hit count for the breakpoint should be 1. + self.assertTrue(breakpoint.GetHitCount() == 1) + + frame = threads[0].GetFrameAtIndex(0) + command_result = lldb.SBCommandReturnObject() + interp = self.dbg.GetCommandInterpreter() + + # Just get args: + result = interp.HandleCommand("frame var -l", command_result) + self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult, "frame var -a didn't succeed") + output = command_result.GetOutput() + self.assertTrue("argc" in output, "Args didn't find argc") + self.assertTrue("argv" in output, "Args didn't find argv") + self.assertTrue("test_var" not in output, "Args found a local") + self.assertTrue("g_var" not in output, "Args found a global") + + # Just get locals: + result = interp.HandleCommand("frame var -a", command_result) + self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult, "frame var -a didn't succeed") + output = command_result.GetOutput() + self.assertTrue("argc" not in output, "Locals found argc") + self.assertTrue("argv" not in output, "Locals found argv") + self.assertTrue("test_var" in output, "Locals didn't find test_var") + self.assertTrue("g_var" not in output, "Locals found a global") + + # Get the file statics: + result = interp.HandleCommand("frame var -l -a -g", command_result) + self.assertEqual(result, lldb.eReturnStatusSuccessFinishResult, "frame var -a didn't succeed") + output = command_result.GetOutput() + self.assertTrue("argc" not in output, "Globals found argc") + self.assertTrue("argv" not in output, "Globals found argv") + self.assertTrue("test_var" not in output, "Globals found test_var") + self.assertTrue("g_var" in output, "Globals didn't find g_var") + + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var/main.c new file mode 100644 index 00000000000..da23af2ac55 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/frame/var/main.c @@ -0,0 +1,11 @@ +#include <stdio.h> + +int g_var = 200; + +int +main(int argc, char **argv) +{ + int test_var = 10; + printf ("Set a breakpoint here: %d %d.\n", test_var, g_var); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/basic/Makefile new file mode 100644 index 00000000000..c9319d6e688 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/basic/Makefile @@ -0,0 +1,2 @@ +C_SOURCES := main.c +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/basic/TestGuiBasic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/basic/TestGuiBasic.py new file mode 100644 index 00000000000..2dcc7d08e6e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/basic/TestGuiBasic.py @@ -0,0 +1,64 @@ +""" +Test that the 'gui' displays the help window and basic UI. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test.lldbpexpect import PExpectTest + +class BasicGuiCommandTest(PExpectTest): + + mydir = TestBase.compute_mydir(__file__) + + # PExpect uses many timeouts internally and doesn't play well + # under ASAN on a loaded machine.. + @skipIfAsan + @skipIfCursesSupportMissing + @skipIfRemote # "run" command will not work correctly for remote debug + def test_gui(self): + self.build() + + self.launch(executable=self.getBuildArtifact("a.out"), dimensions=(100,500)) + self.expect('br set -f main.c -p "// Break here"', substrs=["Breakpoint 1", "address ="]) + self.expect("run", substrs=["stop reason ="]) + + + escape_key = chr(27).encode() + + # Start the GUI for the first time and check for the welcome window. + self.child.sendline("gui") + self.child.expect_exact("Welcome to the LLDB curses GUI.") + + # Press escape to quit the welcome screen + self.child.send(escape_key) + # Press escape again to quit the gui + self.child.send(escape_key) + self.expect_prompt() + + # Start the GUI a second time, this time we should have the normal GUI. + self.child.sendline("gui") + # Check for GUI elements in the menu bar. + self.child.expect_exact("Target") + self.child.expect_exact("Process") + self.child.expect_exact("Thread") + self.child.expect_exact("View") + self.child.expect_exact("Help") + + # Check the sources window. + self.child.expect_exact("Sources") + self.child.expect_exact("main") + self.child.expect_exact("funky_var_name_that_should_be_rendered") + + # Check the variable window. + self.child.expect_exact("Variables") + self.child.expect_exact("(int) funky_var_name_that_should_be_rendered = 22") + + # Check the bar at the bottom. + self.child.expect_exact("Frame:") + + # Press escape to quit the gui + self.child.send(escape_key) + + self.expect_prompt() + self.quit() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/basic/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/basic/main.c new file mode 100644 index 00000000000..97d57fc7183 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/basic/main.c @@ -0,0 +1,4 @@ +int main(int argc, char **argv) { + int funky_var_name_that_should_be_rendered = 22; + return 0; // Break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/invalid-args/TestInvalidArgsGui.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/invalid-args/TestInvalidArgsGui.py new file mode 100644 index 00000000000..11fdc92243b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/gui/invalid-args/TestInvalidArgsGui.py @@ -0,0 +1,13 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +class GuiTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + @skipIfCursesSupportMissing + def test_reproducer_generate_invalid_invocation(self): + self.expect("gui blub", error=True, + substrs=["the gui command takes no arguments."]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/help/TestHelp.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/help/TestHelp.py new file mode 100644 index 00000000000..31656af633c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/help/TestHelp.py @@ -0,0 +1,265 @@ +""" +Test some lldb help commands. + +See also CommandInterpreter::OutputFormattedHelpText(). +""" + + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class HelpCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_simplehelp(self): + """A simple test of 'help' command and its output.""" + self.expect("help", + startstr='Debugger commands:') + + self.expect("help -a", matching=False, + substrs=['next']) + + self.expect("help", matching=True, + substrs=['next']) + + @no_debug_info_test + def test_help_on_help(self): + """Testing the help on the help facility.""" + self.expect("help help", matching=True, + substrs=['--hide-aliases', + '--hide-user-commands']) + + @no_debug_info_test + def version_number_string(self): + """Helper function to find the version number string of lldb.""" + plist = os.path.join( + os.environ["LLDB_SRC"], + "resources", + "LLDB-Info.plist") + try: + CFBundleVersionSegFound = False + with open(plist, 'r') as f: + for line in f: + if CFBundleVersionSegFound: + version_line = line.strip() + import re + m = re.match("<string>(.*)</string>", version_line) + if m: + version = m.group(1) + return version + else: + # Unsuccessful, let's juts break out of the for + # loop. + break + + if line.find("<key>CFBundleVersion</key>") != -1: + # Found our match. The next line contains our version + # string, for example: + # + # <string>38</string> + CFBundleVersionSegFound = True + + except: + # Just fallthrough... + import traceback + traceback.print_exc() + + # Use None to signify that we are not able to grok the version number. + return None + + @no_debug_info_test + def test_help_arch(self): + """Test 'help arch' which should list of supported architectures.""" + self.expect("help arch", + substrs=['arm', 'x86_64', 'i386']) + + @no_debug_info_test + def test_help_version(self): + """Test 'help version' and 'version' commands.""" + self.expect("help version", + substrs=['Show the LLDB debugger version.']) + import re + version_str = self.version_number_string() + match = re.match('[0-9]+', version_str) + search_regexp = ['lldb( version|-' + (version_str if match else '[0-9]+') + ').*\n'] + + self.expect("version", + patterns=search_regexp) + + @no_debug_info_test + def test_help_should_not_crash_lldb(self): + """Command 'help disasm' should not crash lldb.""" + self.runCmd("help disasm", check=False) + self.runCmd("help unsigned-integer") + + @no_debug_info_test + def test_help_should_not_hang_emacsshell(self): + """Command 'settings set term-width 0' should not hang the help command.""" + self.expect( + "settings set term-width 0", + COMMAND_FAILED_AS_EXPECTED, + error=True, + substrs=['error: 0 is out of range, valid values must be between']) + # self.runCmd("settings set term-width 0") + self.expect("help", + startstr='Debugger commands:') + + @no_debug_info_test + def test_help_breakpoint_set(self): + """Test that 'help breakpoint set' does not print out redundant lines of: + 'breakpoint set [-s <shlib-name>] ...'.""" + self.expect("help breakpoint set", matching=False, + substrs=['breakpoint set [-s <shlib-name>]']) + + @no_debug_info_test + def test_help_image_dump_symtab_should_not_crash(self): + """Command 'help image dump symtab' should not crash lldb.""" + # 'image' is an alias for 'target modules'. + self.expect("help image dump symtab", + substrs=['dump symtab', + 'sort-order']) + + @no_debug_info_test + def test_help_image_du_sym_is_ambiguous(self): + """Command 'help image du sym' is ambiguous and spits out the list of candidates.""" + self.expect("help image du sym", + COMMAND_FAILED_AS_EXPECTED, error=True, + substrs=['error: ambiguous command image du sym', + 'symfile', + 'symtab']) + + @no_debug_info_test + def test_help_image_du_line_should_work(self): + """Command 'help image du line-table' is not ambiguous and should work.""" + # 'image' is an alias for 'target modules'. + self.expect("help image du line", substrs=[ + 'Dump the line table for one or more compilation units']) + + @no_debug_info_test + def test_help_target_variable_syntax(self): + """Command 'help target variable' should display <variable-name> ...""" + self.expect("help target variable", + substrs=['<variable-name> [<variable-name> [...]]']) + + @no_debug_info_test + def test_help_watchpoint_and_its_args(self): + """Command 'help watchpoint', 'help watchpt-id', and 'help watchpt-id-list' should work.""" + self.expect("help watchpoint", + substrs=['delete', 'disable', 'enable', 'list']) + self.expect("help watchpt-id", + substrs=['<watchpt-id>']) + self.expect("help watchpt-id-list", + substrs=['<watchpt-id-list>']) + + @no_debug_info_test + def test_help_watchpoint_set(self): + """Test that 'help watchpoint set' prints out 'expression' and 'variable' + as the possible subcommands.""" + self.expect("help watchpoint set", + substrs=['The following subcommands are supported:'], + patterns=['expression +--', + 'variable +--']) + + @no_debug_info_test + def test_help_po_hides_options(self): + """Test that 'help po' does not show all the options for expression""" + self.expect( + "help po", + substrs=[ + '--show-all-children', + '--object-description'], + matching=False) + + @no_debug_info_test + def test_help_run_hides_options(self): + """Test that 'help run' does not show all the options for process launch""" + self.expect("help run", + substrs=['--arch', '--environment'], matching=False) + + @no_debug_info_test + def test_help_next_shows_options(self): + """Test that 'help next' shows all the options for thread step-over""" + self.expect("help next", + substrs=['--step-out-avoids-no-debug', '--run-mode'], matching=True) + + @no_debug_info_test + def test_help_provides_alternatives(self): + """Test that help on commands that don't exist provides information on additional help avenues""" + self.expect( + "help thisisnotadebuggercommand", + substrs=[ + "'thisisnotadebuggercommand' is not a known command.", + "Try 'help' to see a current list of commands.", + "Try 'apropos thisisnotadebuggercommand' for a list of related commands.", + "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc."], + error=True) + + self.expect( + "help process thisisnotadebuggercommand", + substrs=[ + "'process thisisnotadebuggercommand' is not a known command.", + "Try 'help' to see a current list of commands.", + "Try 'apropos thisisnotadebuggercommand' for a list of related commands.", + "Try 'type lookup thisisnotadebuggercommand' for information on types, methods, functions, modules, etc."]) + + @no_debug_info_test + def test_custom_help_alias(self): + """Test that aliases pick up custom help text.""" + def cleanup(): + self.runCmd('command unalias afriendlyalias', check=False) + self.runCmd('command unalias averyfriendlyalias', check=False) + + self.addTearDownHook(cleanup) + self.runCmd( + 'command alias --help "I am a friendly alias" -- afriendlyalias help') + self.expect( + "help afriendlyalias", + matching=True, + substrs=['I am a friendly alias']) + self.runCmd( + 'command alias --long-help "I am a very friendly alias" -- averyfriendlyalias help') + self.expect("help averyfriendlyalias", matching=True, + substrs=['I am a very friendly alias']) + @no_debug_info_test + def test_alias_prints_origin(self): + """Test that 'help <unique_match_to_alias>' prints the alias origin.""" + def cleanup(): + self.runCmd('command unalias alongaliasname', check=False) + + self.addTearDownHook(cleanup) + self.runCmd('command alias alongaliasname help') + self.expect("help alongaliasna", matching=True, + substrs=["'alongaliasna' is an abbreviation for 'help'"]) + + @no_debug_info_test + def test_hidden_help(self): + self.expect("help -h", + substrs=["_regexp-bt"]) + + @no_debug_info_test + def test_help_ambiguous(self): + self.expect("help g", + substrs=["Help requested with ambiguous command name, possible completions:", + "gdb-remote", "gui"]) + + @no_debug_info_test + def test_help_unknown_flag(self): + self.expect("help -z", error=True, + substrs=["unknown or ambiguous option"]) + + @no_debug_info_test + def test_help_format_output(self): + """Test that help output reaches TerminalWidth.""" + self.runCmd( + 'settings set term-width 108') + self.expect( + "help format", + matching=True, + substrs=['<format> -- One of the format names']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/basic/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/basic/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/basic/TestLogging.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/basic/TestLogging.py new file mode 100644 index 00000000000..16321dca86f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/basic/TestLogging.py @@ -0,0 +1,102 @@ +""" +Test lldb logging. This test just makes sure logging doesn't crash, and produces some output. +""" + + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LogTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + super(LogTestCase, self).setUp() + self.log_file = self.getBuildArtifact("log-file.txt") + + def test_file_writing(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.expect("file " + exe, + patterns=["Current executable set to .*a.out"]) + + if (os.path.exists(self.log_file)): + os.remove(self.log_file) + + # By default, Debugger::EnableLog() will set log options to + # PREPEND_THREAD_NAME + OPTION_THREADSAFE. We don't want the + # threadnames here, so we enable just threadsafe (-t). + self.runCmd("log enable -t -f '%s' lldb commands" % (self.log_file)) + + self.runCmd("command alias bp breakpoint") + + self.runCmd("bp set -n main") + + self.runCmd("bp l") + + self.runCmd("log disable lldb") + + self.assertTrue(os.path.isfile(self.log_file)) + + f = open(self.log_file) + log_lines = f.readlines() + f.close() + os.remove(self.log_file) + + self.assertGreater( + len(log_lines), + 0, + "Something was written to the log file.") + + # Check that lldb truncates its log files + def test_log_truncate(self): + # put something in our log file + with open(self.log_file, "w") as f: + for i in range(1, 1000): + f.write("bacon\n") + + self.runCmd("log enable -t -f '%s' lldb commands" % self.log_file) + self.runCmd("help log") + self.runCmd("log disable lldb") + + self.assertTrue(os.path.isfile(self.log_file)) + with open(self.log_file, "r") as f: + contents = f.read() + + # check that it got removed + self.assertEquals(contents.find("bacon"), -1) + + # Check that lldb can append to a log file + def test_log_append(self): + # put something in our log file + with open(self.log_file, "w") as f: + f.write("bacon\n") + + self.runCmd( "log enable -t -a -f '%s' lldb commands" % self.log_file) + self.runCmd("help log") + self.runCmd("log disable lldb") + + self.assertTrue(os.path.isfile(self.log_file)) + with open(self.log_file, "r") as f: + contents = f.read() + + # check that it is still there + self.assertEquals(contents.find("bacon"), 0) + + # Enable all log options and check that nothing crashes. + @skipIfWindows + def test_all_log_options(self): + if (os.path.exists(self.log_file)): + os.remove(self.log_file) + + self.runCmd("log enable -v -t -s -T -p -n -S -F -f '%s' lldb commands" % self.log_file) + self.runCmd("help log") + self.runCmd("log disable lldb") + + self.assertTrue(os.path.isfile(self.log_file)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/basic/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/basic/main.cpp new file mode 100644 index 00000000000..f5f1687695b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/basic/main.cpp @@ -0,0 +1,61 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <cstdlib> +#include <string> +#include <fstream> +#include <iostream> + +int +product (int x, int y) +{ + int result = x * y; + return result; +} + +int +sum (int a, int b) +{ + int result = a + b; + return result; +} + +int +strange_max (int m, int n) +{ + if (m > n) + return m; + else if (n > m) + return n; + else + return 0; +} + +int +foo (int i, int j) +{ + if (strange_max (i, j) == i) + return product (i, j); + else if (strange_max (i, j) == j) + return sum (i, j); + else + return product (sum (i, i), sum (j, j)); +} + +int +main(int argc, char const *argv[]) +{ + + int array[3]; + + array[0] = foo (1238, 78392); + array[1] = foo (379265, 23674); + array[2] = foo (872934, 234); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/invalid-args/TestInvalidArgsLog.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/invalid-args/TestInvalidArgsLog.py new file mode 100644 index 00000000000..4d3c5733598 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/log/invalid-args/TestInvalidArgsLog.py @@ -0,0 +1,22 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +class InvalidArgsLogTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_enable_empty(self): + self.expect("log enable", error=True, + substrs=["error: log enable takes a log channel and one or more log types."]) + + @no_debug_info_test + def test_disable_empty(self): + self.expect("log disable", error=True, + substrs=["error: log disable takes a log channel and one or more log types."]) + + @no_debug_info_test + def test_timer_empty(self): + self.expect("log timer", error=True, + substrs=["error: Missing subcommand"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/basic/TestPlatformCommand.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/basic/TestPlatformCommand.py new file mode 100644 index 00000000000..ab45b221c94 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/basic/TestPlatformCommand.py @@ -0,0 +1,79 @@ +""" +Test some lldb platform commands. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PlatformCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_help_platform(self): + self.runCmd("help platform") + + @no_debug_info_test + def test_list(self): + self.expect("platform list", + patterns=['^Available platforms:']) + + @no_debug_info_test + def test_process_list(self): + self.expect("platform process list", + substrs=['PID', 'TRIPLE', 'NAME']) + + @no_debug_info_test + def test_process_info_with_no_arg(self): + """This is expected to fail and to return a proper error message.""" + self.expect("platform process info", error=True, + substrs=['one or more process id(s) must be specified']) + + @no_debug_info_test + def test_status(self): + self.expect( + "platform status", + substrs=[ + 'Platform', + 'Triple', + 'OS Version', + 'Kernel', + 'Hostname']) + + @expectedFailureAll(oslist=["windows"]) + @no_debug_info_test + def test_shell(self): + """ Test that the platform shell command can invoke ls. """ + triple = self.dbg.GetSelectedPlatform().GetTriple() + if re.match(".*-.*-windows", triple): + self.expect( + "platform shell dir c:\\", substrs=[ + "Windows", "Program Files"]) + elif re.match(".*-.*-.*-android", triple): + self.expect( + "platform shell ls /", + substrs=[ + "cache", + "dev", + "system"]) + else: + self.expect("platform shell ls /", substrs=["dev", "tmp", "usr"]) + + @no_debug_info_test + def test_shell_builtin(self): + """ Test a shell built-in command (echo) """ + self.expect("platform shell echo hello lldb", + substrs=["hello lldb"]) + + # FIXME: re-enable once platform shell -t can specify the desired timeout + @no_debug_info_test + def test_shell_timeout(self): + """ Test a shell built-in command (sleep) that times out """ + self.skipTest("due to taking too long to complete.") + self.expect("platform shell sleep 15", error=True, substrs=[ + "error: timed out waiting for shell command to complete"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/basic/TestPlatformPython.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/basic/TestPlatformPython.py new file mode 100644 index 00000000000..ab10d30b6ff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/basic/TestPlatformPython.py @@ -0,0 +1,81 @@ +""" +Test the lldb platform Python API. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PlatformPythonTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + @no_debug_info_test + def test_platform_list(self): + """Test SBDebugger::GetNumPlatforms() & GetPlatformAtIndex() API""" + # Verify the host platform is present by default. + initial_num_platforms = self.dbg.GetNumPlatforms() + self.assertGreater(initial_num_platforms, 0) + host_platform = self.dbg.GetPlatformAtIndex(0) + self.assertTrue(host_platform.IsValid() and + host_platform.GetName() == 'host', + 'The host platform is present') + # Select another platform and verify that the platform is added to + # the platform list. + platform_idx = self.dbg.GetNumAvailablePlatforms() - 1 + if platform_idx < 1: + self.fail('No platforms other than host are available') + platform_data = self.dbg.GetAvailablePlatformInfoAtIndex(platform_idx) + platform_name = platform_data.GetValueForKey('name').GetStringValue(100) + self.assertNotEqual(platform_name, 'host') + self.dbg.SetCurrentPlatform(platform_name) + selected_platform = self.dbg.GetSelectedPlatform() + self.assertTrue(selected_platform.IsValid()) + self.assertEqual(selected_platform.GetName(), platform_name) + self.assertEqual(self.dbg.GetNumPlatforms(), initial_num_platforms + 1) + platform_found = False + for platform_idx in range(self.dbg.GetNumPlatforms()): + platform = self.dbg.GetPlatformAtIndex(platform_idx) + if platform.GetName() == platform_name: + platform_found = True + break + self.assertTrue(platform_found) + + @add_test_categories(['pyapi']) + @no_debug_info_test + def test_host_is_connected(self): + # We've already tested that this one IS the host platform. + host_platform = self.dbg.GetPlatformAtIndex(0) + self.assertTrue(host_platform.IsConnected(), "The host platform is always connected") + + + @add_test_categories(['pyapi']) + @no_debug_info_test + def test_available_platform_list(self): + """Test SBDebugger::GetNumAvailablePlatforms() and GetAvailablePlatformInfoAtIndex() API""" + num_platforms = self.dbg.GetNumAvailablePlatforms() + self.assertGreater( + num_platforms, 0, + 'There should be at least one platform available') + + for i in range(num_platforms): + platform_data = self.dbg.GetAvailablePlatformInfoAtIndex(i) + name_data = platform_data.GetValueForKey('name') + desc_data = platform_data.GetValueForKey('description') + self.assertTrue( + name_data and name_data.IsValid(), + 'Platform has a name') + self.assertEqual( + name_data.GetType(), lldb.eStructuredDataTypeString, + 'Platform name is a string') + self.assertTrue( + desc_data and desc_data.IsValid(), + 'Platform has a description') + self.assertEqual( + desc_data.GetType(), lldb.eStructuredDataTypeString, + 'Platform description is a string') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/process/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/process/Makefile new file mode 100644 index 00000000000..b560876f24e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/process/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +EXE := TestProcess + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/process/TestProcessList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/process/TestProcessList.py new file mode 100644 index 00000000000..102d6f92dd1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/process/TestProcessList.py @@ -0,0 +1,32 @@ +""" +Test process list. +""" + + + +import os +import lldb +import shutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ProcessListTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @skipIfWindows # https://bugs.llvm.org/show_bug.cgi?id=43702 + def test_process_list_with_args(self): + """Test process list show process args""" + self.build() + exe = self.getBuildArtifact("TestProcess") + + # Spawn a new process + popen = self.spawnSubprocess(exe, args=["arg1", "--arg2", "arg3"]) + self.addTearDownHook(self.cleanupSubprocesses) + + self.expect("platform process list -v", + substrs=["TestProcess arg1 --arg2 arg3", str(popen.pid)]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/process/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/process/main.cpp new file mode 100644 index 00000000000..da43e60155e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/platform/process/main.cpp @@ -0,0 +1,9 @@ +#include <stdio.h> + +#include <chrono> +#include <thread> + +int main(int argc, char const *argv[]) { + std::this_thread::sleep_for(std::chrono::seconds(30)); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach-resume/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach-resume/Makefile new file mode 100644 index 00000000000..dc1d28d1c03 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach-resume/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +EXE := AttachResume + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach-resume/TestAttachResume.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach-resume/TestAttachResume.py new file mode 100644 index 00000000000..b559f44a6b3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach-resume/TestAttachResume.py @@ -0,0 +1,93 @@ +""" +Test process attach/resume. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +exe_name = "AttachResume" # Must match Makefile + + +class AttachResumeTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipIfRemote + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr19310') + @expectedFailureNetBSD + @skipIfWindows # llvm.org/pr24778, llvm.org/pr21753 + def test_attach_continue_interrupt_detach(self): + """Test attach/continue/interrupt/detach""" + self.build() + self.process_attach_continue_interrupt_detach() + + def process_attach_continue_interrupt_detach(self): + """Test attach/continue/interrupt/detach""" + + exe = self.getBuildArtifact(exe_name) + + popen = self.spawnSubprocess(exe) + self.addTearDownHook(self.cleanupSubprocesses) + + self.runCmd("process attach -p " + str(popen.pid)) + + self.setAsync(True) + listener = self.dbg.GetListener() + process = self.dbg.GetSelectedTarget().GetProcess() + + self.runCmd("c") + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning]) + + self.runCmd("process interrupt") + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateStopped]) + + # be sure to continue/interrupt/continue (r204504) + self.runCmd("c") + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning]) + + self.runCmd("process interrupt") + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateStopped]) + + # Second interrupt should have no effect. + self.expect( + "process interrupt", + patterns=["Process is not running"], + error=True) + + # check that this breakpoint is auto-cleared on detach (r204752) + self.runCmd("br set -f main.cpp -l %u" % + (line_number('main.cpp', '// Set breakpoint here'))) + + self.runCmd("c") + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning, lldb.eStateStopped]) + self.expect('br list', 'Breakpoint not hit', + substrs=['hit count = 1']) + + # Make sure the breakpoint is not hit again. + self.expect("expr debugger_flag = false", substrs=[" = false"]) + + self.runCmd("c") + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning]) + + # make sure to detach while in running state (r204759) + self.runCmd("detach") + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateDetached]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach-resume/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach-resume/main.cpp new file mode 100644 index 00000000000..82aad70eed5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach-resume/main.cpp @@ -0,0 +1,35 @@ +#include <stdio.h> +#include <fcntl.h> + +#include <chrono> +#include <thread> + +volatile bool debugger_flag = true; // The debugger will flip this to false + +void *start(void *data) +{ + int i; + size_t idx = (size_t)data; + for (i=0; i<30; i++) + { + if ( idx == 0 && debugger_flag) + std::this_thread::sleep_for(std::chrono::microseconds(1)); // Set breakpoint here + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + return 0; +} + +int main(int argc, char const *argv[]) +{ + lldb_enable_attach(); + + static const size_t nthreads = 16; + std::thread threads[nthreads]; + size_t i; + + for (i=0; i<nthreads; i++) + threads[i] = std::move(std::thread(start, (void*)i)); + + for (i=0; i<nthreads; i++) + threads[i].join(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/Makefile new file mode 100644 index 00000000000..8a52f8fcd47 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +EXE := ProcessAttach + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/TestProcessAttach.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/TestProcessAttach.py new file mode 100644 index 00000000000..b85d5713350 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/TestProcessAttach.py @@ -0,0 +1,90 @@ +""" +Test process attach. +""" + + + +import os +import lldb +import shutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +exe_name = "ProcessAttach" # Must match Makefile + + +class ProcessAttachTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @skipIfiOSSimulator + @expectedFailureNetBSD + def test_attach_to_process_by_id(self): + """Test attach by process id""" + self.build() + exe = self.getBuildArtifact(exe_name) + + # Spawn a new process + popen = self.spawnSubprocess(exe) + self.addTearDownHook(self.cleanupSubprocesses) + + self.runCmd("process attach -p " + str(popen.pid)) + + target = self.dbg.GetSelectedTarget() + + process = target.GetProcess() + self.assertTrue(process, PROCESS_IS_VALID) + + @expectedFailureNetBSD + def test_attach_to_process_from_different_dir_by_id(self): + """Test attach by process id""" + newdir = self.getBuildArtifact("newdir") + try: + os.mkdir(newdir) + except OSError as e: + if e.errno != os.errno.EEXIST: + raise + testdir = self.getBuildDir() + exe = os.path.join(newdir, 'proc_attach') + self.buildProgram('main.cpp', exe) + self.addTearDownHook(lambda: shutil.rmtree(newdir)) + + # Spawn a new process + popen = self.spawnSubprocess(exe) + self.addTearDownHook(self.cleanupSubprocesses) + + os.chdir(newdir) + self.addTearDownHook(lambda: os.chdir(testdir)) + self.runCmd("process attach -p " + str(popen.pid)) + + target = self.dbg.GetSelectedTarget() + + process = target.GetProcess() + self.assertTrue(process, PROCESS_IS_VALID) + + @expectedFailureNetBSD + def test_attach_to_process_by_name(self): + """Test attach by process name""" + self.build() + exe = self.getBuildArtifact(exe_name) + + # Spawn a new process + popen = self.spawnSubprocess(exe) + self.addTearDownHook(self.cleanupSubprocesses) + + self.runCmd("process attach -n " + exe_name) + + target = self.dbg.GetSelectedTarget() + + process = target.GetProcess() + self.assertTrue(process, PROCESS_IS_VALID) + + def tearDown(self): + # Destroy process before TestBase.tearDown() + self.dbg.GetSelectedTarget().GetProcess().Destroy() + + # Call super's tearDown(). + TestBase.tearDown(self) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/Makefile new file mode 100644 index 00000000000..a694d36ac0d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/Makefile @@ -0,0 +1,12 @@ +CXX_SOURCES := main.cpp + +EXE := AttachDenied + +all: AttachDenied sign + +include Makefile.rules + +sign: entitlements.plist AttachDenied +ifeq ($(OS),Darwin) + codesign -s - -f --entitlements $^ +endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/TestAttachDenied.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/TestAttachDenied.py new file mode 100644 index 00000000000..dcd73da42e9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/TestAttachDenied.py @@ -0,0 +1,45 @@ +""" +Test denied process attach. +""" + + + +import time +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +exe_name = 'AttachDenied' # Must match Makefile + + +class AttachDeniedTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipIfWindows + @skipIfiOSSimulator + @skipIfDarwinEmbedded # ptrace(ATTACH_REQUEST...) won't work on ios/tvos/etc + def test_attach_to_process_by_id_denied(self): + """Test attach by process id denied""" + self.build() + exe = self.getBuildArtifact(exe_name) + + # Use a file as a synchronization point between test and inferior. + pid_file_path = lldbutil.append_to_process_working_directory(self, + "pid_file_%d" % (int(time.time()))) + self.addTearDownHook( + lambda: self.run_platform_command( + "rm %s" % + (pid_file_path))) + + # Spawn a new process + popen = self.spawnSubprocess(exe, [pid_file_path]) + self.addTearDownHook(self.cleanupSubprocesses) + + pid = lldbutil.wait_for_file_on_target(self, pid_file_path) + + self.expect('process attach -p ' + pid, + startstr='error: attach failed:', + error=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/entitlements.plist b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/entitlements.plist new file mode 100644 index 00000000000..3d60e8bd0b9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/entitlements.plist @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>com.apple.security.cs.debugger</key> + <true/> +</dict> +</plist> diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/main.cpp new file mode 100644 index 00000000000..ff1fccae4b1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/attach_denied/main.cpp @@ -0,0 +1,108 @@ +#include <errno.h> +#include <fcntl.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include <sys/types.h> +#include <sys/ptrace.h> +#include <sys/stat.h> +#include <sys/wait.h> + +#if defined(PTRACE_ATTACH) +#define ATTACH_REQUEST PTRACE_ATTACH +#define DETACH_REQUEST PTRACE_DETACH +#elif defined(PT_ATTACH) +#define ATTACH_REQUEST PT_ATTACH +#define DETACH_REQUEST PT_DETACH +#else +#error "Unsupported platform" +#endif + +bool writePid (const char* file_name, const pid_t pid) +{ + char *tmp_file_name = (char *)malloc(strlen(file_name) + 16); + strcpy(tmp_file_name, file_name); + strcat(tmp_file_name, "_tmp"); + int fd = open (tmp_file_name, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); + if (fd == -1) + { + fprintf (stderr, "open(%s) failed: %s\n", tmp_file_name, strerror (errno)); + free(tmp_file_name); + return false; + } + char buffer[64]; + snprintf (buffer, sizeof(buffer), "%ld", (long)pid); + + bool res = true; + if (write (fd, buffer, strlen (buffer)) == -1) + { + fprintf (stderr, "write(%s) failed: %s\n", buffer, strerror (errno)); + res = false; + } + close (fd); + + if (rename (tmp_file_name, file_name) == -1) + { + fprintf (stderr, "rename(%s, %s) failed: %s\n", tmp_file_name, file_name, strerror (errno)); + res = false; + } + free(tmp_file_name); + + return res; +} + +void signal_handler (int) +{ +} + +int main (int argc, char const *argv[]) +{ + if (argc < 2) + { + fprintf (stderr, "invalid number of command line arguments\n"); + return 1; + } + + const pid_t pid = fork (); + if (pid == -1) + { + fprintf (stderr, "fork failed: %s\n", strerror (errno)); + return 1; + } + + if (pid > 0) + { + // Make pause call to return when a signal is received. Normally this happens when the + // test runner tries to terminate us. + signal (SIGHUP, signal_handler); + signal (SIGTERM, signal_handler); + if (ptrace (ATTACH_REQUEST, pid, NULL, 0) == -1) + { + fprintf (stderr, "ptrace(ATTACH) failed: %s\n", strerror (errno)); + } + else + { + if (writePid (argv[1], pid)) + pause (); // Waiting for the debugger trying attach to the child. + + if (ptrace (DETACH_REQUEST, pid, NULL, 0) != 0) + fprintf (stderr, "ptrace(DETACH) failed: %s\n", strerror (errno)); + } + + kill (pid, SIGTERM); + int status = 0; + if (waitpid (pid, &status, 0) == -1) + fprintf (stderr, "waitpid failed: %s\n", strerror (errno)); + } + else + { + // child inferior. + pause (); + } + + printf ("Exiting now\n"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/main.cpp new file mode 100644 index 00000000000..46ffacc0a84 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/attach/main.cpp @@ -0,0 +1,20 @@ +#include <stdio.h> + +#include <chrono> +#include <thread> + +int main(int argc, char const *argv[]) { + int temp; + lldb_enable_attach(); + + // Waiting to be attached by the debugger. + temp = 0; + + while (temp < 30) // Waiting to be attached... + { + std::this_thread::sleep_for(std::chrono::seconds(2)); + temp++; + } + + printf("Exiting now\n"); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/TestLaunchWithShellExpand.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/TestLaunchWithShellExpand.py new file mode 100644 index 00000000000..49bd0cf1d56 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/TestLaunchWithShellExpand.py @@ -0,0 +1,124 @@ +""" +Test that argdumper is a viable launching strategy. +""" +import os + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LaunchWithShellExpandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @expectedFailureAll( + oslist=[ + "windows", + "linux", + "freebsd"], + bugnumber="llvm.org/pr24778 llvm.org/pr22627") + @skipIfDarwinEmbedded # iOS etc don't launch the binary via a shell, so arg expansion won't happen + @expectedFailureNetBSD + def test(self): + self.build() + exe = self.getBuildArtifact("a.out") + + self.runCmd("target create %s" % exe) + + # Create the target + target = self.dbg.CreateTarget(exe) + + # Create any breakpoints we need + breakpoint = target.BreakpointCreateBySourceRegex( + 'break here', lldb.SBFileSpec("main.cpp", False)) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Ensure we do the expansion with /bin/sh on POSIX. + os.environ["SHELL"] = '/bin/sh' + + self.runCmd( + "process launch -X true -w %s -- fi*.tx? () > <" % + (self.getSourceDir())) + + process = self.process() + + self.assertTrue(process.GetState() == lldb.eStateStopped, + STOPPED_DUE_TO_BREAKPOINT) + + thread = process.GetThreadAtIndex(0) + + self.assertTrue(thread.IsValid(), + "Process stopped at 'main' should have a valid thread") + + stop_reason = thread.GetStopReason() + + self.assertTrue( + stop_reason == lldb.eStopReasonBreakpoint, + "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint") + + self.expect("frame variable argv[1]", substrs=['file1.txt']) + self.expect("frame variable argv[2]", substrs=['file2.txt']) + self.expect("frame variable argv[3]", substrs=['file3.txt']) + self.expect("frame variable argv[4]", substrs=['file4.txy']) + self.expect("frame variable argv[5]", substrs=['()']) + self.expect("frame variable argv[6]", substrs=['>']) + self.expect("frame variable argv[7]", substrs=['<']) + self.expect( + "frame variable argv[5]", + substrs=['file5.tyx'], + matching=False) + self.expect( + "frame variable argv[8]", + substrs=['file5.tyx'], + matching=False) + + self.runCmd("process kill") + + self.runCmd( + 'process launch -X true -w %s -- "foo bar"' % + (self.getSourceDir())) + + process = self.process() + + self.assertTrue(process.GetState() == lldb.eStateStopped, + STOPPED_DUE_TO_BREAKPOINT) + + thread = process.GetThreadAtIndex(0) + + self.assertTrue(thread.IsValid(), + "Process stopped at 'main' should have a valid thread") + + stop_reason = thread.GetStopReason() + + self.assertTrue( + stop_reason == lldb.eStopReasonBreakpoint, + "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint") + + self.expect("frame variable argv[1]", substrs=['foo bar']) + + self.runCmd("process kill") + + self.runCmd('process launch -X true -w %s -- foo\ bar' + % (self.getBuildDir())) + + process = self.process() + + self.assertTrue(process.GetState() == lldb.eStateStopped, + STOPPED_DUE_TO_BREAKPOINT) + + thread = process.GetThreadAtIndex(0) + + self.assertTrue(thread.IsValid(), + "Process stopped at 'main' should have a valid thread") + + stop_reason = thread.GetStopReason() + + self.assertTrue( + stop_reason == lldb.eStopReasonBreakpoint, + "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint") + + self.expect("frame variable argv[1]", substrs=['foo bar']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file1.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file1.txt new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file1.txt diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file2.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file2.txt new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file2.txt diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file3.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file3.txt new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file3.txt diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file4.txy b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file4.txy new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file4.txy diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file5.tyx b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file5.tyx new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/file5.tyx diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/foo bar b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/foo bar new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/foo bar diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/main.cpp new file mode 100644 index 00000000000..cbef8d1e6da --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch-with-shellexpand/main.cpp @@ -0,0 +1,5 @@ +int +main (int argc, char const **argv) +{ + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/Makefile new file mode 100644 index 00000000000..eff77274c7b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp +#CXX_SOURCES := print-cwd.cpp + +include Makefile.rules + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/TestProcessLaunch.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/TestProcessLaunch.py new file mode 100644 index 00000000000..a2b27c2e590 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/TestProcessLaunch.py @@ -0,0 +1,205 @@ +""" +Test lldb process launch flags. +""" + +from __future__ import print_function + +import os + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +import six + + +class ProcessLaunchTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.runCmd("settings set auto-confirm true") + + def tearDown(self): + self.runCmd("settings clear auto-confirm") + TestBase.tearDown(self) + + @not_remote_testsuite_ready + def test_io(self): + """Test that process launch I/O redirection flags work properly.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.expect("file " + exe, + patterns=["Current executable set to .*a.out"]) + + in_file = os.path.join(self.getSourceDir(), "input-file.txt") + out_file = lldbutil.append_to_process_working_directory(self, "output-test.out") + err_file = lldbutil.append_to_process_working_directory(self, "output-test.err") + + # Make sure the output files do not exist before launching the process + try: + os.remove(out_file) + except OSError: + pass + + try: + os.remove(err_file) + except OSError: + pass + + launch_command = "process launch -i '{0}' -o '{1}' -e '{2}' -w '{3}'".format( + in_file, out_file, err_file, self.get_process_working_directory()) + + if lldb.remote_platform: + self.runCmd('platform put-file "{local}" "{remote}"'.format( + local=in_file, remote=in_file)) + + self.expect(launch_command, + patterns=["Process .* launched: .*a.out"]) + + success = True + err_msg = "" + + out = lldbutil.read_file_on_target(self, out_file) + if out != "This should go to stdout.\n": + success = False + err_msg = err_msg + " ERROR: stdout file does not contain correct output.\n" + + + err = lldbutil.read_file_on_target(self, err_file) + if err != "This should go to stderr.\n": + success = False + err_msg = err_msg + " ERROR: stderr file does not contain correct output.\n" + + if not success: + self.fail(err_msg) + + # rdar://problem/9056462 + # The process launch flag '-w' for setting the current working directory + # not working? + @not_remote_testsuite_ready + @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr20265") + @expectedFailureNetBSD + def test_set_working_dir_nonexisting(self): + """Test that '-w dir' fails to set the working dir when running the inferior with a dir which doesn't exist.""" + d = {'CXX_SOURCES': 'print_cwd.cpp'} + self.build(dictionary=d) + self.setTearDownCleanup(d) + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe) + + mywd = 'my_working_dir' + out_file_name = "my_working_dir_test.out" + err_file_name = "my_working_dir_test.err" + + my_working_dir_path = self.getBuildArtifact(mywd) + out_file_path = os.path.join(my_working_dir_path, out_file_name) + err_file_path = os.path.join(my_working_dir_path, err_file_name) + + # Check that we get an error when we have a nonexisting path + invalid_dir_path = mywd + 'z' + launch_command = "process launch -w %s -o %s -e %s" % ( + invalid_dir_path, out_file_path, err_file_path) + + self.expect( + launch_command, error=True, patterns=[ + "error:.* No such file or directory: %s" % + invalid_dir_path]) + + @not_remote_testsuite_ready + def test_set_working_dir_existing(self): + """Test that '-w dir' sets the working dir when running the inferior.""" + d = {'CXX_SOURCES': 'print_cwd.cpp'} + self.build(dictionary=d) + self.setTearDownCleanup(d) + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe) + + mywd = 'my_working_dir' + out_file_name = "my_working_dir_test.out" + err_file_name = "my_working_dir_test.err" + + my_working_dir_path = self.getBuildArtifact(mywd) + lldbutil.mkdir_p(my_working_dir_path) + out_file_path = os.path.join(my_working_dir_path, out_file_name) + err_file_path = os.path.join(my_working_dir_path, err_file_name) + + # Make sure the output files do not exist before launching the process + try: + os.remove(out_file_path) + os.remove(err_file_path) + except OSError: + pass + + launch_command = "process launch -w %s -o %s -e %s" % ( + my_working_dir_path, out_file_path, err_file_path) + + self.expect(launch_command, + patterns=["Process .* launched: .*a.out"]) + + success = True + err_msg = "" + + # Check to see if the 'stdout' file was created + try: + out_f = open(out_file_path) + except IOError: + success = False + err_msg = err_msg + "ERROR: stdout file was not created.\n" + else: + # Check to see if the 'stdout' file contains the right output + line = out_f.readline() + if self.TraceOn(): + print("line:", line) + if not re.search(mywd, line): + success = False + err_msg = err_msg + "The current working directory was not set correctly.\n" + out_f.close() + + # Try to delete the 'stdout' and 'stderr' files + try: + os.remove(out_file_path) + os.remove(err_file_path) + except OSError: + pass + + if not success: + self.fail(err_msg) + + def test_environment_with_special_char(self): + """Test that environment variables containing '*' and '}' are handled correctly by the inferior.""" + source = 'print_env.cpp' + d = {'CXX_SOURCES': source} + self.build(dictionary=d) + self.setTearDownCleanup(d) + exe = self.getBuildArtifact("a.out") + + evil_var = 'INIT*MIDDLE}TAIL' + + target = self.dbg.CreateTarget(exe) + main_source_spec = lldb.SBFileSpec(source) + breakpoint = target.BreakpointCreateBySourceRegex( + '// Set breakpoint here.', main_source_spec) + + process = target.LaunchSimple(None, + ['EVIL=' + evil_var], + self.get_process_working_directory()) + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertEqual(len(threads), 1) + frame = threads[0].GetFrameAtIndex(0) + sbvalue = frame.EvaluateExpression("evil") + value = sbvalue.GetSummary().strip('"') + + self.assertEqual(value, evil_var) + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/input-file.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/input-file.txt new file mode 100644 index 00000000000..cc269ba0ff8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/input-file.txt @@ -0,0 +1,2 @@ +This should go to stdout. +This should go to stderr. diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/main.cpp new file mode 100644 index 00000000000..f2035d55167 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/main.cpp @@ -0,0 +1,17 @@ +#include <stdio.h> +#include <stdlib.h> + +int +main (int argc, char **argv) +{ + char buffer[1024]; + + fgets (buffer, sizeof (buffer), stdin); + fprintf (stdout, "%s", buffer); + + + fgets (buffer, sizeof (buffer), stdin); + fprintf (stderr, "%s", buffer); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/print_cwd.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/print_cwd.cpp new file mode 100644 index 00000000000..b4b073fbcb8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/print_cwd.cpp @@ -0,0 +1,21 @@ +#include <stdio.h> + +#ifdef _MSC_VER +#define _CRT_NONSTDC_NO_WARNINGS +#include <direct.h> +#undef getcwd +#define getcwd(buffer, length) _getcwd(buffer, length) +#else +#include <unistd.h> +#endif + +int +main (int argc, char **argv) +{ + char buffer[1024]; + + fprintf(stdout, "stdout: %s\n", getcwd(buffer, 1024)); + fprintf(stderr, "stderr: %s\n", getcwd(buffer, 1024)); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/print_env.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/print_env.cpp new file mode 100644 index 00000000000..8c6df8ea01a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/process/launch/print_env.cpp @@ -0,0 +1,10 @@ +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +int main (int argc, char **argv) +{ + char *evil = getenv("EVIL"); + + return 0; // Set breakpoint here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/quit/TestQuit.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/quit/TestQuit.py new file mode 100644 index 00000000000..d4dbd16869a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/quit/TestQuit.py @@ -0,0 +1,31 @@ +""" +Test lldb's quit command. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class QuitCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_quit_exit_code_disallow(self): + self.ci.AllowExitCodeOnQuit(False) + self.expect( + "quit 20", + substrs=[ + "error: The current driver doesn't allow custom exit codes for the quit command"], + error=True) + self.assertFalse(self.ci.HasCustomQuitExitCode()) + + @no_debug_info_test + def test_quit_exit_code_allow(self): + self.ci.AllowExitCodeOnQuit(True) + self.runCmd("quit 10", check=False) + self.assertTrue(self.ci.HasCustomQuitExitCode()) + self.assertEqual(self.ci.GetQuitStatus(), 10) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/Makefile new file mode 100644 index 00000000000..5cc7382f1d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +CFLAGS_EXTRAS := -mmpx -fcheck-pointer-bounds -fuse-ld=bfd + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/TestMPXRegisters.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/TestMPXRegisters.py new file mode 100644 index 00000000000..5644855868b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/TestMPXRegisters.py @@ -0,0 +1,61 @@ +""" +Test the Intel(R) MPX registers. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class RegisterCommandsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(compiler="clang") + @skipIf(oslist=no_match(['linux'])) + @skipIf(archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=["linux"], compiler="gcc", compiler_version=["<", "5"]) #GCC version >= 5 supports Intel(R) MPX. + def test_mpx_registers_with_example_code(self): + """Test Intel(R) MPX registers with example code.""" + self.build() + self.mpx_registers_with_example_code() + + def mpx_registers_with_example_code(self): + """Test Intel(R) MPX registers after running example code.""" + self.line = line_number('main.cpp', '// Set a break point here.') + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line, num_expected_locations=1) + self.runCmd("run", RUN_SUCCEEDED) + + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + if (process.GetState() == lldb.eStateExited): + self.skipTest("Intel(R) MPX is not supported.") + else: + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs = ["stop reason = breakpoint 1."]) + + if self.getArchitecture() == 'x86_64': + self.expect("register read -s 3", + substrs = ['bnd0 = {0x0000000000000010 0xffffffffffffffe6}', + 'bnd1 = {0x0000000000000020 0xffffffffffffffd6}', + 'bnd2 = {0x0000000000000030 0xffffffffffffffc6}', + 'bnd3 = {0x0000000000000040 0xffffffffffffffb6}', + 'bndcfgu = {0x01 0x80 0xb5 0x76 0xff 0x7f 0x00 0x00}', + 'bndstatus = {0x02 0x80 0xb5 0x76 0xff 0x7f 0x00 0x00}']) + if self.getArchitecture() == 'i386': + self.expect("register read -s 3", + substrs = ['bnd0 = {0x0000000000000010 0x00000000ffffffe6}', + 'bnd1 = {0x0000000000000020 0x00000000ffffffd6}', + 'bnd2 = {0x0000000000000030 0x00000000ffffffc6}', + 'bnd3 = {0x0000000000000040 0x00000000ffffffb6}', + 'bndcfgu = {0x01 0xd0 0x7d 0xf7 0x00 0x00 0x00 0x00}', + 'bndstatus = {0x02 0xd0 0x7d 0xf7 0x00 0x00 0x00 0x00}']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/main.cpp new file mode 100644 index 00000000000..97b50585a52 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/main.cpp @@ -0,0 +1,61 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +//// +//// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +//// See https://llvm.org/LICENSE.txt for license information. +//// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +//// +////===----------------------------------------------------------------------===// +// + +#include <cpuid.h> +#include <cstddef> + +int +main(int argc, char const *argv[]) +{ +// PR_MPX_ENABLE_MANAGEMENT won't be defined on linux kernel versions below 3.19 +#ifndef PR_MPX_ENABLE_MANAGEMENT + return -1; +#endif + + // This call returns 0 only if the CPU and the kernel support Intel(R) MPX. + if (prctl(PR_MPX_ENABLE_MANAGEMENT, 0, 0, 0, 0) != 0) + return -1; + +// Run Intel(R) MPX test code. +#if defined(__x86_64__) + asm("mov $16, %rax\n\t" + "mov $9, %rdx\n\t" + "bndmk (%rax,%rdx), %bnd0\n\t" + "mov $32, %rax\n\t" + "mov $9, %rdx\n\t" + "bndmk (%rax,%rdx), %bnd1\n\t" + "mov $48, %rax\n\t" + "mov $9, %rdx\n\t" + "bndmk (%rax,%rdx), %bnd2\n\t" + "mov $64, %rax\n\t" + "mov $9, %rdx\n\t" + "bndmk (%rax,%rdx), %bnd3\n\t" + "bndstx %bnd3, (%rax) \n\t" + "nop\n\t"); +#endif +#if defined(__i386__) + asm("mov $16, %eax\n\t" + "mov $9, %edx\n\t" + "bndmk (%eax,%edx), %bnd0\n\t" + "mov $32, %eax\n\t" + "mov $9, %edx\n\t" + "bndmk (%eax,%edx), %bnd1\n\t" + "mov $48, %eax\n\t" + "mov $9, %edx\n\t" + "bndmk (%eax,%edx), %bnd2\n\t" + "mov $64, %eax\n\t" + "mov $9, %edx\n\t" + "bndmk (%eax,%edx), %bnd3\n\t" + "bndstx %bnd3, (%eax)\n\t" + "nop\n\t"); +#endif + asm("nop\n\t"); // Set a break point here. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_bound_violation/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_bound_violation/Makefile new file mode 100644 index 00000000000..5cc7382f1d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_bound_violation/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +CFLAGS_EXTRAS := -mmpx -fcheck-pointer-bounds -fuse-ld=bfd + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_bound_violation/TestBoundViolation.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_bound_violation/TestBoundViolation.py new file mode 100644 index 00000000000..9a812a146b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_bound_violation/TestBoundViolation.py @@ -0,0 +1,52 @@ +""" +Test the Intel(R) MPX bound violation signal. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class RegisterCommandsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(compiler="clang") + @skipIf(oslist=no_match(['linux'])) + @skipIf(archs=no_match(['i386', 'x86_64'])) + @skipIf(oslist=["linux"], compiler="gcc", compiler_version=["<", "5"]) #GCC version >= 5 supports Intel(R) MPX. + def test_mpx_boundary_violation(self): + """Test Intel(R) MPX bound violation signal.""" + self.build() + self.mpx_boundary_violation() + + def mpx_boundary_violation(self): + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + if (process.GetState() == lldb.eStateExited): + self.skipTest("Intel(R) MPX is not supported.") + + if (process.GetState() == lldb.eStateStopped): + self.expect("thread backtrace", STOPPED_DUE_TO_SIGNAL, + substrs = ['stop reason = signal SIGSEGV: upper bound violation', + 'fault address:', 'lower bound:', 'upper bound:']) + + self.runCmd("continue") + + if (process.GetState() == lldb.eStateStopped): + self.expect("thread backtrace", STOPPED_DUE_TO_SIGNAL, + substrs = ['stop reason = signal SIGSEGV: lower bound violation', + 'fault address:', 'lower bound:', 'upper bound:']) + + self.runCmd("continue") + self.assertTrue(process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_bound_violation/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_bound_violation/main.cpp new file mode 100644 index 00000000000..3c5ef07e4b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_bound_violation/main.cpp @@ -0,0 +1,44 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +//// +//// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +//// See https://llvm.org/LICENSE.txt for license information. +//// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +//// +////===----------------------------------------------------------------------===// +// + +#include <cstddef> +#include <sys/prctl.h> + +static void violate_upper_bound(int *ptr, int size) +{ + int i; + i = *(ptr + size); +} + +static void violate_lower_bound (int *ptr, int size) +{ + int i; + i = *(ptr - size); +} + +int +main(int argc, char const *argv[]) +{ + unsigned int rax, rbx, rcx, rdx; + int array[5]; + +// PR_MPX_ENABLE_MANAGEMENT won't be defined on linux kernel versions below 3.19 +#ifndef PR_MPX_ENABLE_MANAGEMENT + return -1; +#endif + + // This call returns 0 only if the CPU and the kernel support Intel(R) MPX. + if (prctl(PR_MPX_ENABLE_MANAGEMENT, 0, 0, 0, 0) != 0) + return -1; + + violate_upper_bound(array, 5); + violate_lower_bound(array, 5); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_offset_intersection/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_offset_intersection/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_offset_intersection/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_offset_intersection/TestMPXOffsetIntersection.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_offset_intersection/TestMPXOffsetIntersection.py new file mode 100644 index 00000000000..109e8e93404 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_offset_intersection/TestMPXOffsetIntersection.py @@ -0,0 +1,69 @@ +""" +Test Intel(R) MPX registers do not get overwritten by AVX data. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class MPXOffsetIntersectionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + AVX_REGS = ('ymm' + str(i) for i in range(16)) + YMM_VALUE = '{' + ' '.join(('0x00' for _ in range(32))) + '}' + + MPX_REGULAR_REGS = ('bnd0', 'bnd1', 'bnd2', 'bnd3') + MPX_CONFIG_REGS = ('bndcfgu', 'bndstatus') + BND_VALUE = '{' + ' '.join(('0xff' for _ in range(16))) + '}' + + @skipIf(oslist=no_match(['linux'])) + @skipIf(archs=no_match(['x86_64'])) + def test_mpx_registers_offset_intersection(self): + """Test if AVX data does not overwrite MPX values.""" + self.build() + self.mpx_registers_offset_intersection() + + def mpx_registers_offset_intersection(self): + exe = self.getBuildArtifact('a.out') + self.runCmd('file ' + exe, CURRENT_EXECUTABLE_SET) + self.runCmd('run', RUN_SUCCEEDED) + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + thread = process.GetThreadAtIndex(0) + currentFrame = thread.GetFrameAtIndex(0) + + has_avx = False + has_mpx = False + for registerSet in currentFrame.GetRegisters(): + if 'advanced vector extensions' in registerSet.GetName().lower(): + has_avx = True + if 'memory protection extension' in registerSet.GetName().lower(): + has_mpx = True + if not (has_avx and has_mpx): + self.skipTest('Both AVX and MPX registers must be supported.') + + for reg in self.AVX_REGS: + self.runCmd('register write ' + reg + " '" + self.YMM_VALUE + " '") + for reg in self.MPX_REGULAR_REGS + self.MPX_CONFIG_REGS: + self.runCmd('register write ' + reg + " '" + self.BND_VALUE + " '") + + self.verify_mpx() + self.verify_avx() + self.verify_mpx() + + def verify_mpx(self): + for reg in self.MPX_REGULAR_REGS: + self.expect('register read ' + reg, + substrs = [reg + ' = {0xffffffffffffffff 0xffffffffffffffff}']) + for reg in self.MPX_CONFIG_REGS: + self.expect('register read ' + reg, + substrs = [reg + ' = {0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff}']) + + def verify_avx(self): + for reg in self.AVX_REGS: + self.expect('register read ' + reg, substrs = [reg + ' = ' + self.YMM_VALUE]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_offset_intersection/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_offset_intersection/main.cpp new file mode 100644 index 00000000000..0285cfdaad0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/intel_xtended_registers/mpx_offset_intersection/main.cpp @@ -0,0 +1,6 @@ +#include <cstdint> + +int main() { + asm volatile("int3"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/Makefile new file mode 100644 index 00000000000..d2bc2ba44a0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp a.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/TestRegisters.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/TestRegisters.py new file mode 100644 index 00000000000..01d2367c855 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/TestRegisters.py @@ -0,0 +1,502 @@ +""" +Test the 'register' command. +""" + +from __future__ import print_function + + +import os +import sys +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class RegisterCommandsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + TestBase.setUp(self) + self.has_teardown = False + + def tearDown(self): + self.dbg.GetSelectedTarget().GetProcess().Destroy() + TestBase.tearDown(self) + + @skipIfiOSSimulator + @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) + @expectedFailureNetBSD + def test_register_commands(self): + """Test commands related to registers, in particular vector registers.""" + self.build() + self.common_setup() + + # verify that logging does not assert + self.log_enable("registers") + + self.expect("register read -a", MISSING_EXPECTED_REGISTERS, + substrs=['registers were unavailable'], matching=False) + + if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: + self.runCmd("register read xmm0") + self.runCmd("register read ymm15") # may be available + self.runCmd("register read bnd0") # may be available + elif self.getArchitecture() in ['arm', 'armv7', 'armv7k', 'arm64', 'arm64e', 'arm64_32']: + self.runCmd("register read s0") + self.runCmd("register read q15") # may be available + + self.expect( + "register read -s 4", + substrs=['invalid register set index: 4'], + error=True) + + @skipIfiOSSimulator + # Writing of mxcsr register fails, presumably due to a kernel/hardware + # problem + @skipIfTargetAndroid(archs=["i386"]) + @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37995") + def test_fp_register_write(self): + """Test commands that write to registers, in particular floating-point registers.""" + self.build() + self.fp_register_write() + + @skipIfiOSSimulator + # "register read fstat" always return 0xffff + @expectedFailureAndroid(archs=["i386"]) + @skipIfFreeBSD # llvm.org/pr25057 + @skipIf(archs=no_match(['amd64', 'i386', 'x86_64'])) + @skipIfOutOfTreeDebugserver + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37995") + @expectedFailureNetBSD + def test_fp_special_purpose_register_read(self): + """Test commands that read fpu special purpose registers.""" + self.build() + self.fp_special_purpose_register_read() + + @skipIfiOSSimulator + @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37683") + def test_register_expressions(self): + """Test expression evaluation with commands related to registers.""" + self.build() + self.common_setup() + + if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: + gpr = "eax" + vector = "xmm0" + elif self.getArchitecture() in ['arm64', 'aarch64', 'arm64e', 'arm64_32']: + gpr = "w0" + vector = "v0" + elif self.getArchitecture() in ['arm', 'armv7', 'armv7k']: + gpr = "r0" + vector = "q0" + + self.expect("expr/x $%s" % gpr, substrs=['unsigned int', ' = 0x']) + self.expect("expr $%s" % vector, substrs=['vector_type']) + self.expect( + "expr (unsigned int)$%s[0]" % + vector, substrs=['unsigned int']) + + if self.getArchitecture() in ['amd64', 'x86_64']: + self.expect( + "expr -- ($rax & 0xffffffff) == $eax", + substrs=['true']) + + @skipIfiOSSimulator + @skipIf(archs=no_match(['amd64', 'x86_64'])) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37683") + def test_convenience_registers(self): + """Test convenience registers.""" + self.build() + self.convenience_registers() + + @skipIfiOSSimulator + @skipIf(archs=no_match(['amd64', 'x86_64'])) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37683") + @expectedFailureNetBSD + def test_convenience_registers_with_process_attach(self): + """Test convenience registers after a 'process attach'.""" + self.build() + self.convenience_registers_with_process_attach(test_16bit_regs=False) + + @skipIfiOSSimulator + @skipIf(archs=no_match(['amd64', 'x86_64'])) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37683") + @expectedFailureNetBSD + def test_convenience_registers_16bit_with_process_attach(self): + """Test convenience registers after a 'process attach'.""" + self.build() + self.convenience_registers_with_process_attach(test_16bit_regs=True) + + def common_setup(self): + exe = self.getBuildArtifact("a.out") + + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break in main(). + lldbutil.run_break_set_by_symbol( + self, "main", num_expected_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=['stopped', 'stop reason = breakpoint']) + + # platform specific logging of the specified category + def log_enable(self, category): + # This intentionally checks the host platform rather than the target + # platform as logging is host side. + self.platform = "" + if (sys.platform.startswith("freebsd") or + sys.platform.startswith("linux") or + sys.platform.startswith("netbsd")): + self.platform = "posix" + + if self.platform != "": + self.log_file = self.getBuildArtifact('TestRegisters.log') + self.runCmd( + "log enable " + + self.platform + + " " + + str(category) + + " registers -v -f " + + self.log_file, + RUN_SUCCEEDED) + if not self.has_teardown: + def remove_log(self): + if os.path.exists(self.log_file): + os.remove(self.log_file) + self.has_teardown = True + self.addTearDownHook(remove_log) + + def write_and_read(self, frame, register, new_value, must_exist=True): + value = frame.FindValue(register, lldb.eValueTypeRegister) + if must_exist: + self.assertTrue( + value.IsValid(), + "finding a value for register " + + register) + elif not value.IsValid(): + return # If register doesn't exist, skip this test + + # Also test the 're' alias. + self.runCmd("re write " + register + " \'" + new_value + "\'") + self.expect( + "register read " + + register, + substrs=[ + register + + ' = ', + new_value]) + + def fp_special_purpose_register_read(self): + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Launch the process and stop. + self.expect("run", PROCESS_STOPPED, substrs=['stopped']) + + # Check stop reason; Should be either signal SIGTRAP or EXC_BREAKPOINT + output = self.res.GetOutput() + matched = False + substrs = [ + 'stop reason = EXC_BREAKPOINT', + 'stop reason = signal SIGTRAP'] + for str1 in substrs: + matched = output.find(str1) != -1 + with recording(self, False) as sbuf: + print("%s sub string: %s" % ('Expecting', str1), file=sbuf) + print("Matched" if matched else "Not Matched", file=sbuf) + if matched: + break + self.assertTrue(matched, STOPPED_DUE_TO_SIGNAL) + + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + thread = process.GetThreadAtIndex(0) + self.assertTrue(thread.IsValid(), "current thread is valid") + + currentFrame = thread.GetFrameAtIndex(0) + self.assertTrue(currentFrame.IsValid(), "current frame is valid") + + # Extract the value of fstat and ftag flag at the point just before + # we start pushing floating point values on st% register stack + value = currentFrame.FindValue("fstat", lldb.eValueTypeRegister) + error = lldb.SBError() + reg_value_fstat_initial = value.GetValueAsUnsigned(error, 0) + + self.assertTrue(error.Success(), "reading a value for fstat") + value = currentFrame.FindValue("ftag", lldb.eValueTypeRegister) + error = lldb.SBError() + reg_value_ftag_initial = value.GetValueAsUnsigned(error, 0) + + self.assertTrue(error.Success(), "reading a value for ftag") + fstat_top_pointer_initial = (reg_value_fstat_initial & 0x3800) >> 11 + + # Execute 'si' aka 'thread step-inst' instruction 5 times and with + # every execution verify the value of fstat and ftag registers + for x in range(0, 5): + # step into the next instruction to push a value on 'st' register + # stack + self.runCmd("si", RUN_SUCCEEDED) + + # Verify fstat and save it to be used for verification in next + # execution of 'si' command + if not (reg_value_fstat_initial & 0x3800): + self.expect("register read fstat", substrs=[ + 'fstat' + ' = ', str("0x%0.4x" % ((reg_value_fstat_initial & ~(0x3800)) | 0x3800))]) + reg_value_fstat_initial = ( + (reg_value_fstat_initial & ~(0x3800)) | 0x3800) + fstat_top_pointer_initial = 7 + else: + self.expect("register read fstat", substrs=[ + 'fstat' + ' = ', str("0x%0.4x" % (reg_value_fstat_initial - 0x0800))]) + reg_value_fstat_initial = (reg_value_fstat_initial - 0x0800) + fstat_top_pointer_initial -= 1 + + # Verify ftag and save it to be used for verification in next + # execution of 'si' command + self.expect( + "register read ftag", substrs=[ + 'ftag' + ' = ', str( + "0x%0.4x" % + (reg_value_ftag_initial | ( + 1 << fstat_top_pointer_initial)))]) + reg_value_ftag_initial = reg_value_ftag_initial | ( + 1 << fstat_top_pointer_initial) + + def fp_register_write(self): + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Launch the process, stop at the entry point. + error = lldb.SBError() + process = target.Launch( + lldb.SBListener(), + None, None, # argv, envp + None, None, None, # stdin/out/err + self.get_process_working_directory(), + 0, # launch flags + True, # stop at entry + error) + self.assertTrue(error.Success(), "Launch succeeds. Error is :" + str(error)) + + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + thread = process.GetThreadAtIndex(0) + self.assertTrue(thread.IsValid(), "current thread is valid") + + currentFrame = thread.GetFrameAtIndex(0) + self.assertTrue(currentFrame.IsValid(), "current frame is valid") + + if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: + reg_list = [ + # reg value must-have + ("fcw", "0x0000ff0e", False), + ("fsw", "0x0000ff0e", False), + ("ftw", "0x0000ff0e", False), + ("ip", "0x0000ff0e", False), + ("dp", "0x0000ff0e", False), + ("mxcsr", "0x0000ff0e", False), + ("mxcsrmask", "0x0000ff0e", False), + ] + + st0regname = None + if currentFrame.FindRegister("st0").IsValid(): + st0regname = "st0" + elif currentFrame.FindRegister("stmm0").IsValid(): + st0regname = "stmm0" + if st0regname is not None: + # reg value + # must-have + reg_list.append( + (st0regname, "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00}", True)) + reg_list.append( + ("xmm0", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", + True)) + reg_list.append( + ("xmm15", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False)) + elif self.getArchitecture() in ['arm64', 'aarch64', 'arm64e', 'arm64_32']: + reg_list = [ + # reg value + # must-have + ("fpsr", "0xfbf79f9f", True), + ("s0", "1.25", True), + ("s31", "0.75", True), + ("d1", "123", True), + ("d17", "987", False), + ("v1", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True), + ("v14", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False), + ] + elif self.getArchitecture() in ['armv7'] and self.platformIsDarwin(): + reg_list = [ + # reg value + # must-have + ("fpsr", "0xfbf79f9f", True), + ("s0", "1.25", True), + ("s31", "0.75", True), + ("d1", "123", True), + ("d17", "987", False), + ("q1", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True), + ("q14", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False), + ] + elif self.getArchitecture() in ['arm', 'armv7k']: + reg_list = [ + # reg value + # must-have + ("fpscr", "0xfbf79f9f", True), + ("s0", "1.25", True), + ("s31", "0.75", True), + ("d1", "123", True), + ("d17", "987", False), + ("q1", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True), + ("q14", + "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", + False), + ] + + for (reg, val, must) in reg_list: + self.write_and_read(currentFrame, reg, val, must) + + if self.getArchitecture() in ['amd64', 'i386', 'x86_64']: + if st0regname is None: + self.fail("st0regname could not be determined") + self.runCmd( + "register write " + + st0regname + + " \"{0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00}\"") + self.expect( + "register read " + + st0regname + + " --format f", + substrs=[ + st0regname + + ' = 0']) + + has_avx = False + has_mpx = False + # Returns an SBValueList. + registerSets = currentFrame.GetRegisters() + for registerSet in registerSets: + if 'advanced vector extensions' in registerSet.GetName().lower(): + has_avx = True + if 'memory protection extension' in registerSet.GetName().lower(): + has_mpx = True + + if has_avx: + new_value = "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x0c 0x0d 0x0e 0x0f}" + self.write_and_read(currentFrame, "ymm0", new_value) + self.write_and_read(currentFrame, "ymm7", new_value) + self.expect("expr $ymm0", substrs=['vector_type']) + else: + self.runCmd("register read ymm0") + + if has_mpx: + # Test write and read for bnd0. + new_value_w = "{0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0a 0x0b 0x0c 0x0d 0x0e 0x0f 0x10}" + self.runCmd("register write bnd0 \'" + new_value_w + "\'") + new_value_r = "{0x0807060504030201 0x100f0e0d0c0b0a09}" + self.expect("register read bnd0", substrs = ['bnd0 = ', new_value_r]) + self.expect("expr $bnd0", substrs = ['vector_type']) + + # Test write and for bndstatus. + new_value = "{0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08}" + self.write_and_read(currentFrame, "bndstatus", new_value) + self.expect("expr $bndstatus", substrs = ['vector_type']) + else: + self.runCmd("register read bnd0") + + def convenience_registers(self): + """Test convenience registers.""" + self.common_setup() + + # The command "register read -a" does output a derived register like + # eax... + self.expect("register read -a", matching=True, + substrs=['eax']) + + # ...however, the vanilla "register read" command should not output derived registers like eax. + self.expect("register read", matching=False, + substrs=['eax']) + + # Test reading of rax and eax. + self.expect("register read rax eax", + substrs=['rax = 0x', 'eax = 0x']) + + # Now write rax with a unique bit pattern and test that eax indeed + # represents the lower half of rax. + self.runCmd("register write rax 0x1234567887654321") + self.expect("register read rax 0x1234567887654321", + substrs=['0x1234567887654321']) + + def convenience_registers_with_process_attach(self, test_16bit_regs): + """Test convenience registers after a 'process attach'.""" + exe = self.getBuildArtifact("a.out") + + # Spawn a new process + pid = self.spawnSubprocess(exe, ['wait_for_attach']).pid + self.addTearDownHook(self.cleanupSubprocesses) + + if self.TraceOn(): + print("pid of spawned process: %d" % pid) + + self.runCmd("process attach -p %d" % pid) + + # Check that "register read eax" works. + self.runCmd("register read eax") + + if self.getArchitecture() in ['amd64', 'x86_64']: + self.expect("expr -- ($rax & 0xffffffff) == $eax", + substrs=['true']) + + if test_16bit_regs: + self.expect("expr -- $ax == (($ah << 8) | $al)", + substrs=['true']) + + @skipIfiOSSimulator + @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) + def test_invalid_invocation(self): + self.build() + self.common_setup() + + self.expect("register read -a arg", error=True, + substrs=["the --all option can't be used when registers names are supplied as arguments"]) + + self.expect("register read --set 0 r", error=True, + substrs=["the --set <set> option can't be used when registers names are supplied as arguments"]) + + self.expect("register write a", error=True, + substrs=["register write takes exactly 2 arguments: <reg-name> <value>"]) + self.expect("register write a b c", error=True, + substrs=["register write takes exactly 2 arguments: <reg-name> <value>"]) + + @skipIfiOSSimulator + @skipIf(archs=no_match(['amd64', 'arm', 'i386', 'x86_64'])) + def test_write_unknown_register(self): + self.build() + self.common_setup() + + self.expect("register write blub 1", error=True, + substrs=["error: Register not found for 'blub'."]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/a.cpp new file mode 100644 index 00000000000..79f111aa247 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/a.cpp @@ -0,0 +1,43 @@ +//===-- a.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +long double +return_long_double (long double value) +{ +#if defined (__i386__) || defined (__x86_64__) + float a=2, b=4,c=8, d=16, e=32, f=64, k=128, l=256, add=0; + __asm__ ( + "int3 ;" + "flds %1 ;" + "flds %2 ;" + "flds %3 ;" + "flds %4 ;" + "flds %5 ;" + "flds %6 ;" + "flds %7 ;" + "faddp ;" : "=g" (add) : "g" (a), "g" (b), "g" (c), "g" (d), "g" (e), "g" (f), "g" (k), "g" (l) ); // Set break point at this line. +#endif // #if defined (__i386__) || defined (__x86_64__) + return value; +} + +long double +outer_return_long_double (long double value) +{ + long double val = return_long_double(value); + val *= 2 ; + return val; +} + +long double +outermost_return_long_double (long double value) +{ + long double val = outer_return_long_double(value); + val *= 2 ; + return val; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/main.cpp new file mode 100644 index 00000000000..493a09e034d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/register/register/register_command/main.cpp @@ -0,0 +1,35 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +#include <chrono> +#include <thread> + +long double outermost_return_long_double (long double my_long_double); + +int main (int argc, char const *argv[]) +{ + lldb_enable_attach(); + + char my_string[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 0}; + double my_double = 1234.5678; + long double my_long_double = 1234.5678; + + // For simplicity assume that any cmdline argument means wait for attach. + if (argc > 1) + { + volatile int wait_for_attach=1; + while (wait_for_attach) + std::this_thread::sleep_for(std::chrono::microseconds(1)); + } + + printf("my_string=%s\n", my_string); + printf("my_double=%g\n", my_double); + outermost_return_long_double (my_long_double); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/reproducer/invalid-args/TestInvalidArgsReproducer.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/reproducer/invalid-args/TestInvalidArgsReproducer.py new file mode 100644 index 00000000000..74db2fc7756 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/reproducer/invalid-args/TestInvalidArgsReproducer.py @@ -0,0 +1,17 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +class ReproducerTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_reproducer_generate_invalid_invocation(self): + self.expect("reproducer generate f", error=True, + substrs=["'reproducer generate' takes no arguments"]) + + @no_debug_info_test + def test_reproducer_status_invalid_invocation(self): + self.expect("reproducer status f", error=True, + substrs=["'reproducer status' takes no arguments"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/TestSettings.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/TestSettings.py new file mode 100644 index 00000000000..1130821bac0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/TestSettings.py @@ -0,0 +1,604 @@ +""" +Test lldb settings command. +""" + + + +import os +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SettingsCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_apropos_should_also_search_settings_description(self): + """Test that 'apropos' command should also search descriptions for the settings variables.""" + + self.expect("apropos 'environment variable'", + substrs=["target.env-vars", + "environment variables", + "executable's environment"]) + + def test_append_target_env_vars(self): + """Test that 'append target.run-args' works.""" + # Append the env-vars. + self.runCmd('settings append target.env-vars MY_ENV_VAR=YES') + # And add hooks to restore the settings during tearDown(). + self.addTearDownHook( + lambda: self.runCmd("settings clear target.env-vars")) + + # Check it immediately! + self.expect('settings show target.env-vars', + substrs=['MY_ENV_VAR=YES']) + + def test_insert_before_and_after_target_run_args(self): + """Test that 'insert-before/after target.run-args' works.""" + # Set the run-args first. + self.runCmd('settings set target.run-args a b c') + # And add hooks to restore the settings during tearDown(). + self.addTearDownHook( + lambda: self.runCmd("settings clear target.run-args")) + + # Now insert-before the index-0 element with '__a__'. + self.runCmd('settings insert-before target.run-args 0 __a__') + # And insert-after the index-1 element with '__A__'. + self.runCmd('settings insert-after target.run-args 1 __A__') + # Check it immediately! + self.expect('settings show target.run-args', + substrs=['target.run-args', + '[0]: "__a__"', + '[1]: "a"', + '[2]: "__A__"', + '[3]: "b"', + '[4]: "c"']) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr44430") + def test_replace_target_run_args(self): + """Test that 'replace target.run-args' works.""" + # Set the run-args and then replace the index-0 element. + self.runCmd('settings set target.run-args a b c') + # And add hooks to restore the settings during tearDown(). + self.addTearDownHook( + lambda: self.runCmd("settings clear target.run-args")) + + # Now replace the index-0 element with 'A', instead. + self.runCmd('settings replace target.run-args 0 A') + # Check it immediately! + self.expect('settings show target.run-args', + substrs=['target.run-args (arguments) =', + '[0]: "A"', + '[1]: "b"', + '[2]: "c"']) + + def test_set_prompt(self): + """Test that 'set prompt' actually changes the prompt.""" + + # Set prompt to 'lldb2'. + self.runCmd("settings set prompt 'lldb2 '") + + # Immediately test the setting. + self.expect("settings show prompt", SETTING_MSG("prompt"), + startstr='prompt (string) = "lldb2 "') + + # The overall display should also reflect the new setting. + self.expect("settings show", SETTING_MSG("prompt"), + substrs=['prompt (string) = "lldb2 "']) + + # Use '-r' option to reset to the original default prompt. + self.runCmd("settings clear prompt") + + def test_set_term_width(self): + """Test that 'set term-width' actually changes the term-width.""" + + self.runCmd("settings set term-width 70") + + # Immediately test the setting. + self.expect("settings show term-width", SETTING_MSG("term-width"), + startstr="term-width (int) = 70") + + # The overall display should also reflect the new setting. + self.expect("settings show", SETTING_MSG("term-width"), + substrs=["term-width (int) = 70"]) + + # rdar://problem/10712130 + @skipIf(oslist=["windows"], bugnumber="llvm.org/pr44431") + def test_set_frame_format(self): + """Test that 'set frame-format' with a backtick char in the format string works as well as fullpath.""" + self.build() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + def cleanup(): + self.runCmd( + "settings set frame-format %s" % + self.format_string, check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("settings show frame-format") + m = re.match( + '^frame-format \(format-string\) = "(.*)\"$', + self.res.GetOutput()) + self.assertTrue(m, "Bad settings string") + self.format_string = m.group(1) + + # Change the default format to print function.name rather than + # function.name-with-args + format_string = "frame #${frame.index}: ${frame.pc}{ ${module.file.basename}\`${function.name}{${function.pc-offset}}}{ at ${line.file.fullpath}:${line.number}}{, lang=${language}}\n" + self.runCmd("settings set frame-format %s" % format_string) + + # Immediately test the setting. + self.expect("settings show frame-format", SETTING_MSG("frame-format"), + substrs=[format_string]) + + self.runCmd("breakpoint set -n main") + self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()), + RUN_SUCCEEDED) + self.expect("thread backtrace", + substrs=["`main", self.getSourceDir()]) + + def test_set_auto_confirm(self): + """Test that after 'set auto-confirm true', manual confirmation should not kick in.""" + self.build() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("settings set auto-confirm true") + + # Immediately test the setting. + self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"), + startstr="auto-confirm (boolean) = true") + + # Now 'breakpoint delete' should just work fine without confirmation + # prompt from the command interpreter. + self.runCmd("breakpoint set -n main") + self.expect("breakpoint delete", + startstr="All breakpoints removed") + + # Restore the original setting of auto-confirm. + self.runCmd("settings clear auto-confirm") + self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"), + startstr="auto-confirm (boolean) = false") + + @skipIf(archs=no_match(['x86_64', 'i386', 'i686'])) + def test_disassembler_settings(self): + """Test that user options for the disassembler take effect.""" + self.build() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # AT&T syntax + self.runCmd("settings set target.x86-disassembly-flavor att") + self.runCmd("settings set target.use-hex-immediates false") + self.expect("disassemble -n numberfn", + substrs=["$90"]) + self.runCmd("settings set target.use-hex-immediates true") + self.runCmd("settings set target.hex-immediate-style c") + self.expect("disassemble -n numberfn", + substrs=["$0x5a"]) + self.runCmd("settings set target.hex-immediate-style asm") + self.expect("disassemble -n numberfn", + substrs=["$5ah"]) + + # Intel syntax + self.runCmd("settings set target.x86-disassembly-flavor intel") + self.runCmd("settings set target.use-hex-immediates false") + self.expect("disassemble -n numberfn", + substrs=["90"]) + self.runCmd("settings set target.use-hex-immediates true") + self.runCmd("settings set target.hex-immediate-style c") + self.expect("disassemble -n numberfn", + substrs=["0x5a"]) + self.runCmd("settings set target.hex-immediate-style asm") + self.expect("disassemble -n numberfn", + substrs=["5ah"]) + + @skipIfDarwinEmbedded # <rdar://problem/34446098> debugserver on ios etc can't write files + def test_run_args_and_env_vars(self): + """Test that run-args and env-vars are passed to the launched process.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Set the run-args and the env-vars. + # And add hooks to restore the settings during tearDown(). + self.runCmd('settings set target.run-args A B C') + self.addTearDownHook( + lambda: self.runCmd("settings clear target.run-args")) + self.runCmd('settings set target.env-vars ["MY_ENV_VAR"]=YES') + self.addTearDownHook( + lambda: self.runCmd("settings clear target.env-vars")) + + self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()), + RUN_SUCCEEDED) + + # Read the output file produced by running the program. + output = lldbutil.read_file_from_process_wd(self, "output2.txt") + + self.expect( + output, + exe=False, + substrs=[ + "argv[1] matches", + "argv[2] matches", + "argv[3] matches", + "Environment variable 'MY_ENV_VAR' successfully passed."]) + + @skipIfRemote # it doesn't make sense to send host env to remote target + def test_pass_host_env_vars(self): + """Test that the host env vars are passed to the launched process.""" + self.build() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # By default, inherit-env is 'true'. + self.expect( + 'settings show target.inherit-env', + "Default inherit-env is 'true'", + startstr="target.inherit-env (boolean) = true") + + # Set some host environment variables now. + os.environ["MY_HOST_ENV_VAR1"] = "VAR1" + os.environ["MY_HOST_ENV_VAR2"] = "VAR2" + + # This is the function to unset the two env variables set above. + def unset_env_variables(): + os.environ.pop("MY_HOST_ENV_VAR1") + os.environ.pop("MY_HOST_ENV_VAR2") + + self.addTearDownHook(unset_env_variables) + self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()), + RUN_SUCCEEDED) + + # Read the output file produced by running the program. + output = lldbutil.read_file_from_process_wd(self, "output1.txt") + + self.expect( + output, + exe=False, + substrs=[ + "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.", + "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."]) + + @skipIfDarwinEmbedded # <rdar://problem/34446098> debugserver on ios etc can't write files + def test_set_error_output_path(self): + """Test that setting target.error/output-path for the launched process works.""" + self.build() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Set the error-path and output-path and verify both are set. + self.runCmd("settings set target.error-path '{0}'".format( + lldbutil.append_to_process_working_directory(self, "stderr.txt"))) + self.runCmd("settings set target.output-path '{0}".format( + lldbutil.append_to_process_working_directory(self, "stdout.txt"))) + # And add hooks to restore the original settings during tearDown(). + self.addTearDownHook( + lambda: self.runCmd("settings clear target.output-path")) + self.addTearDownHook( + lambda: self.runCmd("settings clear target.error-path")) + + self.expect("settings show target.error-path", + SETTING_MSG("target.error-path"), + substrs=['target.error-path (file)', 'stderr.txt"']) + + self.expect("settings show target.output-path", + SETTING_MSG("target.output-path"), + substrs=['target.output-path (file)', 'stdout.txt"']) + + self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()), + RUN_SUCCEEDED) + + output = lldbutil.read_file_from_process_wd(self, "stderr.txt") + message = "This message should go to standard error." + if lldbplatformutil.hasChattyStderr(self): + self.expect(output, exe=False, substrs=[message]) + else: + self.expect(output, exe=False, startstr=message) + + output = lldbutil.read_file_from_process_wd(self, "stdout.txt") + self.expect(output, exe=False, + startstr="This message should go to standard out.") + + def test_print_dictionary_setting(self): + self.runCmd("settings clear target.env-vars") + self.runCmd("settings set target.env-vars [\"MY_VAR\"]=some-value") + self.expect("settings show target.env-vars", + substrs=["MY_VAR=some-value"]) + self.runCmd("settings clear target.env-vars") + + def test_print_array_setting(self): + self.runCmd("settings clear target.run-args") + self.runCmd("settings set target.run-args gobbledy-gook") + self.expect("settings show target.run-args", + substrs=['[0]: "gobbledy-gook"']) + self.runCmd("settings clear target.run-args") + + def test_settings_with_quotes(self): + self.runCmd("settings clear target.run-args") + self.runCmd("settings set target.run-args a b c") + self.expect("settings show target.run-args", + substrs=['[0]: "a"', + '[1]: "b"', + '[2]: "c"']) + self.runCmd("settings set target.run-args 'a b c'") + self.expect("settings show target.run-args", + substrs=['[0]: "a b c"']) + self.runCmd("settings clear target.run-args") + self.runCmd("settings clear target.env-vars") + self.runCmd( + 'settings set target.env-vars ["MY_FILE"]="this is a file name with spaces.txt"') + self.expect("settings show target.env-vars", + substrs=['MY_FILE=this is a file name with spaces.txt']) + self.runCmd("settings clear target.env-vars") + # Test and make sure that setting "format-string" settings obeys quotes + # if they are provided + self.runCmd("settings set thread-format 'abc def' ") + self.expect("settings show thread-format", + 'thread-format (format-string) = "abc def"') + self.runCmd('settings set thread-format "abc def" ') + self.expect("settings show thread-format", + 'thread-format (format-string) = "abc def"') + # Make sure when no quotes are provided that we maintain any trailing + # spaces + self.runCmd('settings set thread-format abc def ') + self.expect("settings show thread-format", + 'thread-format (format-string) = "abc def "') + self.runCmd('settings clear thread-format') + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr44430") + def test_settings_with_trailing_whitespace(self): + + # boolean + # Set to known value + self.runCmd("settings set target.skip-prologue true") + # Set to new value with trailing whitespace + self.runCmd("settings set target.skip-prologue false ") + # Make sure the setting was correctly set to "false" + self.expect( + "settings show target.skip-prologue", + SETTING_MSG("target.skip-prologue"), + startstr="target.skip-prologue (boolean) = false") + self.runCmd("settings clear target.skip-prologue", check=False) + # integer + self.runCmd("settings set term-width 70") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set term-width 60 \t") + self.expect("settings show term-width", SETTING_MSG("term-width"), + startstr="term-width (int) = 60") + self.runCmd("settings clear term-width", check=False) + # string + self.runCmd("settings set target.arg0 abc") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set target.arg0 cde\t ") + self.expect("settings show target.arg0", SETTING_MSG("target.arg0"), + startstr='target.arg0 (string) = "cde"') + self.runCmd("settings clear target.arg0", check=False) + # file + path1 = self.getBuildArtifact("path1.txt") + path2 = self.getBuildArtifact("path2.txt") + self.runCmd( + "settings set target.output-path %s" % + path1) # Set to known value + self.expect( + "settings show target.output-path", + SETTING_MSG("target.output-path"), + startstr='target.output-path (file) = ', + substrs=[path1]) + self.runCmd("settings set target.output-path %s " % + path2) # Set to new value with trailing whitespaces + self.expect( + "settings show target.output-path", + SETTING_MSG("target.output-path"), + startstr='target.output-path (file) = ', + substrs=[path2]) + self.runCmd("settings clear target.output-path", check=False) + # enum + # Set to known value + self.runCmd("settings set stop-disassembly-display never") + # Set to new value with trailing whitespaces + self.runCmd("settings set stop-disassembly-display always ") + self.expect( + "settings show stop-disassembly-display", + SETTING_MSG("stop-disassembly-display"), + startstr='stop-disassembly-display (enum) = always') + self.runCmd("settings clear stop-disassembly-display", check=False) + # language + # Set to known value + self.runCmd("settings set target.language c89") + # Set to new value with trailing whitespace + self.runCmd("settings set target.language c11 ") + self.expect( + "settings show target.language", + SETTING_MSG("target.language"), + startstr="target.language (language) = c11") + self.runCmd("settings clear target.language", check=False) + # arguments + self.runCmd("settings set target.run-args 1 2 3") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set target.run-args 3 4 5 ") + self.expect( + "settings show target.run-args", + SETTING_MSG("target.run-args"), + substrs=[ + 'target.run-args (arguments) =', + '[0]: "3"', + '[1]: "4"', + '[2]: "5"']) + self.runCmd("settings set target.run-args 1 2 3") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set target.run-args 3 \ \ ") + self.expect( + "settings show target.run-args", + SETTING_MSG("target.run-args"), + substrs=[ + 'target.run-args (arguments) =', + '[0]: "3"', + '[1]: " "', + '[2]: " "']) + self.runCmd("settings clear target.run-args", check=False) + # dictionaries + self.runCmd("settings clear target.env-vars") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set target.env-vars A=B C=D\t ") + self.expect( + "settings show target.env-vars", + SETTING_MSG("target.env-vars"), + substrs=[ + 'target.env-vars (dictionary of strings) =', + 'A=B', + 'C=D']) + self.runCmd("settings clear target.env-vars", check=False) + # regex + # Set to known value + self.runCmd("settings clear target.process.thread.step-avoid-regexp") + # Set to new value with trailing whitespaces + self.runCmd( + "settings set target.process.thread.step-avoid-regexp foo\\ ") + self.expect( + "settings show target.process.thread.step-avoid-regexp", + SETTING_MSG("target.process.thread.step-avoid-regexp"), + substrs=['target.process.thread.step-avoid-regexp (regex) = foo\\ ']) + self.runCmd( + "settings clear target.process.thread.step-avoid-regexp", + check=False) + # format-string + self.runCmd("settings clear disassembly-format") # Set to known value + # Set to new value with trailing whitespaces + self.runCmd("settings set disassembly-format foo ") + self.expect("settings show disassembly-format", + SETTING_MSG("disassembly-format"), + substrs=['disassembly-format (format-string) = "foo "']) + self.runCmd("settings clear disassembly-format", check=False) + + def test_settings_list(self): + # List settings (and optionally test the filter to only show 'target' settings). + self.expect("settings list target", substrs=["language", "arg0", "detach-on-error"]) + self.expect("settings list target", matching=False, substrs=["packet-timeout"]) + self.expect("settings list", substrs=["language", "arg0", "detach-on-error", "packet-timeout"]) + + def test_settings_remove_single(self): + # Set some environment variables and use 'remove' to delete them. + self.runCmd("settings set target.env-vars a=b c=d") + self.expect("settings show target.env-vars", substrs=["a=b", "c=d"]) + self.runCmd("settings remove target.env-vars a") + self.expect("settings show target.env-vars", matching=False, substrs=["a=b"]) + self.expect("settings show target.env-vars", substrs=["c=d"]) + self.runCmd("settings remove target.env-vars c") + self.expect("settings show target.env-vars", matching=False, substrs=["a=b", "c=d"]) + + def test_settings_remove_multiple(self): + self.runCmd("settings set target.env-vars a=b c=d e=f") + self.expect("settings show target.env-vars", substrs=["a=b", "c=d", "e=f"]) + self.runCmd("settings remove target.env-vars a e") + self.expect("settings show target.env-vars", matching=False, substrs=["a=b", "e=f"]) + self.expect("settings show target.env-vars", substrs=["c=d"]) + + def test_settings_remove_nonexistent_value(self): + self.expect("settings remove target.env-vars doesntexist", error=True, + substrs=["no value found named 'doesntexist'"]) + + def test_settings_remove_nonexistent_settings(self): + self.expect("settings remove doesntexist alsodoesntexist", error=True, + substrs=["error: invalid value path 'doesntexist'"]) + + def test_settings_remove_missing_arg(self): + self.expect("settings remove", error=True, + substrs=["'settings remove' takes an array or dictionary item, or"]) + + def test_settings_remove_empty_arg(self): + self.expect("settings remove ''", error=True, + substrs=["'settings remove' command requires a valid variable name"]) + + def test_all_settings_exist(self): + self.expect("settings show", + substrs=["auto-confirm", + "frame-format", + "notify-void", + "prompt", + "script-lang", + "stop-disassembly-count", + "stop-disassembly-display", + "stop-line-count-after", + "stop-line-count-before", + "stop-show-column", + "term-width", + "thread-format", + "use-external-editor", + "target.default-arch", + "target.move-to-nearest-code", + "target.expr-prefix", + "target.language", + "target.prefer-dynamic-value", + "target.enable-synthetic-value", + "target.skip-prologue", + "target.source-map", + "target.exec-search-paths", + "target.max-children-count", + "target.max-string-summary-length", + "target.breakpoints-use-platform-avoid-list", + "target.run-args", + "target.env-vars", + "target.inherit-env", + "target.input-path", + "target.output-path", + "target.error-path", + "target.disable-aslr", + "target.disable-stdio", + "target.x86-disassembly-flavor", + "target.use-hex-immediates", + "target.hex-immediate-style", + "target.process.disable-memory-cache", + "target.process.extra-startup-command", + "target.process.thread.step-avoid-regexp", + "target.process.thread.trace-thread"]) + + # settings under an ".experimental" domain should have two properties: + # 1. If the name does not exist with "experimental" in the name path, + # the name lookup should try to find it without "experimental". So + # a previously-experimental setting that has been promoted to a + # "real" setting will still be set by the original name. + # 2. Changing a setting with .experimental., name, where the setting + # does not exist either with ".experimental." or without, should + # not generate an error. So if an experimental setting is removed, + # people who may have that in their ~/.lldbinit files should not see + # any errors. + def test_experimental_settings(self): + cmdinterp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + + # Set target.arg0 to a known value, check that we can retrieve it via + # the actual name and via .experimental. + self.expect('settings set target.arg0 first-value') + self.expect('settings show target.arg0', substrs=['first-value']) + self.expect('settings show target.experimental.arg0', substrs=['first-value'], error=False) + + # Set target.arg0 to a new value via a target.experimental.arg0 name, + # verify that we can read it back via both .experimental., and not. + self.expect('settings set target.experimental.arg0 second-value', error=False) + self.expect('settings show target.arg0', substrs=['second-value']) + self.expect('settings show target.experimental.arg0', substrs=['second-value'], error=False) + + # showing & setting an undefined .experimental. setting should generate no errors. + self.expect('settings show target.experimental.setting-which-does-not-exist', patterns=['^\s$'], error=False) + self.expect('settings set target.experimental.setting-which-does-not-exist true', error=False) + + # A domain component before .experimental. which does not exist should give an error + # But the code does not yet do that. + # self.expect('settings set target.setting-which-does-not-exist.experimental.arg0 true', error=True) + + # finally, confirm that trying to set a setting that does not exist still fails. + # (SHOWING a setting that does not exist does not currently yield an error.) + self.expect('settings set target.setting-which-does-not-exist true', error=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/main.cpp new file mode 100644 index 00000000000..5159eaa65b5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/main.cpp @@ -0,0 +1,74 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <cstdlib> +#include <string> +#include <fstream> +#include <iostream> + +int numberfn() +{ + return 0x5a; +} + +int +main(int argc, char const *argv[]) +{ + // The program writes its output to the following file: + // + // o "output1.txt" for test_pass_host_env_vars() test case + // o "output2.txt" for test_run_args_and_env_vars_with_dsym() test case + // o "output2.txt" for test_run_args_and_env_vars_with_dwarf() test case + std::ofstream outfile; + if (argc == 1) + outfile.open("output1.txt"); + else + outfile.open("output2.txt"); + + for (unsigned i = 0; i < argc; ++i) { + std::string theArg(argv[i]); + if (i == 1 && "A" == theArg) + outfile << "argv[1] matches\n"; + + if (i == 2 && "B" == theArg) + outfile << "argv[2] matches\n"; + + if (i == 3 && "C" == theArg) + outfile << "argv[3] matches\n"; + } + + // For passing environment vars from the debugger to the launched process. + if (::getenv("MY_ENV_VAR")) { + std::string MY_ENV_VAR(getenv("MY_ENV_VAR")); + if ("YES" == MY_ENV_VAR) { + outfile << "Environment variable 'MY_ENV_VAR' successfully passed.\n"; + } + } + + + // For passing host environment vars to the launched process. + if (::getenv("MY_HOST_ENV_VAR1")) { + std::string MY_HOST_ENV_VAR1(getenv("MY_HOST_ENV_VAR1")); + if ("VAR1" == MY_HOST_ENV_VAR1) { + outfile << "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.\n"; + } + } + + if (::getenv("MY_HOST_ENV_VAR2")) { + std::string MY_HOST_ENV_VAR2(getenv("MY_HOST_ENV_VAR2")); + if ("VAR2" == MY_HOST_ENV_VAR2) { + outfile << "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed.\n"; + } + } + + std::cerr << "This message should go to standard error.\n"; + std::cout << "This message should go to standard out.\n"; + + outfile.close(); + return numberfn(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/quoting/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/quoting/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/quoting/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/quoting/TestQuoting.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/quoting/TestQuoting.py new file mode 100644 index 00000000000..5853313db6f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/quoting/TestQuoting.py @@ -0,0 +1,93 @@ +""" +Test quoting of arguments to lldb commands +""" + + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SettingsCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @classmethod + def classCleanup(cls): + """Cleanup the test byproducts.""" + cls.RemoveTempFile("stdout.txt") + + @no_debug_info_test + def test_no_quote(self): + self.do_test_args("a b c", "a\0b\0c\0") + + @no_debug_info_test + def test_single_quote(self): + self.do_test_args("'a b c'", "a b c\0") + + @no_debug_info_test + def test_double_quote(self): + self.do_test_args('"a b c"', "a b c\0") + + @no_debug_info_test + def test_single_quote_escape(self): + self.do_test_args("'a b\\' c", "a b\\\0c\0") + + @no_debug_info_test + def test_double_quote_escape(self): + self.do_test_args('"a b\\" c"', 'a b" c\0') + + @no_debug_info_test + def test_double_quote_escape2(self): + self.do_test_args('"a b\\\\" c', 'a b\\\0c\0') + + @no_debug_info_test + def test_single_in_double(self): + self.do_test_args('"a\'b"', "a'b\0") + + @no_debug_info_test + def test_double_in_single(self): + self.do_test_args("'a\"b'", 'a"b\0') + + @no_debug_info_test + def test_combined(self): + self.do_test_args('"a b"c\'d e\'', 'a bcd e\0') + + @no_debug_info_test + def test_bare_single(self): + self.do_test_args("a\\'b", "a'b\0") + + @no_debug_info_test + def test_bare_double(self): + self.do_test_args('a\\"b', 'a"b\0') + + def do_test_args(self, args_in, args_out): + """Test argument parsing. Run the program with args_in. The program dumps its arguments + to stdout. Compare the stdout with args_out.""" + self.buildDefault() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + local_outfile = self.getBuildArtifact("output.txt") + if lldb.remote_platform: + remote_outfile = "output.txt" # Relative to platform's PWD + else: + remote_outfile = local_outfile + + self.runCmd("process launch -- %s %s" %(remote_outfile, args_in)) + + if lldb.remote_platform: + src_file_spec = lldb.SBFileSpec(remote_outfile, False) + dst_file_spec = lldb.SBFileSpec(local_outfile, True) + lldb.remote_platform.Get(src_file_spec, dst_file_spec) + + with open(local_outfile, 'r') as f: + output = f.read() + + self.RemoveTempFile(local_outfile) + + self.assertEqual(output, args_out) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/quoting/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/quoting/main.c new file mode 100644 index 00000000000..2ebaa142bc5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/settings/quoting/main.c @@ -0,0 +1,21 @@ +#include <stdio.h> +#include <string.h> +#include <stdlib.h> + +/* This program writes its arguments (separated by '\0') to stdout. */ +int +main(int argc, char const *argv[]) +{ + int i; + + FILE *output = fopen (argv[1], "w"); + if (output == NULL) + exit (1); + + for (i = 2; i < argc; ++i) + fwrite(argv[i], strlen(argv[i])+1, 1, output); + + fclose (output); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/source/info/TestSourceInfo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/source/info/TestSourceInfo.py new file mode 100644 index 00000000000..c8308c16011 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/source/info/TestSourceInfo.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/source/info/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/source/info/main.cpp new file mode 100644 index 00000000000..7d714900418 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/source/info/main.cpp @@ -0,0 +1,14 @@ +int bar(); + +int foo() { + return 3; +} + +int main() { + int f = foo() + bar(); + f++; + return f; //%self.expect("source info", substrs=["Lines found in module ", "main.cpp:10"]) + //%self.expect("source info -f main.cpp -c 10", matching=True, substrs=["main.cpp:10"]) + //%self.expect("source info -f main.cpp -c 1", matching=False, substrs=["main.cpp:10"]) + //%self.expect("source info -f main.cpp -l 10", matching=False, substrs=["main.cpp:7"]) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/source/info/second.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/source/info/second.cpp new file mode 100644 index 00000000000..0e068a691a8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/source/info/second.cpp @@ -0,0 +1,5 @@ +int bar() { + int i = 3; //%self.expect("source info", substrs=["Lines found in module ", "second.cpp:2"]) + return i; //%self.expect("source info", substrs=["Lines found in module ", "second.cpp:3"]) + //%self.expect("source info --name main", substrs=["Lines found in module ", "main.cpp:7", "main.cpp:10"]) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/statistics/basic/TestStats.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/statistics/basic/TestStats.py new file mode 100644 index 00000000000..9f5c7172a65 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/statistics/basic/TestStats.py @@ -0,0 +1,5 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [decorators.no_debug_info_test]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/statistics/basic/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/statistics/basic/main.c new file mode 100644 index 00000000000..9adb3a09a08 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/statistics/basic/main.c @@ -0,0 +1,18 @@ +// Test that the lldb command `statistics` works. + +int main(void) { + int patatino = 27; + //%self.expect("statistics disable", substrs=['need to enable statistics before disabling'], error=True) + //%self.expect("statistics enable") + //%self.expect("statistics enable", substrs=['already enabled'], error=True) + //%self.expect("expr patatino", substrs=['27']) + //%self.expect("statistics disable") + //%self.expect("statistics dump", substrs=['expr evaluation successes : 1', 'expr evaluation failures : 0']) + //%self.expect("frame var", substrs=['27']) + //%self.expect("statistics enable") + //%self.expect("frame var", substrs=['27']) + //%self.expect("statistics disable") + //%self.expect("statistics dump", substrs=['frame var successes : 1', 'frame var failures : 0']) + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/Makefile new file mode 100644 index 00000000000..b31e594019f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/Makefile @@ -0,0 +1,6 @@ +# Example: +# +# C_SOURCES := b.c +# EXE := b.out + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/TestTargetCommand.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/TestTargetCommand.py new file mode 100644 index 00000000000..6152a6a9673 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/TestTargetCommand.py @@ -0,0 +1,439 @@ +""" +Test some target commands: create, list, select, variable. +""" + +import os +import stat +import tempfile + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class targetCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers for our breakpoints. + self.line_b = line_number('b.c', '// Set break point at this line.') + self.line_c = line_number('c.c', '// Set break point at this line.') + + def buildB(self): + db = {'C_SOURCES': 'b.c', 'EXE': self.getBuildArtifact('b.out')} + self.build(dictionary=db) + self.addTearDownCleanup(dictionary=db) + + def buildAll(self): + da = {'C_SOURCES': 'a.c', 'EXE': self.getBuildArtifact('a.out')} + self.build(dictionary=da) + self.addTearDownCleanup(dictionary=da) + + self.buildB() + + dc = {'C_SOURCES': 'c.c', 'EXE': self.getBuildArtifact('c.out')} + self.build(dictionary=dc) + self.addTearDownCleanup(dictionary=dc) + + def test_target_command(self): + """Test some target commands: create, list, select.""" + self.buildAll() + self.do_target_command() + + def test_target_variable_command(self): + """Test 'target variable' command before and after starting the inferior.""" + d = {'C_SOURCES': 'globals.c', 'EXE': self.getBuildArtifact('globals')} + self.build(dictionary=d) + self.addTearDownCleanup(dictionary=d) + + self.do_target_variable_command('globals') + + def test_target_variable_command_no_fail(self): + """Test 'target variable' command before and after starting the inferior.""" + d = {'C_SOURCES': 'globals.c', 'EXE': self.getBuildArtifact('globals')} + self.build(dictionary=d) + self.addTearDownCleanup(dictionary=d) + + self.do_target_variable_command_no_fail('globals') + + def do_target_command(self): + """Exercise 'target create', 'target list', 'target select' commands.""" + exe_a = self.getBuildArtifact("a.out") + exe_b = self.getBuildArtifact("b.out") + exe_c = self.getBuildArtifact("c.out") + + self.runCmd("target list") + output = self.res.GetOutput() + if output.startswith("No targets"): + # We start from index 0. + base = 0 + else: + # Find the largest index of the existing list. + import re + pattern = re.compile("target #(\d+):") + for line in reversed(output.split(os.linesep)): + match = pattern.search(line) + if match: + # We will start from (index + 1) .... + base = int(match.group(1), 10) + 1 + #print("base is:", base) + break + + self.runCmd("target create " + exe_a, CURRENT_EXECUTABLE_SET) + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("target create " + exe_b, CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, 'b.c', self.line_b, num_expected_locations=1, loc_exact=True) + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("target create " + exe_c, CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, 'c.c', self.line_c, num_expected_locations=1, loc_exact=True) + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("target list") + + self.runCmd("target select %d" % base) + self.runCmd("thread backtrace") + + self.runCmd("target select %d" % (base + 2)) + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=['c.c:%d' % self.line_c, + 'stop reason = breakpoint']) + + self.runCmd("target select %d" % (base + 1)) + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=['b.c:%d' % self.line_b, + 'stop reason = breakpoint']) + + self.runCmd("target list") + + def do_target_variable_command(self, exe_name): + """Exercise 'target variable' command before and after starting the inferior.""" + self.runCmd("file " + self.getBuildArtifact(exe_name), + CURRENT_EXECUTABLE_SET) + + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) + self.expect("target variable my_global_str_ptr", matching=False, + substrs=['"abc"']) + self.expect("target variable *my_global_str_ptr", matching=True, + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) + + self.runCmd("b main") + self.runCmd("run") + + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) + self.expect("target variable my_global_str_ptr", matching=False, + substrs=['"abc"']) + self.expect("target variable *my_global_str_ptr", matching=True, + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) + + self.runCmd("c") + + # rdar://problem/9763907 + # 'target variable' command fails if the target program has been run + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) + self.expect("target variable my_global_str_ptr", matching=False, + substrs=['"abc"']) + self.expect("target variable *my_global_str_ptr", matching=True, + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) + + def do_target_variable_command_no_fail(self, exe_name): + """Exercise 'target variable' command before and after starting the inferior.""" + self.runCmd("file " + self.getBuildArtifact(exe_name), + CURRENT_EXECUTABLE_SET) + + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) + self.expect("target variable my_global_str_ptr", matching=False, + substrs=['"abc"']) + self.expect("target variable *my_global_str_ptr", matching=True, + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) + + self.runCmd("b main") + self.runCmd("run") + + # New feature: you don't need to specify the variable(s) to 'target vaiable'. + # It will find all the global and static variables in the current + # compile unit. + self.expect("target variable", + substrs=['my_global_char', + 'my_global_str', + 'my_global_str_ptr', + 'my_static_int']) + + self.expect( + "target variable my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_global_str', + '"abc"']) + self.expect( + "target variable my_static_int", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'my_static_int', + '228']) + self.expect("target variable my_global_str_ptr", matching=False, + substrs=['"abc"']) + self.expect("target variable *my_global_str_ptr", matching=True, + substrs=['"abc"']) + self.expect( + "target variable *my_global_str", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['a']) + self.expect( + "target variable my_global_char", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "my_global_char", + "'X'"]) + + @no_debug_info_test + def test_target_stop_hook_disable_enable(self): + self.buildB() + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + + self.expect("target stop-hook disable 1", error=True, substrs=['unknown stop hook id: "1"']) + self.expect("target stop-hook disable blub", error=True, substrs=['invalid stop hook id: "blub"']) + self.expect("target stop-hook enable 1", error=True, substrs=['unknown stop hook id: "1"']) + self.expect("target stop-hook enable blub", error=True, substrs=['invalid stop hook id: "blub"']) + + @no_debug_info_test + def test_target_stop_hook_delete(self): + self.buildB() + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + + self.expect("target stop-hook delete 1", error=True, substrs=['unknown stop hook id: "1"']) + self.expect("target stop-hook delete blub", error=True, substrs=['invalid stop hook id: "blub"']) + + @no_debug_info_test + def test_target_list_args(self): + self.expect("target list blub", error=True, + substrs=["the 'target list' command takes no arguments"]) + + @no_debug_info_test + def test_target_select_no_index(self): + self.expect("target select", error=True, + substrs=["'target select' takes a single argument: a target index"]) + + @no_debug_info_test + def test_target_select_invalid_index(self): + self.runCmd("target delete --all") + self.expect("target select 0", error=True, + substrs=["index 0 is out of range since there are no active targets"]) + self.buildB() + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + self.expect("target select 1", error=True, + substrs=["index 1 is out of range, valid target indexes are 0 - 0"]) + + + @no_debug_info_test + def test_target_create_multiple_args(self): + self.expect("target create a b", error=True, + substrs=["'target create' takes exactly one executable path"]) + + @no_debug_info_test + def test_target_create_nonexistent_core_file(self): + self.expect("target create -c doesntexist", error=True, + substrs=["core file 'doesntexist' doesn't exist"]) + + # Write only files don't seem to be supported on Windows. + @skipIfWindows + @no_debug_info_test + def test_target_create_unreadable_core_file(self): + tf = tempfile.NamedTemporaryFile() + os.chmod(tf.name, stat.S_IWRITE) + self.expect("target create -c '" + tf.name + "'", error=True, + substrs=["core file '", "' is not readable"]) + + @no_debug_info_test + def test_target_create_nonexistent_sym_file(self): + self.expect("target create -s doesntexist doesntexisteither", error=True, + substrs=["invalid symbol file path 'doesntexist'"]) + + @skipIfWindows + @no_debug_info_test + def test_target_create_invalid_core_file(self): + invalid_core_path = os.path.join(self.getSourceDir(), "invalid_core_file") + self.expect("target create -c '" + invalid_core_path + "'", error=True, + substrs=["Unable to find process plug-in for core file '"]) + + + # Write only files don't seem to be supported on Windows. + @skipIfWindows + @no_debug_info_test + def test_target_create_unreadable_sym_file(self): + tf = tempfile.NamedTemporaryFile() + os.chmod(tf.name, stat.S_IWRITE) + self.expect("target create -s '" + tf.name + "' no_exe", error=True, + substrs=["symbol file '", "' is not readable"]) + + @no_debug_info_test + def test_target_delete_all(self): + self.buildAll() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + self.expect("target delete --all") + self.expect("target list", substrs=["No targets."]) + + @no_debug_info_test + def test_target_delete_by_index(self): + self.buildAll() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("c.out"), CURRENT_EXECUTABLE_SET) + self.expect("target delete 3", error=True, + substrs=["target index 3 is out of range, valid target indexes are 0 - 2"]) + + self.runCmd("target delete 1") + self.expect("target list", matching=False, substrs=["b.out"]) + self.runCmd("target delete 1") + self.expect("target list", matching=False, substrs=["c.out"]) + + self.expect("target delete 1", error=True, + substrs=["target index 1 is out of range, the only valid index is 0"]) + + self.runCmd("target delete 0") + self.expect("target list", matching=False, substrs=["a.out"]) + + self.expect("target delete 0", error=True, substrs=["no targets to delete"]) + self.expect("target delete 1", error=True, substrs=["no targets to delete"]) + + @no_debug_info_test + def test_target_delete_by_index_multiple(self): + self.buildAll() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("c.out"), CURRENT_EXECUTABLE_SET) + + self.expect("target delete 0 1 2 3", error=True, + substrs=["target index 3 is out of range, valid target indexes are 0 - 2"]) + self.expect("target list", substrs=["a.out", "b.out", "c.out"]) + + self.runCmd("target delete 0 1 2") + self.expect("target list", matching=False, substrs=["a.out", "c.out"]) + + @no_debug_info_test + def test_target_delete_selected(self): + self.buildAll() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("file " + self.getBuildArtifact("c.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("target select 1") + self.runCmd("target delete") + self.expect("target list", matching=False, substrs=["b.out"]) + self.runCmd("target delete") + self.runCmd("target delete") + self.expect("target list", substrs=["No targets."]) + self.expect("target delete", error=True, substrs=["no target is currently selected"]) + + @no_debug_info_test + def test_target_modules_search_paths_clear(self): + self.buildB() + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("target modules search-paths add foo bar") + self.runCmd("target modules search-paths add foz baz") + self.runCmd("target modules search-paths clear") + self.expect("target list", matching=False, substrs=["bar", "baz"]) + + @no_debug_info_test + def test_target_modules_search_paths_query(self): + self.buildB() + self.runCmd("file " + self.getBuildArtifact("b.out"), CURRENT_EXECUTABLE_SET) + self.runCmd("target modules search-paths add foo bar") + self.expect("target modules search-paths query foo", substrs=["bar"]) + # Query something that doesn't exist. + self.expect("target modules search-paths query faz", substrs=["faz"]) + + # Invalid arguments. + self.expect("target modules search-paths query faz baz", error=True, + substrs=["query requires one argument"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/a.c new file mode 100644 index 00000000000..ec4824ad4ad --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/a.c @@ -0,0 +1,15 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int main(int argc, const char* argv[]) +{ + int *null_ptr = 0; + printf("Hello, segfault!\n"); + printf("Now crash %d\n", *null_ptr); // Crash here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/b.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/b.c new file mode 100644 index 00000000000..bcc466c8f96 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/b.c @@ -0,0 +1,12 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main (int argc, char const *argv[]) +{ + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/c.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/c.c new file mode 100644 index 00000000000..a2cb5995aa5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/c.c @@ -0,0 +1,28 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int main (int argc, char const *argv[]) +{ + enum days { + Monday = 10, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, + Sunday, + kNumDays + }; + enum days day; + for (day = Monday - 1; day <= kNumDays + 1; day++) + { + printf("day as int is %i\n", (int)day); + } + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/globals.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/globals.c new file mode 100644 index 00000000000..421b34c0cbc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/globals.c @@ -0,0 +1,24 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +char my_global_char = 'X'; +const char* my_global_str = "abc"; +const char **my_global_str_ptr = &my_global_str; +static int my_static_int = 228; + +int main (int argc, char const *argv[]) +{ + printf("global char: %c\n", my_global_char); + + printf("global str: %s\n", my_global_str); + + printf("argc + my_static_int = %d\n", (argc + my_static_int)); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/invalid_core_file b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/invalid_core_file new file mode 100644 index 00000000000..39802f64280 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/basic/invalid_core_file @@ -0,0 +1 @@ +stub diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/Makefile new file mode 100644 index 00000000000..3e5b1049b5a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/Makefile @@ -0,0 +1,10 @@ +LD_EXTRAS := -L. -lload_a +CXX_SOURCES := main.cpp + +a.out: libload_a + +include Makefile.rules + +libload_a: + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_NAME=load_a DYLIB_CXX_SOURCES=a.cpp diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/TestTargetCreateDeps.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/TestTargetCreateDeps.py new file mode 100644 index 00000000000..31be1cc86fa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/TestTargetCreateDeps.py @@ -0,0 +1,113 @@ +""" +Test that loading of dependents works correctly for all the potential +combinations. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +@skipIfWindows # Windows deals differently with shared libs. +class TargetDependentsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + TestBase.setUp(self) + self.build() + + def has_exactly_one_image(self, matching, msg=""): + self.expect( + "image list", + "image list should contain at least one image", + substrs=['[ 0]']) + should_match = not matching + self.expect( + "image list", msg, matching=should_match, substrs=['[ 1]']) + + + @expectedFailureAll(oslist=["linux"], + triple=no_match(".*-android")) + #linux does not support loading dependent files, but android does + @expectedFailureNetBSD + def test_dependents_implicit_default_exe(self): + """Test default behavior""" + exe = self.getBuildArtifact("a.out") + self.runCmd("target create " + exe, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(False) + + @expectedFailureAll(oslist=["linux"], + triple=no_match(".*-android")) + #linux does not support loading dependent files, but android does + @expectedFailureNetBSD + def test_dependents_explicit_default_exe(self): + """Test default behavior""" + exe = self.getBuildArtifact("a.out") + self.runCmd("target create -ddefault " + exe, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(False) + + def test_dependents_explicit_true_exe(self): + """Test default behavior""" + exe = self.getBuildArtifact("a.out") + self.runCmd("target create -dtrue " + exe, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(True) + + @expectedFailureAll(oslist=["linux"], + triple=no_match(".*-android")) + #linux does not support loading dependent files, but android does + @expectedFailureNetBSD + def test_dependents_explicit_false_exe(self): + """Test default behavior""" + exe = self.getBuildArtifact("a.out") + self.runCmd("target create -dfalse " + exe, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(False) + + def test_dependents_implicit_false_exe(self): + """Test default behavior""" + exe = self.getBuildArtifact("a.out") + self.runCmd("target create -d " + exe, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(True) + + @expectedFailureAndroid # android will return mutiple images + def test_dependents_implicit_default_lib(self): + ctx = self.platformContext + dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + lib = self.getBuildArtifact(dylibName) + self.runCmd("target create " + lib, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(True) + + def test_dependents_explicit_default_lib(self): + ctx = self.platformContext + dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + lib = self.getBuildArtifact(dylibName) + self.runCmd("target create -ddefault " + lib, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(True) + + def test_dependents_explicit_true_lib(self): + ctx = self.platformContext + dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + lib = self.getBuildArtifact(dylibName) + self.runCmd("target create -dtrue " + lib, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(True) + + @expectedFailureAll(oslist=["linux"], + triple=no_match(".*-android")) + #linux does not support loading dependent files, but android does + @expectedFailureNetBSD + def test_dependents_explicit_false_lib(self): + ctx = self.platformContext + dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + lib = self.getBuildArtifact(dylibName) + self.runCmd("target create -dfalse " + lib, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(False) + + def test_dependents_implicit_false_lib(self): + ctx = self.platformContext + dylibName = ctx.shlib_prefix + 'load_a.' + ctx.shlib_extension + lib = self.getBuildArtifact(dylibName) + self.runCmd("target create -d " + lib, CURRENT_EXECUTABLE_SET) + self.has_exactly_one_image(True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/a.cpp new file mode 100644 index 00000000000..e80612bd5cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/a.cpp @@ -0,0 +1,12 @@ +//===-- b.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int a_function () +{ + return 500; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/main.cpp new file mode 100644 index 00000000000..7ee1981a4c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-deps/main.cpp @@ -0,0 +1,16 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +extern int a_function (); +extern int b_function (); + +int +main (int argc, char const *argv[]) +{ + return a_function(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-no-such-arch/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-no-such-arch/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-no-such-arch/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-no-such-arch/TestNoSuchArch.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-no-such-arch/TestNoSuchArch.py new file mode 100644 index 00000000000..622a813ed41 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-no-such-arch/TestNoSuchArch.py @@ -0,0 +1,33 @@ +""" +Test that using a non-existent architecture name does not crash LLDB. +""" + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class NoSuchArchTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test(self): + self.build() + exe = self.getBuildArtifact("a.out") + + # Check that passing an invalid arch via the command-line fails but + # doesn't crash + self.expect( + "target create --arch nothingtoseehere %s" % + (exe), error=True, substrs=["error: invalid triple 'nothingtoseehere'"]) + + # Check that passing an invalid arch via the SB API fails but doesn't + # crash + target = self.dbg.CreateTargetWithFileAndArch(exe, "nothingtoseehere") + self.assertFalse(target.IsValid(), "This target should not be valid") + + # Now just create the target with the default arch and check it's fine + target = self.dbg.CreateTarget(exe) + self.assertTrue(target.IsValid(), "This target should now be valid") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-no-such-arch/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-no-such-arch/main.cpp new file mode 100644 index 00000000000..4cce7f667ff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/create-no-such-arch/main.cpp @@ -0,0 +1,3 @@ +int main() { + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/dump-symtab-demangle/TestDumpSymtabDemangle.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/dump-symtab-demangle/TestDumpSymtabDemangle.py new file mode 100644 index 00000000000..9f95a11f387 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/dump-symtab-demangle/TestDumpSymtabDemangle.py @@ -0,0 +1,30 @@ +""" +Test 'target modules dump symtab -m' doesn't demangle symbols. +""" + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test(self): + src_dir = self.getSourceDir() + yaml_path = os.path.join(src_dir, "a.yaml") + yaml_base, ext = os.path.splitext(yaml_path) + obj_path = self.getBuildArtifact("main.o") + self.yaml2obj(yaml_path, obj_path) + + # Create a target with the object file we just created from YAML + target = self.dbg.CreateTarget(obj_path) + self.assertTrue(target, VALID_TARGET) + + # First test that we demangle by default and our mangled symbol isn't in the output. + self.expect("target modules dump symtab", substrs=["foo::bar(int)"]) + self.expect("target modules dump symtab", matching=False, substrs=["_ZN3foo3barEi"]) + + # Turn off demangling and make sure that we now see the mangled name in the output. + self.expect("target modules dump symtab -m", substrs=["_ZN3foo3barEi"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/dump-symtab-demangle/a.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/dump-symtab-demangle/a.yaml new file mode 100644 index 00000000000..ed591d7c1c1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/dump-symtab-demangle/a.yaml @@ -0,0 +1,18 @@ +--- !ELF +FileHeader: + Class: ELFCLASS64 + Data: ELFDATA2LSB + Type: ET_REL + Machine: EM_X86_64 +Sections: + - Name: .text + Type: SHT_PROGBITS + Flags: [ SHF_ALLOC, SHF_EXECINSTR ] + AddressAlign: 0x0000000000000010 + Content: 554889E5897DFC5DC3 +Symbols: + - Name: _ZN3foo3barEi + Type: STT_FUNC + Section: .text + Size: 0x0000000000000009 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/stop-hooks/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/stop-hooks/Makefile new file mode 100644 index 00000000000..695335e068c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/stop-hooks/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/stop-hooks/TestStopHooks.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/stop-hooks/TestStopHooks.py new file mode 100644 index 00000000000..64686afe627 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/stop-hooks/TestStopHooks.py @@ -0,0 +1,40 @@ +""" +Test that stop hooks trigger on "step-out" +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class TestStopHooks(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def test_stop_hooks_step_out(self): + """Test that stop hooks fire on step-out.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.c") + self.step_out_test() + + def step_out_test(self): + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", self.main_source_file) + + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + interp.HandleCommand("target stop-hook add -o 'expr g_var++'", result) + self.assertTrue(result.Succeeded, "Set the target stop hook") + thread.StepOut() + var = target.FindFirstGlobalVariable("g_var") + self.assertTrue(var.IsValid()) + self.assertEqual(var.GetValueAsUnsigned(), 1, "Updated g_var") + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/stop-hooks/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/stop-hooks/main.c new file mode 100644 index 00000000000..d08ad14776b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/target/stop-hooks/main.c @@ -0,0 +1,14 @@ +#include <stdio.h> + +static int g_var = 0; + +int step_out_of_me() +{ + return g_var; // Set a breakpoint here and step out. +} + +int +main() +{ + return step_out_of_me(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/version/TestVersion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/version/TestVersion.py new file mode 100644 index 00000000000..48b46f65a78 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/version/TestVersion.py @@ -0,0 +1,19 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +class VersionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_version(self): + # Should work even when people patch the output, + # so let's just assume that every vendor at least mentions + # 'lldb' in their version string. + self.expect("version", substrs=['lldb']) + + @no_debug_info_test + def test_version_invalid_invocation(self): + self.expect("version a", error=True, + substrs=['the version command takes no arguments.']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/.categories new file mode 100644 index 00000000000..50c1613cda7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/.categories @@ -0,0 +1 @@ +watchpoint diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchlocation/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchlocation/Makefile new file mode 100644 index 00000000000..de4ec12b13c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchlocation/Makefile @@ -0,0 +1,4 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchlocation/TestWatchLocation.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchlocation/TestWatchLocation.py new file mode 100644 index 00000000000..55bf929b25f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchlocation/TestWatchLocation.py @@ -0,0 +1,109 @@ +""" +Test lldb watchpoint that uses '-s size' to watch a pointed location with size. +""" + + + +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class HelloWatchLocationTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.cpp' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + # This is for verifying that watch location works. + self.violating_func = "do_bad_thing_with_location" + # Build dictionary to have unique executable names for each test + # method. + self.exe_name = self.testMethodName + self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + + # Most of the MIPS boards provide only one H/W watchpoints, and S/W + # watchpoints are not supported yet + @expectedFailureAll(triple=re.compile('^mips')) + # SystemZ and PowerPC also currently supports only one H/W watchpoint + @expectedFailureAll(archs=['powerpc64le', 's390x']) + @skipIfDarwin + def test_hello_watchlocation(self): + """Test watching a location with '-s size' option.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1, loc_exact=False) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a write-type watchpoint pointed to by 'g_char_ptr'. + self.expect( + "watchpoint set expression -w write -s 1 -- g_char_ptr", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 1', + 'type = w']) + # Get a hold of the watchpoint id just created, it is used later on to + # match the watchpoint id which is expected to be fired. + match = re.match( + "Watchpoint created: Watchpoint (.*):", + self.res.GetOutput().splitlines()[0]) + if match: + expected_wp_id = int(match.group(1), 0) + else: + self.fail("Grokking watchpoint id faailed!") + + self.runCmd("expr unsigned val = *g_char_ptr; val") + self.expect(self.res.GetOutput().splitlines()[0], exe=False, + endstr=' = 0') + + self.runCmd("watchpoint set expression -w write -s 4 -- &threads[0]") + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (write type), but + # only once. The stop reason of the thread should be watchpoint. + self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stopped', + 'stop reason = watchpoint %d' % expected_wp_id]) + + # Switch to the thread stopped due to watchpoint and issue some + # commands. + self.switch_to_thread_with_stop_reason(lldb.eStopReasonWatchpoint) + self.runCmd("thread backtrace") + self.expect("frame info", + substrs=[self.violating_func]) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should now be 1. + self.expect("watchpoint list -v", + substrs=['hit_count = 1']) + + self.runCmd("thread backtrace all") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchlocation/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchlocation/main.cpp new file mode 100644 index 00000000000..ac8cf6be166 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchlocation/main.cpp @@ -0,0 +1,103 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <chrono> +#include <condition_variable> +#include <cstdio> +#include <random> +#include <thread> + +std::default_random_engine g_random_engine{std::random_device{}()}; +std::uniform_int_distribution<> g_distribution{0, 3000000}; +std::condition_variable g_condition_variable; +std::mutex g_mutex; +int g_count; + +char *g_char_ptr = nullptr; + +void +barrier_wait() +{ + std::unique_lock<std::mutex> lock{g_mutex}; + if (--g_count > 0) + g_condition_variable.wait(lock); + else + g_condition_variable.notify_all(); +} + +void +do_bad_thing_with_location(char *char_ptr, char new_val) +{ + unsigned what = new_val; + printf("new value written to location(%p) = %u\n", char_ptr, what); + *char_ptr = new_val; +} + +uint32_t +access_pool (bool flag = false) +{ + static std::mutex g_access_mutex; + g_access_mutex.lock(); + + char old_val = *g_char_ptr; + if (flag) + do_bad_thing_with_location(g_char_ptr, old_val + 1); + + g_access_mutex.unlock(); + return *g_char_ptr; +} + +void +thread_func (uint32_t thread_index) +{ + printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index); + + barrier_wait(); + + uint32_t count = 0; + uint32_t val; + while (count++ < 15) + { + // random micro second sleep from zero to 3 seconds + int usec = g_distribution(g_random_engine); + printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec); + std::this_thread::sleep_for(std::chrono::microseconds{usec}); + + if (count < 7) + val = access_pool (); + else + val = access_pool (true); + + printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count); + } + printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index); +} + + +int main (int argc, char const *argv[]) +{ + g_count = 4; + std::thread threads[3]; + + g_char_ptr = new char{}; + + // Create 3 threads + for (auto &thread : threads) + thread = std::thread{thread_func, std::distance(threads, &thread)}; + + printf ("Before turning all three threads loose...\n"); // Set break point at this line. + barrier_wait(); + + // Join all of our threads + for (auto &thread : threads) + thread.join(); + + delete g_char_ptr; + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchpoint/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchpoint/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchpoint/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchpoint/TestMyFirstWatchpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchpoint/TestMyFirstWatchpoint.py new file mode 100644 index 00000000000..d51565b2b84 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchpoint/TestMyFirstWatchpoint.py @@ -0,0 +1,92 @@ +""" +Test my first lldb watchpoint. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class HelloWatchpointTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.c' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + # And the watchpoint variable declaration line number. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + self.exe_name = self.getBuildArtifact('a.out') + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + @add_test_categories(["basic_process"]) + def test_hello_watchpoint_using_watchpoint_set(self): + """Test a simple sequence of watchpoint creation and watchpoint hit.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a write-type watchpoint for 'global'. + # There should be only one watchpoint hit (see main.c). + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (write type), but + # only once. The stop reason of the thread should be watchpoint. + self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stopped', + 'stop reason = watchpoint']) + + self.runCmd("process continue") + + # Don't expect the read of 'global' to trigger a stop exception. + process = self.dbg.GetSelectedTarget().GetProcess() + if process.GetState() == lldb.eStateStopped: + self.assertFalse( + lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint)) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should now be 1. + self.expect("watchpoint list -v", + substrs=['hit_count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchpoint/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchpoint/main.c new file mode 100644 index 00000000000..173162dd353 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/hello_watchpoint/main.c @@ -0,0 +1,29 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +int32_t global = 10; // Watchpoint variable declaration. +char gchar1 = 'a'; +char gchar2 = 'b'; + +int main(int argc, char** argv) { + int local = 0; + printf("&global=%p\n", &global); + printf("about to write to 'global'...\n"); // Set break point at this line. + // When stopped, watch 'global' for write. + global = 20; + gchar1 += 1; + gchar2 += 1; + local += argc; + ++local; + printf("local: %d\n", local); + printf("global=%d\n", global); + printf("gchar1='%c'\n", gchar1); + printf("gchar2='%c'\n", gchar2); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multi_watchpoint_slots/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multi_watchpoint_slots/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multi_watchpoint_slots/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multi_watchpoint_slots/TestWatchpointMultipleSlots.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multi_watchpoint_slots/TestWatchpointMultipleSlots.py new file mode 100644 index 00000000000..843a2ac7477 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multi_watchpoint_slots/TestWatchpointMultipleSlots.py @@ -0,0 +1,100 @@ +""" +Test watchpoint slots we should not be able to install multiple watchpoints +within same word boundary. We should be able to install individual watchpoints +on any of the bytes, half-word, or word. This is only for ARM/AArch64 targets. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointSlotsTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # This is a arm and aarch64 specific test case. No other architectures tested. + @skipIf(archs=no_match(['arm', 'aarch64'])) + def test_multiple_watchpoints_on_same_word(self): + + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Detect line number after which we are going to increment arrayName. + loc_line = line_number('main.c', '// About to write byteArray') + + # Set a breakpoint on the line detected above. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", loc_line, num_expected_locations=1, loc_exact=True) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # Delete breakpoint we just hit. + self.expect("breakpoint delete 1", substrs=['1 breakpoints deleted']) + + # Set a watchpoint at byteArray[0] + self.expect("watchpoint set variable byteArray[0]", WATCHPOINT_CREATED, + substrs=['Watchpoint created','size = 1']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v 1", substrs=['hit_count = 0']) + + # debugserver on ios doesn't give an error, it creates another watchpoint, + # only expect errors on non-darwin platforms. + if not self.platformIsDarwin(): + # Try setting a watchpoint at byteArray[1] + self.expect("watchpoint set variable byteArray[1]", error=True, + substrs=['Watchpoint creation failed']) + + self.runCmd("process continue") + + # We should be stopped due to the watchpoint. + # The stop reason of the thread should be watchpoint. + self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stopped', 'stop reason = watchpoint 1']) + + # Delete the watchpoint we hit above successfully. + self.expect("watchpoint delete 1", substrs=['1 watchpoints deleted']) + + # Set a watchpoint at byteArray[3] + self.expect("watchpoint set variable byteArray[3]", WATCHPOINT_CREATED, + substrs=['Watchpoint created','size = 1']) + + # Resume inferior. + self.runCmd("process continue") + + # We should be stopped due to the watchpoint. + # The stop reason of the thread should be watchpoint. + if self.platformIsDarwin(): + # On darwin we'll hit byteArray[3] which is watchpoint 2 + self.expect("thread list -v", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stopped', 'stop reason = watchpoint 2']) + else: + self.expect("thread list -v", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stopped', 'stop reason = watchpoint 3']) + + # Resume inferior. + self.runCmd("process continue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multi_watchpoint_slots/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multi_watchpoint_slots/main.c new file mode 100644 index 00000000000..76ad27a4314 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multi_watchpoint_slots/main.c @@ -0,0 +1,28 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +uint64_t pad0 = 0; +uint8_t byteArray[4] = {0}; +uint64_t pad1 = 0; + +int main(int argc, char** argv) { + + int i; + + for (i = 0; i < 4; i++) + { + printf("About to write byteArray[%d] ...\n", i); // About to write byteArray + pad0++; + byteArray[i] = 7; + pad1++; + } + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_hits/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_hits/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_hits/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_hits/TestMultipleHits.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_hits/TestMultipleHits.py new file mode 100644 index 00000000000..2186dd0a42c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_hits/TestMultipleHits.py @@ -0,0 +1,53 @@ +""" +Test handling of cases when a single instruction triggers multiple watchpoints +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class MultipleHitsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipIf(bugnumber="llvm.org/pr30758", oslist=["linux"], archs=["arm", "aarch64", "powerpc64le"]) + @skipIfwatchOS + def test(self): + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target and target.IsValid(), VALID_TARGET) + + bp = target.BreakpointCreateByName("main") + self.assertTrue(bp and bp.IsValid(), "Breakpoint is valid") + + process = target.LaunchSimple(None, None, + self.get_process_working_directory()) + self.assertEqual(process.GetState(), lldb.eStateStopped) + + thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame and frame.IsValid(), "Frame is valid") + + buf = frame.FindValue("buf", lldb.eValueTypeVariableGlobal) + self.assertTrue(buf and buf.IsValid(), "buf is valid") + + for i in [0, target.GetAddressByteSize()]: + member = buf.GetChildAtIndex(i) + self.assertTrue(member and member.IsValid(), "member is valid") + + error = lldb.SBError() + watch = member.Watch(True, True, True, error) + self.assertTrue(error.Success()) + + process.Continue(); + self.assertEqual(process.GetState(), lldb.eStateStopped) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonWatchpoint) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_hits/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_hits/main.cpp new file mode 100644 index 00000000000..f99c12597ee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_hits/main.cpp @@ -0,0 +1,28 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> +alignas(16) uint8_t buf[32]; +// This uses inline assembly to generate an instruction that writes to a large +// block of memory. If it fails on your compiler/architecture, please add +// appropriate code to generate a large write to "buf". If you cannot write at +// least 2*sizeof(void*) bytes with a single instruction, you will have to skip +// this test. + +int main() { +#if defined(__i386__) || defined(__x86_64__) + asm volatile ("movdqa %%xmm0, %0" : : "m"(buf)); +#elif defined(__arm__) + asm volatile ("stm %0, { r0, r1, r2, r3 }" : : "r"(buf)); +#elif defined(__aarch64__) + asm volatile ("stp x0, x1, %0" : : "m"(buf)); +#elif defined(__mips__) + asm volatile ("lw $2, %0" : : "m"(buf)); +#endif + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_threads/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_threads/Makefile new file mode 100644 index 00000000000..de4ec12b13c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_threads/Makefile @@ -0,0 +1,4 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_threads/TestWatchpointMultipleThreads.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_threads/TestWatchpointMultipleThreads.py new file mode 100644 index 00000000000..3e6329eb91f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_threads/TestWatchpointMultipleThreads.py @@ -0,0 +1,108 @@ +""" +Test that lldb watchpoint works for multiple threads. +""" + +from __future__ import print_function + + +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointForMultipleThreadsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + main_spec = lldb.SBFileSpec("main.cpp", False) + + def test_watchpoint_before_thread_start(self): + """Test that we can hit a watchpoint we set before starting another thread""" + self.do_watchpoint_test("Before running the thread") + + def test_watchpoint_after_thread_start(self): + """Test that we can hit a watchpoint we set after starting another thread""" + self.do_watchpoint_test("After running the thread") + + def do_watchpoint_test(self, line): + self.build() + lldbutil.run_to_source_breakpoint(self, line, self.main_spec) + + # Now let's set a write-type watchpoint for variable 'g_val'. + self.expect( + "watchpoint set variable -w write g_val", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0']) + + self.runCmd("process continue") + + self.runCmd("thread list") + if "stop reason = watchpoint" in self.res.GetOutput(): + # Good, we verified that the watchpoint works! + self.runCmd("thread backtrace all") + else: + self.fail("The stop reason should be either break or watchpoint") + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should now be 1. + self.expect("watchpoint list -v", + substrs=['hit_count = 1']) + + def test_watchpoint_multiple_threads_wp_set_and_then_delete(self): + """Test that lldb watchpoint works for multiple threads, and after the watchpoint is deleted, the watchpoint event should no longer fires.""" + self.build() + self.setTearDownCleanup() + + lldbutil.run_to_source_breakpoint(self, "After running the thread", self.main_spec) + + # Now let's set a write-type watchpoint for variable 'g_val'. + self.expect( + "watchpoint set variable -w write g_val", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0']) + + watchpoint_stops = 0 + while True: + self.runCmd("process continue") + self.runCmd("process status") + if re.search("Process .* exited", self.res.GetOutput()): + # Great, we are done with this test! + break + + self.runCmd("thread list") + if "stop reason = watchpoint" in self.res.GetOutput(): + self.runCmd("thread backtrace all") + watchpoint_stops += 1 + if watchpoint_stops > 1: + self.fail( + "Watchpoint hits not supposed to exceed 1 by design!") + # Good, we verified that the watchpoint works! Now delete the + # watchpoint. + if self.TraceOn(): + print( + "watchpoint_stops=%d at the moment we delete the watchpoint" % + watchpoint_stops) + self.runCmd("watchpoint delete 1") + self.expect("watchpoint list -v", + substrs=['No watchpoints currently set.']) + continue + else: + self.fail("The stop reason should be either break or watchpoint") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_threads/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_threads/main.cpp new file mode 100644 index 00000000000..1e6266d2877 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/multiple_threads/main.cpp @@ -0,0 +1,34 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "pseudo_barrier.h" +#include <cstdio> +#include <thread> + +volatile uint32_t g_val = 0; +pseudo_barrier_t g_barrier; + +void thread_func() { + pseudo_barrier_wait(g_barrier); + printf("%s starting...\n", __FUNCTION__); + for (uint32_t i = 0; i < 10; ++i) + g_val = i; +} + +int main(int argc, char const *argv[]) { + printf("Before running the thread\n"); + pseudo_barrier_init(g_barrier, 2); + std::thread thread(thread_func); + + printf("After running the thread\n"); + pseudo_barrier_wait(g_barrier); + + thread.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/step_over_watchpoint/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/step_over_watchpoint/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/step_over_watchpoint/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/step_over_watchpoint/TestStepOverWatchpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/step_over_watchpoint/TestStepOverWatchpoint.py new file mode 100644 index 00000000000..2b8bbbca9e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/step_over_watchpoint/TestStepOverWatchpoint.py @@ -0,0 +1,119 @@ +"""Test stepping over watchpoints.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestStepOverWatchpoint(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @expectedFailureAll( + oslist=["linux"], + archs=[ + 'aarch64', + 'arm'], + bugnumber="llvm.org/pr26031") + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + @expectedFailureAll(oslist=["ios", "watchos", "tvos", "bridgeos"], bugnumber="<rdar://problem/34027183>") # watchpoint tests aren't working on arm64 + @add_test_categories(["basic_process"]) + def test(self): + """Test stepping over watchpoints.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + lldbutil.run_break_set_by_symbol(self, 'main') + + process = target.LaunchSimple(None, None, + self.get_process_working_directory()) + self.assertTrue(process.IsValid(), PROCESS_IS_VALID) + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + thread = lldbutil.get_stopped_thread(process, + lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid(), "Failed to get thread.") + + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame.IsValid(), "Failed to get frame.") + + read_value = frame.FindValue('g_watch_me_read', + lldb.eValueTypeVariableGlobal) + self.assertTrue(read_value.IsValid(), "Failed to find read value.") + + error = lldb.SBError() + + # resolve_location=True, read=True, write=False + read_watchpoint = read_value.Watch(True, True, False, error) + self.assertTrue(error.Success(), + "Error while setting watchpoint: %s" % + error.GetCString()) + self.assertTrue(read_watchpoint, "Failed to set read watchpoint.") + + thread.StepOver() + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonWatchpoint, + STOPPED_DUE_TO_WATCHPOINT) + self.assertTrue(thread.GetStopDescription(20) == 'watchpoint 1') + + process.Continue() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + self.assertTrue(thread.GetStopDescription(20) == 'step over') + + self.step_inst_for_watchpoint(1) + + write_value = frame.FindValue('g_watch_me_write', + lldb.eValueTypeVariableGlobal) + self.assertTrue(write_value, "Failed to find write value.") + + # Most of the MIPS boards provide only one H/W watchpoints, and S/W + # watchpoints are not supported yet + arch = self.getArchitecture() + if re.match("^mips", arch) or re.match("powerpc64le", arch): + self.runCmd("watchpoint delete 1") + + # resolve_location=True, read=False, write=True + write_watchpoint = write_value.Watch(True, False, True, error) + self.assertTrue(write_watchpoint, "Failed to set write watchpoint.") + self.assertTrue(error.Success(), + "Error while setting watchpoint: %s" % + error.GetCString()) + + thread.StepOver() + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonWatchpoint, + STOPPED_DUE_TO_WATCHPOINT) + self.assertTrue(thread.GetStopDescription(20) == 'watchpoint 2') + + process.Continue() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + self.assertTrue(thread.GetStopDescription(20) == 'step over') + + self.step_inst_for_watchpoint(2) + + def step_inst_for_watchpoint(self, wp_id): + watchpoint_hit = False + current_line = self.frame().GetLineEntry().GetLine() + while self.frame().GetLineEntry().GetLine() == current_line: + self.thread().StepInstruction(False) # step_over=False + stop_reason = self.thread().GetStopReason() + if stop_reason == lldb.eStopReasonWatchpoint: + self.assertFalse(watchpoint_hit, "Watchpoint already hit.") + expected_stop_desc = "watchpoint %d" % wp_id + actual_stop_desc = self.thread().GetStopDescription(20) + self.assertTrue(actual_stop_desc == expected_stop_desc, + "Watchpoint ID didn't match.") + watchpoint_hit = True + else: + self.assertTrue(stop_reason == lldb.eStopReasonPlanComplete, + STOPPED_DUE_TO_STEP_IN) + self.assertTrue(watchpoint_hit, "Watchpoint never hit.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/step_over_watchpoint/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/step_over_watchpoint/main.c new file mode 100644 index 00000000000..2d87d9a2f73 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/step_over_watchpoint/main.c @@ -0,0 +1,19 @@ +char g_watch_me_read; +char g_watch_me_write; +char g_temp; + +void watch_read() { + g_temp = g_watch_me_read; +} + +void watch_write() { + g_watch_me_write = g_temp; +} + +int main() { + watch_read(); + g_temp = g_watch_me_read; + watch_write(); + g_watch_me_write = g_temp; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/variable_out_of_scope/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/variable_out_of_scope/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/variable_out_of_scope/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/variable_out_of_scope/TestWatchedVarHitWhenInScope.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/variable_out_of_scope/TestWatchedVarHitWhenInScope.py new file mode 100644 index 00000000000..eee89134a13 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/variable_out_of_scope/TestWatchedVarHitWhenInScope.py @@ -0,0 +1,84 @@ +""" +Test that a variable watchpoint should only hit when in scope. +""" + + + +import unittest2 +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * + + +class WatchedVariableHitWhenInScopeTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + # This test depends on not tracking watchpoint expression hits if we have + # left the watchpoint scope. We will provide such an ability at some point + # but the way this was done was incorrect, and it is unclear that for the + # most part that's not what folks mostly want, so we have to provide a + # clearer API to express this. + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.c' + self.exe_name = self.testMethodName + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Test hangs due to a kernel bug, see fdfeff0f in the linux kernel for details + @skipIfTargetAndroid(api_levels=list(range(25+1)), archs=["aarch64", "arm"]) + @skipIf + def test_watched_var_should_only_hit_when_in_scope(self): + """Test that a variable watchpoint should only hit when in scope.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped in main. + lldbutil.run_break_set_by_symbol( + self, "main", num_expected_locations=-1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a watchpoint for 'c.a'. + # There should be only one watchpoint hit (see main.c). + self.expect("watchpoint set variable c.a", WATCHPOINT_CREATED, + substrs=['Watchpoint created', 'size = 4', 'type = w']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (write type), but + # only once. The stop reason of the thread should be watchpoint. + self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stopped', + 'stop reason = watchpoint']) + + self.runCmd("process continue") + # Don't expect the read of 'global' to trigger a stop exception. + # The process status should be 'exited'. + self.expect("process status", + substrs=['exited']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should now be 1. + self.expect("watchpoint list -v", + substrs=['hit_count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/variable_out_of_scope/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/variable_out_of_scope/main.c new file mode 100644 index 00000000000..1bf7a00ac83 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/variable_out_of_scope/main.c @@ -0,0 +1,15 @@ +typedef struct +{ + int a; + float b; +} mystruct; + +int main() +{ + mystruct c; + + c.a = 5; + c.b = 3.6; + + return 0; +}
\ No newline at end of file diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/TestWatchpointCommands.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/TestWatchpointCommands.py new file mode 100644 index 00000000000..50f78812935 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/TestWatchpointCommands.py @@ -0,0 +1,365 @@ +""" +Test watchpoint list, enable, disable, and delete commands. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointCommandsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.c' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + self.line2 = line_number( + self.source, + '// Set 2nd break point for disable_then_enable test case.') + # And the watchpoint variable declaration line number. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. + self.exe_name = self.testMethodName + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_rw_watchpoint(self): + """Test read_write watchpoint and expect to stop two times.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a read_write-type watchpoint for 'global'. + # There should be two watchpoint hits (see main.c). + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['Number of supported hardware watchpoints:', + 'hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (read_write type). + # The stop reason of the thread should be watchpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stop reason = watchpoint']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (read_write type). + # The stop reason of the thread should be watchpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stop reason = watchpoint']) + + self.runCmd("process continue") + + # There should be no more watchpoint hit and the process status should + # be 'exited'. + self.expect("process status", + substrs=['exited']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should now be 2. + self.expect("watchpoint list -v", + substrs=['hit_count = 2']) + + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_rw_watchpoint_delete(self): + """Test delete watchpoint and expect not to stop for watchpoint.""" + self.build() + lldbutil.run_to_line_breakpoint(self, lldb.SBFileSpec(self.source), + self.line) + + # Now let's set a read_write-type watchpoint for 'global'. + # There should be two watchpoint hits (see main.c). + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) + + # Delete the watchpoint immediately, but set auto-confirm to true + # first. + self.runCmd("settings set auto-confirm true") + self.expect("watchpoint delete", + substrs=['All watchpoints removed.']) + # Restore the original setting of auto-confirm. + self.runCmd("settings clear auto-confirm") + + target = self.dbg.GetSelectedTarget() + self.assertTrue(target and not target.GetNumWatchpoints()) + + # Now let's set a read_write-type watchpoint for 'global'. + # There should be two watchpoint hits (see main.c). + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) + + + # Delete the watchpoint immediately using the force option. + self.expect("watchpoint delete --force", + substrs=['All watchpoints removed.']) + + self.assertTrue(target and not target.GetNumWatchpoints()) + + self.runCmd("process continue") + + # There should be no more watchpoint hit and the process status should + # be 'exited'. + self.expect("process status", + substrs=['exited']) + + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_rw_watchpoint_set_ignore_count(self): + """Test watchpoint ignore count and expect to not to stop at all.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a read_write-type watchpoint for 'global'. + # There should be two watchpoint hits (see main.c). + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) + + # Set the ignore count of the watchpoint immediately. + self.expect("watchpoint ignore -i 2", + substrs=['All watchpoints ignored.']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # Expect to find an ignore_count of 2. + self.expect("watchpoint list -v", + substrs=['hit_count = 0', 'ignore_count = 2']) + + self.runCmd("process continue") + + # There should be no more watchpoint hit and the process status should + # be 'exited'. + self.expect("process status", + substrs=['exited']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # Expect to find a hit_count of 2 as well. + self.expect("watchpoint list -v", + substrs=['hit_count = 2', 'ignore_count = 2']) + + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_rw_disable_after_first_stop(self): + """Test read_write watchpoint but disable it after the first stop.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a read_write-type watchpoint for 'global'. + # There should be two watchpoint hits (see main.c). + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['state = enabled', 'hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (read_write type). + # The stop reason of the thread should be watchpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stop reason = watchpoint']) + + # Before continuing, we'll disable the watchpoint, which means we won't + # stop again after this. + self.runCmd("watchpoint disable") + + self.expect("watchpoint list -v", + substrs=['state = disabled', 'hit_count = 1']) + + self.runCmd("process continue") + + # There should be no more watchpoint hit and the process status should + # be 'exited'. + self.expect("process status", + substrs=['exited']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 1. + self.expect("watchpoint list -v", + substrs=['hit_count = 1']) + + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_rw_disable_then_enable(self): + """Test read_write watchpoint, disable initially, then enable it.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, None, self.line2, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a read_write-type watchpoint for 'global'. + # There should be two watchpoint hits (see main.c). + self.expect( + "watchpoint set variable -w read_write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = rw', + '%s:%d' % + (self.source, + self.decl)]) + + # Immediately, we disable the watchpoint. We won't be stopping due to a + # watchpoint after this. + self.runCmd("watchpoint disable") + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['state = disabled', 'hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the breakpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stop reason = breakpoint']) + + # Before continuing, we'll enable the watchpoint, which means we will + # stop again after this. + self.runCmd("watchpoint enable") + + self.expect("watchpoint list -v", + substrs=['state = enabled', 'hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (read_write type). + # The stop reason of the thread should be watchpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stop reason = watchpoint']) + + self.runCmd("process continue") + + # There should be no more watchpoint hit and the process status should + # be 'exited'. + self.expect("process status", + substrs=['exited']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 1. + self.expect("watchpoint list -v", + substrs=['hit_count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandLLDB.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandLLDB.py new file mode 100644 index 00000000000..cb5a535b730 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandLLDB.py @@ -0,0 +1,155 @@ +""" +Test 'watchpoint command'. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointLLDBCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.cpp' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + # And the watchpoint variable declaration line number. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. + self.exe_name = 'a%d.out' % self.test_number + self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + + def test_watchpoint_command(self): + """Test 'watchpoint command'.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a write-type watchpoint for 'global'. + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) + + self.runCmd('watchpoint command add 1 -o "expr -- cookie = 777"') + + # List the watchpoint command we just added. + self.expect("watchpoint command list 1", + substrs=['expr -- cookie = 777']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (write type). + # The stop reason of the thread should be watchpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stop reason = watchpoint']) + + # Check that the watchpoint snapshoting mechanism is working. + self.expect("watchpoint list -v", + substrs=['old value:', ' = 0', + 'new value:', ' = 1']) + + # The watchpoint command "forced" our global variable 'cookie' to + # become 777. + self.expect("frame variable --show-globals cookie", + substrs=['(int32_t)', 'cookie = 777']) + + def test_watchpoint_command_can_disable_a_watchpoint(self): + """Test that 'watchpoint command' action can disable a watchpoint after it is triggered.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a write-type watchpoint for 'global'. + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) + + self.runCmd('watchpoint command add 1 -o "watchpoint disable 1"') + + # List the watchpoint command we just added. + self.expect("watchpoint command list 1", + substrs=['watchpoint disable 1']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (write type). + # The stop reason of the thread should be watchpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stop reason = watchpoint']) + + # Check that the watchpoint has been disabled. + self.expect("watchpoint list -v", + substrs=['disabled']) + + self.runCmd("process continue") + + # There should be no more watchpoint hit and the process status should + # be 'exited'. + self.expect("process status", + substrs=['exited']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandPython.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandPython.py new file mode 100644 index 00000000000..c72a535c51a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/TestWatchpointCommandPython.py @@ -0,0 +1,154 @@ +""" +Test 'watchpoint command'. +""" + + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointPythonCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.cpp' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + # And the watchpoint variable declaration line number. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. + self.exe_name = self.testMethodName + self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + + @skipIfFreeBSD # timing out on buildbot + def test_watchpoint_command(self): + """Test 'watchpoint command'.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a write-type watchpoint for 'global'. + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) + + self.runCmd( + 'watchpoint command add -s python 1 -o \'frame.EvaluateExpression("cookie = 777")\'') + + # List the watchpoint command we just added. + self.expect("watchpoint command list 1", + substrs=['frame.EvaluateExpression', 'cookie = 777']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (write type). + # The stop reason of the thread should be watchpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stop reason = watchpoint']) + + # Check that the watchpoint snapshoting mechanism is working. + self.expect("watchpoint list -v", + substrs=['old value:', ' = 0', + 'new value:', ' = 1']) + + # The watchpoint command "forced" our global variable 'cookie' to + # become 777. + self.expect("frame variable --show-globals cookie", + substrs=['(int32_t)', 'cookie = 777']) + + @skipIfFreeBSD # timing out on buildbot + def test_continue_in_watchpoint_command(self): + """Test continue in a watchpoint command.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a write-type watchpoint for 'global'. + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) + + cmd_script_file = os.path.join(self.getSourceDir(), + "watchpoint_command.py") + self.runCmd("command script import '%s'" % (cmd_script_file)) + + self.runCmd( + 'watchpoint command add -F watchpoint_command.watchpoint_command') + + # List the watchpoint command we just added. + self.expect("watchpoint command list 1", + substrs=['watchpoint_command.watchpoint_command']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (write type). + # The stop reason of the thread should be watchpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stop reason = watchpoint']) + + # We should have hit the watchpoint once, set cookie to 888, then continued to the + # second hit and set it to 999 + self.expect("frame variable --show-globals cookie", + substrs=['(int32_t)', 'cookie = 999']) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/main.cpp new file mode 100644 index 00000000000..43e4c1a7a34 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/main.cpp @@ -0,0 +1,27 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +int32_t global = 0; // Watchpoint variable declaration. +int32_t cookie = 0; + +static void modify(int32_t &var) { + ++var; +} + +int main(int argc, char** argv) { + int local = 0; + printf("&global=%p\n", &global); + printf("about to write to 'global'...\n"); // Set break point at this line. + for (int i = 0; i < 10; ++i) + modify(global); + + printf("global=%d\n", global); + printf("cookie=%d\n", cookie); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/watchpoint_command.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/watchpoint_command.py new file mode 100644 index 00000000000..ae5913a500e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/command/watchpoint_command.py @@ -0,0 +1,15 @@ +import lldb + +num_hits = 0 + + +def watchpoint_command(frame, wp, dict): + global num_hits + if num_hits == 0: + print ("I stopped the first time") + frame.EvaluateExpression("cookie = 888") + num_hits += 1 + frame.thread.process.Continue() + else: + print ("I stopped the %d time" % (num_hits)) + frame.EvaluateExpression("cookie = 999") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/condition/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/condition/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/condition/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/condition/TestWatchpointConditionCmd.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/condition/TestWatchpointConditionCmd.py new file mode 100644 index 00000000000..0605aae5290 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/condition/TestWatchpointConditionCmd.py @@ -0,0 +1,87 @@ +""" +Test watchpoint modify command to set condition on a watchpoint. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointConditionCmdTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.cpp' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + # And the watchpoint variable declaration line number. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. + self.exe_name = self.testMethodName + self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + + def test_watchpoint_cond(self): + """Test watchpoint condition.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a write-type watchpoint for 'global'. + # With a condition of 'global==5'. + self.expect( + "watchpoint set variable -w write global", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 4', + 'type = w', + '%s:%d' % + (self.source, + self.decl)]) + + self.runCmd("watchpoint modify -c 'global==5'") + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0', 'global==5']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (write type). + # The stop reason of the thread should be watchpoint. + self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stop reason = watchpoint']) + self.expect("frame variable --show-globals global", + substrs=['(int32_t)', 'global = 5']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should now be 2. + self.expect("watchpoint list -v", + substrs=['hit_count = 5']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/condition/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/condition/main.cpp new file mode 100644 index 00000000000..3f7c5f5be96 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/condition/main.cpp @@ -0,0 +1,27 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +int32_t global = 0; // Watchpoint variable declaration. + +static void modify(int32_t &var) { + ++var; +} + +int main(int argc, char** argv) { + int local = 0; + printf("&global=%p\n", &global); + printf("about to write to 'global'...\n"); // Set break point at this line. + // When stopped, watch 'global', + // for the condition "global == 5". + for (int i = 0; i < 10; ++i) + modify(global); + + printf("global=%d\n", global); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/main.c new file mode 100644 index 00000000000..a9d1cf28da0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_commands/main.c @@ -0,0 +1,23 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +int32_t global = 10; // Watchpoint variable declaration. + +int main(int argc, char** argv) { + int local = 0; + printf("&global=%p\n", &global); + printf("about to write to 'global'...\n"); // Set break point at this line. + // When stopped, watch 'global'. + global = 20; + local += argc; + ++local; // Set 2nd break point for disable_then_enable test case. + printf("local: %d\n", local); + printf("global=%d\n", global); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_disable/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_disable/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_disable/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_disable/TestWatchpointDisable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_disable/TestWatchpointDisable.py new file mode 100644 index 00000000000..cf33f4708b1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_disable/TestWatchpointDisable.py @@ -0,0 +1,71 @@ +""" +Test that the SBWatchpoint::SetEnable API works. +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from lldbsuite.test import lldbplatform, lldbplatformutil + + +class TestWatchpointSetEnable(TestBase): + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_disable_works (self): + """Set a watchpoint, disable it, and make sure it doesn't get hit.""" + self.build() + self.do_test(False) + + def test_disable_enable_works (self): + """Set a watchpoint, disable it, and make sure it doesn't get hit.""" + self.build() + self.do_test(True) + + def do_test(self, test_enable): + """Set a watchpoint, disable it and make sure it doesn't get hit.""" + + exe = self.getBuildArtifact("a.out") + main_file_spec = lldb.SBFileSpec("main.c") + + # Create a target by the debugger. + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + bkpt_before = self.target.BreakpointCreateBySourceRegex("Set a breakpoint here", main_file_spec) + self.assertEqual(bkpt_before.GetNumLocations(), 1, "Failed setting the before breakpoint.") + + bkpt_after = self.target.BreakpointCreateBySourceRegex("We should have stopped", main_file_spec) + self.assertEqual(bkpt_after.GetNumLocations(), 1, "Failed setting the after breakpoint.") + + process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, bkpt_before) + self.assertTrue(thread.IsValid(), "We didn't stop at the before breakpoint.") + + ret_val = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand("watchpoint set variable -w write global_var", ret_val) + self.assertTrue(ret_val.Succeeded(), "Watchpoint set variable did not return success.") + + wp = self.target.FindWatchpointByID(1) + self.assertTrue(wp.IsValid(), "Didn't make a valid watchpoint.") + self.assertTrue(wp.GetWatchAddress() != lldb.LLDB_INVALID_ADDRESS, "Watch address is invalid") + + wp.SetEnabled(False) + self.assertTrue(not wp.IsEnabled(), "The watchpoint thinks it is still enabled") + + process.Continue() + + stop_reason = thread.GetStopReason() + + self.assertEqual(stop_reason, lldb.eStopReasonBreakpoint, "We didn't stop at our breakpoint.") + + if test_enable: + wp.SetEnabled(True) + self.assertTrue(wp.IsEnabled(), "The watchpoint thinks it is still disabled.") + process.Continue() + stop_reason = thread.GetStopReason() + self.assertEqual(stop_reason, lldb.eStopReasonWatchpoint, "We didn't stop at our watchpoint") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_disable/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_disable/main.c new file mode 100644 index 00000000000..dcbc766c594 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_disable/main.c @@ -0,0 +1,13 @@ +#include <stdio.h> + +int global_var = 10; + +int +main() +{ + printf("Set a breakpoint here: %d.\n", global_var); + global_var = 20; + printf("We should have stopped on the previous line: %d.\n", global_var); + global_var = 30; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_events/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_events/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_events/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_events/TestWatchpointEvents.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_events/TestWatchpointEvents.py new file mode 100644 index 00000000000..826bed8912b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_events/TestWatchpointEvents.py @@ -0,0 +1,110 @@ +"""Test that adding, deleting and modifying watchpoints sends the appropriate events.""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestWatchpointEvents (TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers that we will step to in main: + self.main_source = "main.c" + + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test that adding, deleting and modifying watchpoints sends the appropriate events.""" + self.build() + + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + break_in_main = target.BreakpointCreateBySourceRegex( + '// Put a breakpoint here.', self.main_source_spec) + self.assertTrue(break_in_main, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_main) + + if len(threads) != 1: + self.fail("Failed to stop at first breakpoint in main.") + + thread = threads[0] + frame = thread.GetFrameAtIndex(0) + local_var = frame.FindVariable("local_var") + self.assertTrue(local_var.IsValid()) + + self.listener = lldb.SBListener("com.lldb.testsuite_listener") + self.target_bcast = target.GetBroadcaster() + self.target_bcast.AddListener( + self.listener, lldb.SBTarget.eBroadcastBitWatchpointChanged) + self.listener.StartListeningForEvents( + self.target_bcast, lldb.SBTarget.eBroadcastBitWatchpointChanged) + + error = lldb.SBError() + local_watch = local_var.Watch(True, False, True, error) + if not error.Success(): + self.fail( + "Failed to make watchpoint for local_var: %s" % + (error.GetCString())) + + self.GetWatchpointEvent(lldb.eWatchpointEventTypeAdded) + # Now change some of the features of this watchpoint and make sure we + # get events: + local_watch.SetEnabled(False) + self.GetWatchpointEvent(lldb.eWatchpointEventTypeDisabled) + + local_watch.SetEnabled(True) + self.GetWatchpointEvent(lldb.eWatchpointEventTypeEnabled) + + local_watch.SetIgnoreCount(10) + self.GetWatchpointEvent(lldb.eWatchpointEventTypeIgnoreChanged) + + condition = "1 == 2" + local_watch.SetCondition(condition) + self.GetWatchpointEvent(lldb.eWatchpointEventTypeConditionChanged) + + self.assertTrue(local_watch.GetCondition() == condition, + 'make sure watchpoint condition is "' + condition + '"') + + def GetWatchpointEvent(self, event_type): + # We added a watchpoint so we should get a watchpoint added event. + event = lldb.SBEvent() + success = self.listener.WaitForEvent(1, event) + self.assertTrue(success, "Successfully got watchpoint event") + self.assertTrue( + lldb.SBWatchpoint.EventIsWatchpointEvent(event), + "Event is a watchpoint event.") + found_type = lldb.SBWatchpoint.GetWatchpointEventTypeFromEvent(event) + self.assertTrue( + found_type == event_type, + "Event is not correct type, expected: %d, found: %d" % + (event_type, + found_type)) + # There shouldn't be another event waiting around: + found_event = self.listener.PeekAtNextEventForBroadcasterWithType( + self.target_bcast, lldb.SBTarget.eBroadcastBitBreakpointChanged, event) + if found_event: + print("Found an event I didn't expect: ", event) + + self.assertTrue(not found_event, "Only one event per change.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_events/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_events/main.c new file mode 100644 index 00000000000..4b917536a16 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_events/main.c @@ -0,0 +1,9 @@ +#include <stdio.h> + +int +main (int argc, char **argv) +{ + int local_var = 10; + printf ("local_var is: %d.\n", local_var++); // Put a breakpoint here. + return local_var; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_on_vectors/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_on_vectors/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_on_vectors/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_on_vectors/TestValueOfVectorVariable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_on_vectors/TestValueOfVectorVariable.py new file mode 100644 index 00000000000..81b44c02744 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_on_vectors/TestValueOfVectorVariable.py @@ -0,0 +1,47 @@ +""" +Test displayed value of a vector variable while doing watchpoint operations +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestValueOfVectorVariableTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_value_of_vector_variable_using_watchpoint_set(self): + """Test verify displayed value of vector variable.""" + exe = self.getBuildArtifact("a.out") + d = {'C_SOURCES': self.source, 'EXE': exe} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.value_of_vector_variable_with_watchpoint_set() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.c' + + def value_of_vector_variable_with_watchpoint_set(self): + """Test verify displayed value of vector variable""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Set break to get a frame + self.runCmd("b main") + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Value of a vector variable should be displayed correctly + self.expect( + "watchpoint set variable global_vector", + WATCHPOINT_CREATED, + substrs=['new value: (1, 2, 3, 4)']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_on_vectors/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_on_vectors/main.c new file mode 100644 index 00000000000..04d8a06a354 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_on_vectors/main.c @@ -0,0 +1,15 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +typedef signed char v4i8 __attribute__ ((vector_size(4))); +v4i8 global_vector = {1, 2, 3, 4}; + +int +main () +{ + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_set_command/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_set_command/Makefile new file mode 100644 index 00000000000..de4ec12b13c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_set_command/Makefile @@ -0,0 +1,4 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_set_command/TestWatchLocationWithWatchSet.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_set_command/TestWatchLocationWithWatchSet.py new file mode 100644 index 00000000000..326028e6f36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_set_command/TestWatchLocationWithWatchSet.py @@ -0,0 +1,103 @@ +""" +Test lldb watchpoint that uses 'watchpoint set -w write -s size' to watch a pointed location with size. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchLocationUsingWatchpointSetTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.cpp' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + # This is for verifying that watch location works. + self.violating_func = "do_bad_thing_with_location" + # Build dictionary to have unique executable names for each test + # method. + + @skipIf( + oslist=["linux"], + archs=[ + 'aarch64', + 'arm'], + bugnumber="llvm.org/pr26031") + def test_watchlocation_using_watchpoint_set(self): + """Test watching a location with 'watchpoint set expression -w write -s size' option.""" + self.build() + self.setTearDownCleanup() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint to set a watchpoint when stopped on the breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now let's set a write-type watchpoint pointed to by 'g_char_ptr' and + # with offset as 7. + # The main.cpp, by design, misbehaves by not following the agreed upon + # protocol of only accessing the allowable index range of [0, 6]. + self.expect( + "watchpoint set expression -w write -s 1 -- g_char_ptr + 7", + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = 1', + 'type = w']) + self.runCmd("expr unsigned val = g_char_ptr[7]; val") + self.expect(self.res.GetOutput().splitlines()[0], exe=False, + endstr=' = 0') + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", + substrs=['hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped again due to the watchpoint (write type), but + # only once. The stop reason of the thread should be watchpoint. + self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stopped', + 'stop reason = watchpoint', + self.violating_func]) + + # Switch to the thread stopped due to watchpoint and issue some + # commands. + self.switch_to_thread_with_stop_reason(lldb.eStopReasonWatchpoint) + self.runCmd("thread backtrace") + self.runCmd("expr unsigned val = g_char_ptr[7]; val") + self.expect(self.res.GetOutput().splitlines()[0], exe=False, + endstr=' = 99') + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should now be the same as the number of threads that + # stopped on a watchpoint. + threads = lldbutil.get_stopped_threads( + self.process(), lldb.eStopReasonWatchpoint) + self.expect("watchpoint list -v", + substrs=['hit_count = %d' % len(threads)]) + + self.runCmd("thread backtrace all") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_set_command/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_set_command/main.cpp new file mode 100644 index 00000000000..f21d2b33ff4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_set_command/main.cpp @@ -0,0 +1,115 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <chrono> +#include <condition_variable> +#include <cstdio> +#include <thread> + +std::condition_variable g_condition_variable; +std::mutex g_mutex; +int g_count; + +char *g_char_ptr = nullptr; + +void +barrier_wait() +{ + std::unique_lock<std::mutex> lock{g_mutex}; + if (--g_count > 0) + g_condition_variable.wait(lock); + else + g_condition_variable.notify_all(); +} + +void +do_bad_thing_with_location(unsigned index, char *char_ptr, char new_val) +{ + unsigned what = new_val; + printf("new value written to array(%p) and index(%u) = %u\n", char_ptr, index, what); + char_ptr[index] = new_val; +} + +uint32_t +access_pool (bool flag = false) +{ + static std::mutex g_access_mutex; + static unsigned idx = 0; // Well-behaving thread only writes into indexs from 0..6. + if (!flag) + g_access_mutex.lock(); + + // idx valid range is [0, 6]. + if (idx > 6) + idx = 0; + + if (flag) + { + // Write into a forbidden area. + do_bad_thing_with_location(7, g_char_ptr, 99); + } + + unsigned index = idx++; + + if (!flag) + g_access_mutex.unlock(); + return g_char_ptr[index]; +} + +void +thread_func (uint32_t thread_index) +{ + printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index); + + barrier_wait(); + + uint32_t count = 0; + uint32_t val; + while (count++ < 15) + { + printf ("%s (thread = %u) sleeping for 1 second...\n", __FUNCTION__, thread_index); + std::this_thread::sleep_for(std::chrono::seconds(1)); + + if (count < 7) + val = access_pool (); + else + val = access_pool (true); + + printf ("%s (thread = %u) after sleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count); + } + printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index); +} + + +int main (int argc, char const *argv[]) +{ + g_count = 4; + std::thread threads[3]; + + g_char_ptr = new char[10]{}; + + // Create 3 threads + for (auto &thread : threads) + thread = std::thread{thread_func, std::distance(threads, &thread)}; + + struct { + int a; + int b; + int c; + } MyAggregateDataType; + + printf ("Before turning all three threads loose...\n"); // Set break point at this line. + barrier_wait(); + + // Join all of our threads + for (auto &thread : threads) + thread.join(); + + delete[] g_char_ptr; + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_size/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_size/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_size/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_size/TestWatchpointSizes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_size/TestWatchpointSizes.py new file mode 100644 index 00000000000..e6634f1e4a3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_size/TestWatchpointSizes.py @@ -0,0 +1,122 @@ +""" +Test watchpoint size cases (1-byte, 2-byte, 4-byte). +Make sure we can watch all bytes, words or double words individually +when they are packed in a 8-byte region. + +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointSizeTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_byte_size_watchpoints_with_byte_selection(self): + """Test to selectively watch different bytes in a 8-byte array.""" + self.run_watchpoint_size_test('byteArray', 8, '1') + + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_two_byte_watchpoints_with_word_selection(self): + """Test to selectively watch different words in an 8-byte word array.""" + self.run_watchpoint_size_test('wordArray', 4, '2') + + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_four_byte_watchpoints_with_dword_selection(self): + """Test to selectively watch two double words in an 8-byte dword array.""" + self.run_watchpoint_size_test('dwordArray', 2, '4') + + def run_watchpoint_size_test(self, arrayName, array_size, watchsize): + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Detect line number after which we are going to increment arrayName. + loc_line = line_number('main.c', '// About to write ' + arrayName) + + # Set a breakpoint on the line detected above. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", loc_line, num_expected_locations=1, loc_exact=True) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + for i in range(array_size): + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # Set a read_write type watchpoint arrayName + watch_loc = arrayName + "[" + str(i) + "]" + self.expect( + "watchpoint set variable -w read_write " + + watch_loc, + WATCHPOINT_CREATED, + substrs=[ + 'Watchpoint created', + 'size = ' + + watchsize, + 'type = rw']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should be 0 initially. + self.expect("watchpoint list -v", substrs=['hit_count = 0']) + + self.runCmd("process continue") + + # We should be stopped due to the watchpoint. + # The stop reason of the thread should be watchpoint. + self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stopped', 'stop reason = watchpoint']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should now be 1. + self.expect("watchpoint list -v", + substrs=['hit_count = 1']) + + self.runCmd("process continue") + + # We should be stopped due to the watchpoint. + # The stop reason of the thread should be watchpoint. + self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT, + substrs=['stopped', 'stop reason = watchpoint']) + + # Use the '-v' option to do verbose listing of the watchpoint. + # The hit count should now be 1. + # Verify hit_count has been updated after value has been read. + self.expect("watchpoint list -v", + substrs=['hit_count = 2']) + + # Delete the watchpoint immediately, but set auto-confirm to true + # first. + self.runCmd("settings set auto-confirm true") + self.expect( + "watchpoint delete", + substrs=['All watchpoints removed.']) + # Restore the original setting of auto-confirm. + self.runCmd("settings clear auto-confirm") + + self.runCmd("process continue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_size/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_size/main.c new file mode 100644 index 00000000000..4edcf877e74 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/commands/watchpoints/watchpoint_size/main.c @@ -0,0 +1,65 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +uint64_t pad0 = 0; +uint8_t byteArray[8] = {0}; +uint64_t pad1 = 0; +uint16_t wordArray[4] = {0}; +uint64_t pad2 = 0; +uint32_t dwordArray[2] = {0}; + +int main(int argc, char** argv) { + + int i; + uint8_t localByte; + uint16_t localWord; + uint32_t localDword; + + for (i = 0; i < 8; i++) + { + printf("About to write byteArray[%d] ...\n", i); // About to write byteArray + pad0++; + byteArray[i] = 7; + pad1++; + localByte = byteArray[i]; // Here onwards we should'nt be stopped in loop + byteArray[i]++; + localByte = byteArray[i]; + } + + pad0 = 0; + pad1 = 0; + + for (i = 0; i < 4; i++) + { + printf("About to write wordArray[%d] ...\n", i); // About to write wordArray + pad0++; + wordArray[i] = 7; + pad1++; + localWord = wordArray[i]; // Here onwards we should'nt be stopped in loop + wordArray[i]++; + localWord = wordArray[i]; + } + + pad0 = 0; + pad1 = 0; + + for (i = 0; i < 2; i++) + { + printf("About to write dwordArray[%d] ...\n", i); // About to write dwordArray + pad0++; + dwordArray[i] = 7; + pad1++; + localDword = dwordArray[i]; // Here onwards we shouldn't be stopped in loop + dwordArray[i]++; + localDword = dwordArray[i]; + } + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/concurrent_base.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/concurrent_base.py new file mode 100644 index 00000000000..6acd71ce9e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/concurrent_base.py @@ -0,0 +1,284 @@ +""" +A stress-test of sorts for LLDB's handling of threads in the inferior. + +This test sets a breakpoint in the main thread where test parameters (numbers of +threads) can be adjusted, runs the inferior to that point, and modifies the +locals that control the event thread counts. This test also sets a breakpoint in +breakpoint_func (the function executed by each 'breakpoint' thread) and a +watchpoint on a global modified in watchpoint_func. The inferior is continued +until exit or a crash takes place, and the number of events seen by LLDB is +verified to match the expected number of events. +""" + + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ConcurrentEventsBase(TestBase): + + # Concurrency is the primary test factor here, not debug info variants. + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + super(ConcurrentEventsBase, self).setUp() + # Find the line number for our breakpoint. + self.filename = 'main.cpp' + self.thread_breakpoint_line = line_number( + self.filename, '// Set breakpoint here') + self.setup_breakpoint_line = line_number( + self.filename, '// Break here and adjust num') + self.finish_breakpoint_line = line_number( + self.filename, '// Break here and verify one thread is active') + + def describe_threads(self): + ret = [] + for x in self.inferior_process: + id = x.GetIndexID() + reason = x.GetStopReason() + status = "stopped" if x.IsStopped() else "running" + reason_str = lldbutil.stop_reason_to_str(reason) + if reason == lldb.eStopReasonBreakpoint: + bpid = x.GetStopReasonDataAtIndex(0) + bp = self.inferior_target.FindBreakpointByID(bpid) + reason_str = "%s hit %d times" % ( + lldbutil.get_description(bp), bp.GetHitCount()) + elif reason == lldb.eStopReasonWatchpoint: + watchid = x.GetStopReasonDataAtIndex(0) + watch = self.inferior_target.FindWatchpointByID(watchid) + reason_str = "%s hit %d times" % ( + lldbutil.get_description(watch), watch.GetHitCount()) + elif reason == lldb.eStopReasonSignal: + signals = self.inferior_process.GetUnixSignals() + signal_name = signals.GetSignalAsCString( + x.GetStopReasonDataAtIndex(0)) + reason_str = "signal %s" % signal_name + + location = "\t".join([lldbutil.get_description( + x.GetFrameAtIndex(i)) for i in range(x.GetNumFrames())]) + ret.append( + "thread %d %s due to %s at\n\t%s" % + (id, status, reason_str, location)) + return ret + + def add_breakpoint(self, line, descriptions): + """ Adds a breakpoint at self.filename:line and appends its description to descriptions, and + returns the LLDB SBBreakpoint object. + """ + + bpno = lldbutil.run_break_set_by_file_and_line( + self, self.filename, line, num_expected_locations=-1) + bp = self.inferior_target.FindBreakpointByID(bpno) + descriptions.append( + ": file = 'main.cpp', line = %d" % + self.finish_breakpoint_line) + return bp + + def inferior_done(self): + """ Returns true if the inferior is done executing all the event threads (and is stopped at self.finish_breakpoint, + or has terminated execution. + """ + return self.finish_breakpoint.GetHitCount() > 0 or \ + self.crash_count > 0 or \ + self.inferior_process.GetState() == lldb.eStateExited + + def count_signaled_threads(self): + count = 0 + for thread in self.inferior_process: + if thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex( + 0) == self.inferior_process.GetUnixSignals().GetSignalNumberFromName('SIGUSR1'): + count += 1 + return count + + def do_thread_actions(self, + num_breakpoint_threads=0, + num_signal_threads=0, + num_watchpoint_threads=0, + num_crash_threads=0, + num_delay_breakpoint_threads=0, + num_delay_signal_threads=0, + num_delay_watchpoint_threads=0, + num_delay_crash_threads=0): + """ Sets a breakpoint in the main thread where test parameters (numbers of threads) can be adjusted, runs the inferior + to that point, and modifies the locals that control the event thread counts. Also sets a breakpoint in + breakpoint_func (the function executed by each 'breakpoint' thread) and a watchpoint on a global modified in + watchpoint_func. The inferior is continued until exit or a crash takes place, and the number of events seen by LLDB + is verified to match the expected number of events. + """ + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Get the target + self.inferior_target = self.dbg.GetSelectedTarget() + + expected_bps = [] + + # Initialize all the breakpoints (main thread/aux thread) + self.setup_breakpoint = self.add_breakpoint( + self.setup_breakpoint_line, expected_bps) + self.finish_breakpoint = self.add_breakpoint( + self.finish_breakpoint_line, expected_bps) + + # Set the thread breakpoint + if num_breakpoint_threads + num_delay_breakpoint_threads > 0: + self.thread_breakpoint = self.add_breakpoint( + self.thread_breakpoint_line, expected_bps) + + # Verify breakpoints + self.expect( + "breakpoint list -f", + "Breakpoint locations shown correctly", + substrs=expected_bps) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Check we are at line self.setup_breakpoint + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."]) + + # Initialize the (single) watchpoint on the global variable (g_watchme) + if num_watchpoint_threads + num_delay_watchpoint_threads > 0: + self.runCmd("watchpoint set variable g_watchme") + for w in self.inferior_target.watchpoint_iter(): + self.thread_watchpoint = w + self.assertTrue( + "g_watchme" in str( + self.thread_watchpoint), + "Watchpoint location not shown correctly") + + # Get the process + self.inferior_process = self.inferior_target.GetProcess() + + # We should be stopped at the setup site where we can set the number of + # threads doing each action (break/crash/signal/watch) + self.assertEqual( + self.inferior_process.GetNumThreads(), + 1, + 'Expected to stop before any additional threads are spawned.') + + self.runCmd("expr num_breakpoint_threads=%d" % num_breakpoint_threads) + self.runCmd("expr num_crash_threads=%d" % num_crash_threads) + self.runCmd("expr num_signal_threads=%d" % num_signal_threads) + self.runCmd("expr num_watchpoint_threads=%d" % num_watchpoint_threads) + + self.runCmd( + "expr num_delay_breakpoint_threads=%d" % + num_delay_breakpoint_threads) + self.runCmd( + "expr num_delay_crash_threads=%d" % + num_delay_crash_threads) + self.runCmd( + "expr num_delay_signal_threads=%d" % + num_delay_signal_threads) + self.runCmd( + "expr num_delay_watchpoint_threads=%d" % + num_delay_watchpoint_threads) + + # Continue the inferior so threads are spawned + self.runCmd("continue") + + # Make sure we see all the threads. The inferior program's threads all synchronize with a pseudo-barrier; that is, + # the inferior program ensures all threads are started and running + # before any thread triggers its 'event'. + num_threads = self.inferior_process.GetNumThreads() + expected_num_threads = num_breakpoint_threads + num_delay_breakpoint_threads \ + + num_signal_threads + num_delay_signal_threads \ + + num_watchpoint_threads + num_delay_watchpoint_threads \ + + num_crash_threads + num_delay_crash_threads + 1 + self.assertEqual( + num_threads, + expected_num_threads, + 'Expected to see %d threads, but seeing %d. Details:\n%s' % + (expected_num_threads, + num_threads, + "\n\t".join( + self.describe_threads()))) + + self.signal_count = self.count_signaled_threads() + self.crash_count = len( + lldbutil.get_crashed_threads( + self, self.inferior_process)) + + # Run to completion (or crash) + while not self.inferior_done(): + if self.TraceOn(): + self.runCmd("thread backtrace all") + self.runCmd("continue") + self.signal_count += self.count_signaled_threads() + self.crash_count += len( + lldbutil.get_crashed_threads( + self, self.inferior_process)) + + if num_crash_threads > 0 or num_delay_crash_threads > 0: + # Expecting a crash + self.assertTrue( + self.crash_count > 0, + "Expecting at least one thread to crash. Details: %s" % + "\t\n".join( + self.describe_threads())) + + # Ensure the zombie process is reaped + self.runCmd("process kill") + + elif num_crash_threads == 0 and num_delay_crash_threads == 0: + # There should be a single active thread (the main one) which hit + # the breakpoint after joining + self.assertEqual( + 1, + self.finish_breakpoint.GetHitCount(), + "Expected main thread (finish) breakpoint to be hit once") + + num_threads = self.inferior_process.GetNumThreads() + self.assertEqual( + 1, + num_threads, + "Expecting 1 thread but seeing %d. Details:%s" % + (num_threads, + "\n\t".join( + self.describe_threads()))) + self.runCmd("continue") + + # The inferior process should have exited without crashing + self.assertEqual( + 0, + self.crash_count, + "Unexpected thread(s) in crashed state") + self.assertEqual( + self.inferior_process.GetState(), + lldb.eStateExited, + PROCESS_EXITED) + + # Verify the number of actions took place matches expected numbers + expected_breakpoint_threads = num_delay_breakpoint_threads + num_breakpoint_threads + breakpoint_hit_count = self.thread_breakpoint.GetHitCount( + ) if expected_breakpoint_threads > 0 else 0 + self.assertEqual( + expected_breakpoint_threads, + breakpoint_hit_count, + "Expected %d breakpoint hits, but got %d" % + (expected_breakpoint_threads, + breakpoint_hit_count)) + + expected_signal_threads = num_delay_signal_threads + num_signal_threads + self.assertEqual( + expected_signal_threads, + self.signal_count, + "Expected %d stops due to signal delivery, but got %d" % + (expected_signal_threads, + self.signal_count)) + + expected_watchpoint_threads = num_delay_watchpoint_threads + num_watchpoint_threads + watchpoint_hit_count = self.thread_watchpoint.GetHitCount( + ) if expected_watchpoint_threads > 0 else 0 + self.assertEqual( + expected_watchpoint_threads, + watchpoint_hit_count, + "Expected %d watchpoint hits, got %d" % + (expected_watchpoint_threads, + watchpoint_hit_count)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/configuration.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/configuration.py new file mode 100644 index 00000000000..09fc646f96e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/configuration.py @@ -0,0 +1,188 @@ +""" +Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +See https://llvm.org/LICENSE.txt for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +Provides the configuration class, which holds all information related to +how this invocation of the test suite should be run. +""" + +from __future__ import absolute_import +from __future__ import print_function + +# System modules +import os + + +# Third-party modules +import unittest2 + +# LLDB Modules +import lldbsuite + + +# The test suite. +suite = unittest2.TestSuite() + +# The list of categories we said we care about +categories_list = None +# set to true if we are going to use categories for cherry-picking test cases +use_categories = False +# Categories we want to skip +skip_categories = ["darwin-log"] +# Categories we expect to fail +xfail_categories = [] +# use this to track per-category failures +failures_per_category = {} + +# The path to LLDB.framework is optional. +lldb_framework_path = None + +# Test suite repeat count. Can be overwritten with '-# count'. +count = 1 + +# The 'arch' and 'compiler' can be specified via command line. +arch = None # Must be initialized after option parsing +compiler = None # Must be initialized after option parsing + +# The overriden dwarf verison. +dwarf_version = 0 + +# Any overridden settings. +# Always disable default dynamic types for testing purposes. +settings = [('target.prefer-dynamic-value', 'no-dynamic-values')] + +# Path to the FileCheck testing tool. Not optional. +filecheck = None + +# The arch might dictate some specific CFLAGS to be passed to the toolchain to build +# the inferior programs. The global variable cflags_extras provides a hook to do +# just that. +cflags_extras = '' + +# The filters (testclass.testmethod) used to admit tests into our test suite. +filters = [] + +# The regular expression pattern to match against eligible filenames as +# our test cases. +regexp = None + +# Sets of tests which are excluded at runtime +skip_tests = None +xfail_tests = None + +# By default, recorded session info for errored/failed test are dumped into its +# own file under a session directory named after the timestamp of the test suite +# run. Use '-s session-dir-name' to specify a specific dir name. +sdir_name = None + +# Valid options: +# f - test file name (without extension) +# n - test class name +# m - test method name +# a - architecture +# c - compiler path +# The default is to write all fields. +session_file_format = 'fnmac' + +# Set this flag if there is any session info dumped during the test run. +sdir_has_content = False + +# svn_info stores the output from 'svn info lldb.base.dir'. +svn_info = '' + +# Default verbosity is 0. +verbose = 0 + +# By default, search from the script directory. +# We can't use sys.path[0] to determine the script directory +# because it doesn't work under a debugger +testdirs = [os.path.dirname(os.path.realpath(__file__))] + +# Separator string. +separator = '-' * 70 + +failed = False + +# LLDB Remote platform setting +lldb_platform_name = None +lldb_platform_url = None +lldb_platform_working_dir = None + +# The base directory in which the tests are being built. +test_build_dir = None + +# The clang module cache directory used by lldb. +lldb_module_cache_dir = None +# The clang module cache directory used by clang. +clang_module_cache_dir = None + +# The only directory to scan for tests. If multiple test directories are +# specified, and an exclusive test subdirectory is specified, the latter option +# takes precedence. +exclusive_test_subdir = None + +# Test results handling globals +results_filename = None +results_formatter_name = None +results_formatter_object = None +results_formatter_options = None +test_result = None + +# Test rerun configuration vars +rerun_all_issues = False + +# The names of all tests. Used to assert we don't have two tests with the +# same base name. +all_tests = set() + +def shouldSkipBecauseOfCategories(test_categories): + if use_categories: + if len(test_categories) == 0 or len( + categories_list & set(test_categories)) == 0: + return True + + for category in skip_categories: + if category in test_categories: + return True + + return False + + +def get_absolute_path_to_exclusive_test_subdir(): + """ + If an exclusive test subdirectory is specified, return its absolute path. + Otherwise return None. + """ + test_directory = os.path.dirname(os.path.realpath(__file__)) + + if not exclusive_test_subdir: + return + + if len(exclusive_test_subdir) > 0: + test_subdir = os.path.join(test_directory, exclusive_test_subdir) + if os.path.isdir(test_subdir): + return test_subdir + + print('specified test subdirectory {} is not a valid directory\n' + .format(test_subdir)) + + +def get_absolute_path_to_root_test_dir(): + """ + If an exclusive test subdirectory is specified, return its absolute path. + Otherwise, return the absolute path of the root test directory. + """ + test_subdir = get_absolute_path_to_exclusive_test_subdir() + if test_subdir: + return test_subdir + + return os.path.dirname(os.path.realpath(__file__)) + + +def get_filecheck_path(): + """ + Get the path to the FileCheck testing tool. + """ + if filecheck and os.path.lexists(filecheck): + return filecheck diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/darwin_log.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/darwin_log.py new file mode 100644 index 00000000000..9d473facb09 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/darwin_log.py @@ -0,0 +1,456 @@ +""" +Base class for DarwinLog tests. +""" + +# System imports +from __future__ import print_function + +import json +import platform +import re +import sys +import threading + + +# lldb imports +import lldb +from lldb import SBProcess, SBTarget + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import lldbtest_config +from lldbsuite.test import lldbutil + + +def expand_darwinlog_command(command): + return "plugin structured-data darwin-log " + command + + +def expand_darwinlog_settings_set_command(command): + return "settings set plugin.structured-data.darwin-log." + command + + +class DarwinLogTestBase(lldbtest.TestBase): + """Base class for DarwinLog test cases that are pexpect-based.""" + NO_DEBUG_INFO_TESTCASE = True + + CONTINUE_REGEX = re.compile(r"Process \d+ resuming") + + def setUp(self): + # Call super's setUp(). + super(DarwinLogTestBase, self).setUp() + + # Until other systems support this, exit + # early if we're not macOS version 10.12 + # or greater. + version = platform.mac_ver()[0].split('.') + if ((int(version[0]) == 10) and (int(version[1]) < 12) or + (int(version[0]) < 10)): + self.skipTest("DarwinLog tests currently require macOS 10.12+") + return + + self.child = None + self.child_prompt = '(lldb) ' + self.strict_sources = False + self.enable_process_monitor_logging = False + + def run_lldb_to_breakpoint(self, exe, source_file, line, + enable_command=None, settings_commands=None): + + import pexpect + # Set self.child_prompt, which is "(lldb) ". + prompt = self.child_prompt + + # So that the child gets torn down after the test. + self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, + self.lldbOption, exe)) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + if self.enable_process_monitor_logging: + if platform.system() == 'Darwin': + self.runCmd( + "settings set target.process.extra-startup-command " + "QSetLogging:bitmask=LOG_DARWIN_LOG;") + self.expect_prompt() + + # Run the enable command if we have one. + if enable_command is not None: + self.runCmd(enable_command) + self.expect_prompt() + + # Disable showing of source lines at our breakpoint. + # This is necessary for the logging tests, because the very + # text we want to match for output from the running inferior + # will show up in the source as well. We don't want the source + # output to erroneously make a match with our expected output. + self.runCmd("settings set stop-line-count-before 0") + self.expect_prompt() + self.runCmd("settings set stop-line-count-after 0") + self.expect_prompt() + + # While we're debugging, turn on packet logging. + self.runCmd("log enable -f /tmp/packets.log gdb-remote packets") + self.expect_prompt() + + # Prevent mirroring of NSLog/os_log content to stderr. We want log + # messages to come exclusively through our log channel. + self.runCmd( + "settings set target.env-vars IDE_DISABLED_OS_ACTIVITY_DT_MODE=1") + self.expect_prompt() + + # Run any darwin-log settings commands now, before we enable logging. + if settings_commands is not None: + for setting_command in settings_commands: + self.runCmd( + expand_darwinlog_settings_set_command(setting_command)) + self.expect_prompt() + + # Set breakpoint right before the os_log() macros. We don't + # set it on the os_log*() calls because these are a number of + # nested-scoped calls that will cause the debugger to stop + # multiple times on the same line. That is difficult to match + # os_log() content by since it is non-deterministic what the + # ordering between stops and log lines will be. This is why + # we stop before, and then have the process run in a sleep + # afterwards, so we get the log messages while the target + # process is "running" (sleeping). + child.sendline('breakpoint set -f %s -l %d' % (source_file, line)) + child.expect_exact(prompt) + + # Now run to the breakpoint that we just set. + child.sendline('run') + child.expect_exact(prompt) + + # Ensure we stopped at a breakpoint. + self.runCmd("thread list") + self.expect(re.compile(r"stop reason = breakpoint")) + + # Now we're ready to check if DarwinLog is available. + if not self.darwin_log_available(): + self.skipTest("DarwinLog not available") + + def runCmd(self, cmd): + self.child.sendline(cmd) + + def expect_prompt(self, exactly=True): + self.expect(self.child_prompt, exactly=exactly) + + def expect(self, pattern, exactly=False, *args, **kwargs): + if exactly: + return self.child.expect_exact(pattern, *args, **kwargs) + return self.child.expect(pattern, *args, **kwargs) + + def darwin_log_available(self): + self.runCmd("plugin structured-data darwin-log status") + self.expect(re.compile(r"Availability: ([\S]+)")) + return self.child.match is not None and ( + self.child.match.group(1) == "available") + + def do_test(self, enable_options, expect_regexes=None, + settings_commands=None): + """Test that a single fall-through reject rule rejects all logging.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + # Build the darwin-log enable command. + enable_cmd = expand_darwinlog_command('enable') + if enable_options is not None and len(enable_options) > 0: + enable_cmd += ' ' + ' '.join(enable_options) + + exe = self.getBuildArtifact(self.exe_name) + self.run_lldb_to_breakpoint(exe, self.source, self.line, + enable_command=enable_cmd, + settings_commands=settings_commands) + self.expect_prompt() + + # Now go. + self.runCmd("process continue") + self.expect(self.CONTINUE_REGEX) + + if expect_regexes is None: + # Expect matching a log line or program exit. + # Test methods determine which ones are valid. + expect_regexes = ( + [re.compile(r"source-log-([^-]+)-(\S+)"), + re.compile(r"exited with status") + ]) + self.expect(expect_regexes) + + +def remove_add_mode_entry(log_entries): + """libtrace creates an "Add Mode:..." message when logging is enabled. + Strip this out of results since our test subjects don't create it.""" + return [entry for entry in log_entries + if "message" in entry and + not entry["message"].startswith("Add Mode:")] + + +class DarwinLogEventBasedTestBase(lldbtest.TestBase): + """Base class for event-based DarwinLog tests.""" + NO_DEBUG_INFO_TESTCASE = True + + class EventListenerThread(threading.Thread): + + def __init__(self, listener, process, trace_on, max_entry_count): + super( + DarwinLogEventBasedTestBase.EventListenerThread, + self).__init__() + self.process = process + self.listener = listener + self.trace_on = trace_on + self.max_entry_count = max_entry_count + self.exception = None + self.structured_data_event_count = 0 + self.wait_seconds = 2 + self.max_timeout_count = 4 + self.log_entries = [] + + def handle_structured_data_event(self, event): + structured_data = SBProcess.GetStructuredDataFromEvent(event) + if not structured_data.IsValid(): + if self.trace_on: + print("invalid structured data") + return + + # Track that we received a valid structured data event. + self.structured_data_event_count += 1 + + # Grab the individual log entries from the JSON. + stream = lldb.SBStream() + structured_data.GetAsJSON(stream) + dict = json.loads(stream.GetData()) + self.log_entries.extend(dict["events"]) + if self.trace_on: + print("Structured data (raw):", stream.GetData()) + + # Print the pretty-printed version. + if self.trace_on: + stream.Clear() + structured_data.PrettyPrint(stream) + print("Structured data (pretty print):", + stream.GetData()) + + def done(self, timeout_count): + """Returns True when we're done listening for events.""" + # See if we should consider the number of events retrieved. + if self.max_entry_count is not None: + if len(self.log_entries) >= self.max_entry_count: + # We've received the max threshold of events expected, + # we can exit here. + if self.trace_on: + print("Event listener thread exiting due to max " + "expected log entry count being reached.") + return True + + # If our event timeout count has exceeded our maximum timeout count, + # we're done. + if timeout_count >= self.max_timeout_count: + if self.trace_on: + print("Event listener thread exiting due to max number of " + "WaitForEvent() timeouts being reached.") + return True + + # If our process is dead, we're done. + if not self.process.is_alive: + if self.trace_on: + print("Event listener thread exiting due to test inferior " + "exiting.") + return True + + # We're not done. + return False + + def run(self): + event = lldb.SBEvent() + try: + timeout_count = 0 + + # Wait up to 4 times for the event to arrive. + while not self.done(timeout_count): + if self.trace_on: + print("Calling wait for event...") + if self.listener.WaitForEvent(self.wait_seconds, event): + while event.IsValid(): + # Check if it's a process event. + if SBProcess.EventIsStructuredDataEvent(event): + self.handle_structured_data_event(event) + else: + if self.trace_on: + print("ignoring unexpected event:", + lldbutil.get_description(event)) + # Grab the next event, if there is one. + event.Clear() + if not self.listener.GetNextEvent(event): + if self.trace_on: + print("listener has no more events " + "available at this time") + else: + if self.trace_on: + print("timeout occurred waiting for event...") + timeout_count += 1 + self.listener.Clear() + except Exception as e: + self.exception = e + + def setUp(self): + # Call super's setUp(). + super(DarwinLogEventBasedTestBase, self).setUp() + + # Until other systems support this, exit + # early if we're not macOS version 10.12 + # or greater. + version = platform.mac_ver()[0].split('.') + if ((int(version[0]) == 10) and (int(version[1]) < 12) or + (int(version[0]) < 10)): + self.skipTest("DarwinLog tests currently require macOS 10.12+") + return + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = 'a.out' + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + # Enable debugserver logging of the darwin log collection + # mechanism. + self.runCmd("settings set target.process.extra-startup-command " + "QSetLogging:bitmask=LOG_DARWIN_LOG;") + + def darwin_log_available(self): + match = self.match("plugin structured-data darwin-log status", + patterns=[r"Availability: ([\S]+)"]) + return match is not None and (match.group(1) == "available") + + def do_test(self, enable_options, settings_commands=None, + run_enable_after_breakpoint=False, max_entry_count=None): + """Runs the test inferior, returning collected events. + + This method runs the test inferior to the first breakpoint hit. + It then adds a listener for structured data events, and collects + all events from that point forward until end of execution of the + test inferior. It then returns those events. + + @return + A list of structured data events received, in the order they + were received. + """ + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, lldbtest.VALID_TARGET) + + # Run the darwin-log settings commands. + if settings_commands is not None: + for setting_command in settings_commands: + self.runCmd( + expand_darwinlog_settings_set_command(setting_command)) + + # Build the darwin-log enable command. + enable_cmd = expand_darwinlog_command("enable") + if enable_options is not None and len(enable_options) > 0: + enable_cmd += ' ' + ' '.join(enable_options) + + # Run the darwin-log enable command now if we are not supposed + # to do it at the first breakpoint. This tests the start-up + # code, which has the benefit of being able to set os_log-related + # environment variables. + if not run_enable_after_breakpoint: + self.runCmd(enable_cmd) + + # Create the breakpoint. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertIsNotNone(breakpoint) + self.assertTrue(breakpoint.IsValid()) + self.assertEqual(1, breakpoint.GetNumLocations(), + "Should have found one breakpoint") + + # Enable packet logging. + # self.runCmd("log enable -f /tmp/packets.log gdb-remote packets") + # self.runCmd("log enable lldb process") + + # Launch the process - doesn't stop at entry. + process = target.LaunchSimple(None, None, self.getBuildDir()) + self.assertIsNotNone(process, lldbtest.PROCESS_IS_VALID) + + # Keep track of whether we're tracing output. + trace_on = self.TraceOn() + + # Get the next thread that stops. + from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + + self.assertIsNotNone(thread, "There should be a thread stopped " + "due to breakpoint") + + # The process should be stopped at this point. + self.expect("process status", lldbtest.PROCESS_STOPPED, + patterns=['Process .* stopped']) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", lldbtest.STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # And our one and only breakpoint should have been hit. + self.assertEquals(breakpoint.GetHitCount(), 1) + + # Check if DarwinLog is available. This check cannot be done + # until after the process has started, as the feature availability + # comes through the stub. The stub isn't running until + # the target process is running. So this is really the earliest + # we can check. + if not self.darwin_log_available(): + self.skipTest("DarwinLog not available") + + # Now setup the structured data listener. + # + # Grab the broadcaster for the process. We'll be attaching our + # listener to it. + broadcaster = process.GetBroadcaster() + self.assertIsNotNone(broadcaster) + + listener = lldb.SBListener("SBStructuredData listener") + self.assertIsNotNone(listener) + + rc = broadcaster.AddListener( + listener, lldb.SBProcess.eBroadcastBitStructuredData) + self.assertTrue(rc, "Successfully add listener to process broadcaster") + + # Start the listening thread to retrieve the events. + # Bump up max entry count for the potentially included Add Mode: + # entry. + if max_entry_count is not None: + max_entry_count += 1 + event_thread = self.EventListenerThread(listener, process, trace_on, + max_entry_count) + event_thread.start() + + # Continue the test inferior. We should get any events after this. + process.Continue() + + # Wait until the event thread terminates. + # print("main thread now waiting for event thread to receive events.") + event_thread.join() + + # If the process is still alive, we kill it here. + if process.is_alive: + process.Kill() + + # Fail on any exceptions that occurred during event execution. + if event_thread.exception is not None: + # Re-raise it here so it shows up as a test error. + raise event_thread + + # Return the collected logging events. + return remove_add_mode_entry(event_thread.log_entries) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/decorators.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/decorators.py new file mode 100644 index 00000000000..ec17cb7c256 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/decorators.py @@ -0,0 +1,848 @@ +from __future__ import absolute_import + +# System modules +from distutils.version import LooseVersion +from functools import wraps +import os +import platform +import re +import sys +import tempfile +import subprocess + +# Third-party modules +import six +import unittest2 + +# LLDB modules +import lldb +from . import configuration +from . import test_categories +from . import lldbtest_config +from lldbsuite.test_event.event_builder import EventBuilder +from lldbsuite.support import funcutils +from lldbsuite.test import lldbplatform +from lldbsuite.test import lldbplatformutil + + +class DecorateMode: + Skip, Xfail = range(2) + + +# You can use no_match to reverse the test of the conditional that is used to match keyword +# arguments in the skip / xfail decorators. If oslist=["windows", "linux"] skips windows +# and linux, oslist=no_match(["windows", "linux"]) skips *unless* windows +# or linux. +class no_match: + + def __init__(self, item): + self.item = item + + +def _check_expected_version(comparison, expected, actual): + def fn_leq(x, y): return x <= y + + def fn_less(x, y): return x < y + + def fn_geq(x, y): return x >= y + + def fn_greater(x, y): return x > y + + def fn_eq(x, y): return x == y + + def fn_neq(x, y): return x != y + + op_lookup = { + "==": fn_eq, + "=": fn_eq, + "!=": fn_neq, + "<>": fn_neq, + ">": fn_greater, + "<": fn_less, + ">=": fn_geq, + "<=": fn_leq + } + expected_str = '.'.join([str(x) for x in expected]) + actual_str = '.'.join([str(x) for x in actual]) + + return op_lookup[comparison]( + LooseVersion(actual_str), + LooseVersion(expected_str)) + + +_re_pattern_type = type(re.compile('')) +def _match_decorator_property(expected, actual): + if actual is None or expected is None: + return True + + if isinstance(expected, no_match): + return not _match_decorator_property(expected.item, actual) + elif isinstance(expected, (_re_pattern_type,) + six.string_types): + return re.search(expected, actual) is not None + elif hasattr(expected, "__iter__"): + return any([x is not None and _match_decorator_property(x, actual) + for x in expected]) + else: + return expected == actual + + +def expectedFailure(expected_fn, bugnumber=None): + def expectedFailure_impl(func): + if isinstance(func, type) and issubclass(func, unittest2.TestCase): + raise Exception( + "Decorator can only be used to decorate a test method") + + @wraps(func) + def wrapper(*args, **kwargs): + self = args[0] + if funcutils.requires_self(expected_fn): + xfail_reason = expected_fn(self) + else: + xfail_reason = expected_fn() + if xfail_reason is not None: + if configuration.results_formatter_object is not None: + # Mark this test as expected to fail. + configuration.results_formatter_object.handle_event( + EventBuilder.event_for_mark_test_expected_failure(self)) + xfail_func = unittest2.expectedFailure(func) + xfail_func(*args, **kwargs) + else: + func(*args, **kwargs) + return wrapper + # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows) + # or with arguments (e.g. @expectedFailureWindows(compilers=['gcc'])). When called + # the first way, the first argument will be the actual function because decorators are + # weird like that. So this is basically a check that says "which syntax was the original + # function decorated with?" + if six.callable(bugnumber): + return expectedFailure_impl(bugnumber) + else: + return expectedFailure_impl + + +def skipTestIfFn(expected_fn, bugnumber=None): + def skipTestIfFn_impl(func): + if isinstance(func, type) and issubclass(func, unittest2.TestCase): + raise Exception( + "@skipTestIfFn can only be used to decorate a test method") + + @wraps(func) + def wrapper(*args, **kwargs): + self = args[0] + if funcutils.requires_self(expected_fn): + reason = expected_fn(self) + else: + reason = expected_fn() + + if reason is not None: + self.skipTest(reason) + else: + func(*args, **kwargs) + return wrapper + + # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows) + # or with arguments (e.g. @expectedFailureWindows(compilers=['gcc'])). When called + # the first way, the first argument will be the actual function because decorators are + # weird like that. So this is basically a check that says "how was the + # decorator used" + if six.callable(bugnumber): + return skipTestIfFn_impl(bugnumber) + else: + return skipTestIfFn_impl + + +def _decorateTest(mode, + bugnumber=None, oslist=None, hostoslist=None, + compiler=None, compiler_version=None, + archs=None, triple=None, + debug_info=None, + swig_version=None, py_version=None, + macos_version=None, + remote=None, dwarf_version=None): + def fn(self): + skip_for_os = _match_decorator_property( + lldbplatform.translate(oslist), self.getPlatform()) + skip_for_hostos = _match_decorator_property( + lldbplatform.translate(hostoslist), + lldbplatformutil.getHostPlatform()) + skip_for_compiler = _match_decorator_property( + compiler, self.getCompiler()) and self.expectedCompilerVersion(compiler_version) + skip_for_arch = _match_decorator_property( + archs, self.getArchitecture()) + skip_for_debug_info = _match_decorator_property( + debug_info, self.getDebugInfo()) + skip_for_triple = _match_decorator_property( + triple, lldb.DBG.GetSelectedPlatform().GetTriple()) + skip_for_remote = _match_decorator_property( + remote, lldb.remote_platform is not None) + + skip_for_swig_version = ( + swig_version is None) or ( + not hasattr( + lldb, + 'swig_version')) or ( + _check_expected_version( + swig_version[0], + swig_version[1], + lldb.swig_version)) + skip_for_py_version = ( + py_version is None) or _check_expected_version( + py_version[0], py_version[1], sys.version_info) + skip_for_macos_version = (macos_version is None) or ( + (platform.mac_ver()[0] != "") and (_check_expected_version( + macos_version[0], + macos_version[1], + platform.mac_ver()[0]))) + skip_for_dwarf_version = (dwarf_version is None) or ( + _check_expected_version(dwarf_version[0], dwarf_version[1], + self.getDwarfVersion())) + + # For the test to be skipped, all specified (e.g. not None) parameters must be True. + # An unspecified parameter means "any", so those are marked skip by default. And we skip + # the final test if all conditions are True. + conditions = [(oslist, skip_for_os, "target o/s"), + (hostoslist, skip_for_hostos, "host o/s"), + (compiler, skip_for_compiler, "compiler or version"), + (archs, skip_for_arch, "architecture"), + (debug_info, skip_for_debug_info, "debug info format"), + (triple, skip_for_triple, "target triple"), + (swig_version, skip_for_swig_version, "swig version"), + (py_version, skip_for_py_version, "python version"), + (macos_version, skip_for_macos_version, "macOS version"), + (remote, skip_for_remote, "platform locality (remote/local)"), + (dwarf_version, skip_for_dwarf_version, "dwarf version")] + reasons = [] + final_skip_result = True + for this_condition in conditions: + final_skip_result = final_skip_result and this_condition[1] + if this_condition[0] is not None and this_condition[1]: + reasons.append(this_condition[2]) + reason_str = None + if final_skip_result: + mode_str = { + DecorateMode.Skip: "skipping", + DecorateMode.Xfail: "xfailing"}[mode] + if len(reasons) > 0: + reason_str = ",".join(reasons) + reason_str = "{} due to the following parameter(s): {}".format( + mode_str, reason_str) + else: + reason_str = "{} unconditionally" + if bugnumber is not None and not six.callable(bugnumber): + reason_str = reason_str + " [" + str(bugnumber) + "]" + return reason_str + + if mode == DecorateMode.Skip: + return skipTestIfFn(fn, bugnumber) + elif mode == DecorateMode.Xfail: + return expectedFailure(fn, bugnumber) + else: + return None + +# provide a function to xfail on defined oslist, compiler version, and archs +# if none is specified for any argument, that argument won't be checked and thus means for all +# for example, +# @expectedFailureAll, xfail for all platform/compiler/arch, +# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture +# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386 + + +def expectedFailureAll(bugnumber=None, + oslist=None, hostoslist=None, + compiler=None, compiler_version=None, + archs=None, triple=None, + debug_info=None, + swig_version=None, py_version=None, + macos_version=None, + remote=None, dwarf_version=None): + return _decorateTest(DecorateMode.Xfail, + bugnumber=bugnumber, + oslist=oslist, hostoslist=hostoslist, + compiler=compiler, compiler_version=compiler_version, + archs=archs, triple=triple, + debug_info=debug_info, + swig_version=swig_version, py_version=py_version, + macos_version=None, + remote=remote,dwarf_version=dwarf_version) + + +# provide a function to skip on defined oslist, compiler version, and archs +# if none is specified for any argument, that argument won't be checked and thus means for all +# for example, +# @skipIf, skip for all platform/compiler/arch, +# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture +# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386 +def skipIf(bugnumber=None, + oslist=None, hostoslist=None, + compiler=None, compiler_version=None, + archs=None, triple=None, + debug_info=None, + swig_version=None, py_version=None, + macos_version=None, + remote=None, dwarf_version=None): + return _decorateTest(DecorateMode.Skip, + bugnumber=bugnumber, + oslist=oslist, hostoslist=hostoslist, + compiler=compiler, compiler_version=compiler_version, + archs=archs, triple=triple, + debug_info=debug_info, + swig_version=swig_version, py_version=py_version, + macos_version=macos_version, + remote=remote, dwarf_version=dwarf_version) + + +def _skip_for_android(reason, api_levels, archs): + def impl(obj): + result = lldbplatformutil.match_android_device( + obj.getArchitecture(), valid_archs=archs, valid_api_levels=api_levels) + return reason if result else None + return impl + + +def add_test_categories(cat): + """Add test categories to a TestCase method""" + cat = test_categories.validate(cat, True) + + def impl(func): + if isinstance(func, type) and issubclass(func, unittest2.TestCase): + raise Exception( + "@add_test_categories can only be used to decorate a test method") + try: + if hasattr(func, "categories"): + cat.extend(func.categories) + setattr(func, "categories", cat) + except AttributeError: + raise Exception('Cannot assign categories to inline tests.') + + return func + + return impl + + +def benchmarks_test(func): + """Decorate the item as a benchmarks test.""" + def should_skip_benchmarks_test(): + return "benchmarks test" + + # Mark this function as such to separate them from the regular tests. + result = skipTestIfFn(should_skip_benchmarks_test)(func) + result.__benchmarks_test__ = True + return result + + +def no_debug_info_test(func): + """Decorate the item as a test what don't use any debug info. If this annotation is specified + then the test runner won't generate a separate test for each debug info format. """ + if isinstance(func, type) and issubclass(func, unittest2.TestCase): + raise Exception( + "@no_debug_info_test can only be used to decorate a test method") + + @wraps(func) + def wrapper(self, *args, **kwargs): + return func(self, *args, **kwargs) + + # Mark this function as such to separate them from the regular tests. + wrapper.__no_debug_info_test__ = True + return wrapper + +def apple_simulator_test(platform): + """ + Decorate the test as a test requiring a simulator for a specific platform. + + Consider that a simulator is available if you have the corresponding SDK installed. + The SDK identifiers for simulators are iphonesimulator, appletvsimulator, watchsimulator + """ + def should_skip_simulator_test(): + if lldbplatformutil.getHostPlatform() != 'darwin': + return "simulator tests are run only on darwin hosts" + try: + DEVNULL = open(os.devnull, 'w') + output = subprocess.check_output(["xcodebuild", "-showsdks"], stderr=DEVNULL).decode("utf-8") + if re.search('%ssimulator' % platform, output): + return None + else: + return "%s simulator is not supported on this system." % platform + except subprocess.CalledProcessError: + return "Simulators are unsupported on this system (xcodebuild failed)" + + return skipTestIfFn(should_skip_simulator_test) + + +def debugserver_test(func): + """Decorate the item as a debugserver test.""" + def should_skip_debugserver_test(): + return "debugserver tests" if configuration.dont_do_debugserver_test else None + return skipTestIfFn(should_skip_debugserver_test)(func) + + +def llgs_test(func): + """Decorate the item as a lldb-server test.""" + def should_skip_llgs_tests(): + return "llgs tests" if configuration.dont_do_llgs_test else None + return skipTestIfFn(should_skip_llgs_tests)(func) + + +def not_remote_testsuite_ready(func): + """Decorate the item as a test which is not ready yet for remote testsuite.""" + def is_remote(): + return "Not ready for remote testsuite" if lldb.remote_platform else None + return skipTestIfFn(is_remote)(func) + + +def expectedFailureOS( + oslist, + bugnumber=None, + compilers=None, + debug_info=None, + archs=None): + return expectedFailureAll( + oslist=oslist, + bugnumber=bugnumber, + compiler=compilers, + archs=archs, + debug_info=debug_info) + + +def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None): + # For legacy reasons, we support both "darwin" and "macosx" as OS X + # triples. + return expectedFailureOS( + lldbplatform.darwin_all, + bugnumber, + compilers, + debug_info=debug_info) + + +def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None): + """ Mark a test as xfail for Android. + + Arguments: + bugnumber - The LLVM pr associated with the problem. + api_levels - A sequence of numbers specifying the Android API levels + for which a test is expected to fail. None means all API level. + arch - A sequence of architecture names specifying the architectures + for which a test is expected to fail. None means all architectures. + """ + return expectedFailure( + _skip_for_android( + "xfailing on android", + api_levels, + archs), + bugnumber) + + +def expectedFailureNetBSD(bugnumber=None): + return expectedFailureOS( + ['netbsd'], + bugnumber) + +# Flakey tests get two chances to run. If they fail the first time round, the result formatter +# makes sure it is run one more time. + + +def expectedFlakey(expected_fn, bugnumber=None): + def expectedFailure_impl(func): + @wraps(func) + def wrapper(*args, **kwargs): + self = args[0] + if expected_fn(self): + # Send event marking test as explicitly eligible for rerunning. + if configuration.results_formatter_object is not None: + # Mark this test as rerunnable. + configuration.results_formatter_object.handle_event( + EventBuilder.event_for_mark_test_rerun_eligible(self)) + func(*args, **kwargs) + return wrapper + # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows) + # or with arguments (e.g. @expectedFailureWindows(compilers=['gcc'])). When called + # the first way, the first argument will be the actual function because decorators are + # weird like that. So this is basically a check that says "which syntax was the original + # function decorated with?" + if six.callable(bugnumber): + return expectedFailure_impl(bugnumber) + else: + return expectedFailure_impl + + +def expectedFlakeyOS(oslist, bugnumber=None, compilers=None): + def fn(self): + return (self.getPlatform() in oslist and + self.expectedCompiler(compilers)) + return expectedFlakey(fn, bugnumber) + + +def expectedFlakeyDarwin(bugnumber=None, compilers=None): + # For legacy reasons, we support both "darwin" and "macosx" as OS X + # triples. + return expectedFlakeyOS( + lldbplatformutil.getDarwinOSTriples(), + bugnumber, + compilers) + + +def expectedFlakeyFreeBSD(bugnumber=None, compilers=None): + return expectedFlakeyOS(['freebsd'], bugnumber, compilers) + + +def expectedFlakeyLinux(bugnumber=None, compilers=None): + return expectedFlakeyOS(['linux'], bugnumber, compilers) + + +def expectedFlakeyNetBSD(bugnumber=None, compilers=None): + return expectedFlakeyOS(['netbsd'], bugnumber, compilers) + + +def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None): + return expectedFlakey( + _skip_for_android( + "flakey on android", + api_levels, + archs), + bugnumber) + +def skipIfOutOfTreeDebugserver(func): + """Decorate the item to skip tests if using an out-of-tree debugserver.""" + def is_out_of_tree_debugserver(): + return "out-of-tree debugserver" if lldbtest_config.out_of_tree_debugserver else None + return skipTestIfFn(is_out_of_tree_debugserver)(func) + +def skipIfRemote(func): + """Decorate the item to skip tests if testing remotely.""" + def is_remote(): + return "skip on remote platform" if lldb.remote_platform else None + return skipTestIfFn(is_remote)(func) + + +def skipIfNoSBHeaders(func): + """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers.""" + def are_sb_headers_missing(): + if lldb.remote_platform: + return "skip because SBHeaders tests make no sense remotely" + + if lldbplatformutil.getHostPlatform() == 'darwin': + header = os.path.join( + os.environ["LLDB_LIB_DIR"], + 'LLDB.framework', + 'Versions', + 'Current', + 'Headers', + 'LLDB.h') + if os.path.exists(header): + return None + + header = os.path.join( + os.environ["LLDB_SRC"], + "include", + "lldb", + "API", + "LLDB.h") + if not os.path.exists(header): + return "skip because LLDB.h header not found" + return None + + return skipTestIfFn(are_sb_headers_missing)(func) + + +def skipIfiOSSimulator(func): + """Decorate the item to skip tests that should be skipped on the iOS Simulator.""" + def is_ios_simulator(): + return "skip on the iOS Simulator" if configuration.lldb_platform_name == 'ios-simulator' else None + return skipTestIfFn(is_ios_simulator)(func) + +def skipIfiOS(func): + return skipIfPlatform(["ios"])(func) + +def skipIftvOS(func): + return skipIfPlatform(["tvos"])(func) + +def skipIfwatchOS(func): + return skipIfPlatform(["watchos"])(func) + +def skipIfbridgeOS(func): + return skipIfPlatform(["bridgeos"])(func) + +def skipIfDarwinEmbedded(func): + """Decorate the item to skip tests that should be skipped on Darwin armv7/arm64 targets.""" + return skipIfPlatform( + lldbplatform.translate( + lldbplatform.darwin_embedded))(func) + +def skipIfFreeBSD(func): + """Decorate the item to skip tests that should be skipped on FreeBSD.""" + return skipIfPlatform(["freebsd"])(func) + + +def skipIfNetBSD(func): + """Decorate the item to skip tests that should be skipped on NetBSD.""" + return skipIfPlatform(["netbsd"])(func) + + +def skipIfDarwin(func): + """Decorate the item to skip tests that should be skipped on Darwin.""" + return skipIfPlatform( + lldbplatform.translate( + lldbplatform.darwin_all))(func) + + +def skipIfLinux(func): + """Decorate the item to skip tests that should be skipped on Linux.""" + return skipIfPlatform(["linux"])(func) + + +def skipIfWindows(func): + """Decorate the item to skip tests that should be skipped on Windows.""" + return skipIfPlatform(["windows"])(func) + +def skipUnlessWindows(func): + """Decorate the item to skip tests that should be skipped on any non-Windows platform.""" + return skipUnlessPlatform(["windows"])(func) + + +def skipUnlessDarwin(func): + """Decorate the item to skip tests that should be skipped on any non Darwin platform.""" + return skipUnlessPlatform(lldbplatformutil.getDarwinOSTriples())(func) + +def skipUnlessTargetAndroid(func): + return unittest2.skipUnless(lldbplatformutil.target_is_android(), + "requires target to be Android")(func) + + +def skipIfHostIncompatibleWithRemote(func): + """Decorate the item to skip tests if binaries built on this host are incompatible.""" + + def is_host_incompatible_with_remote(self): + host_arch = self.getLldbArchitecture() + host_platform = lldbplatformutil.getHostPlatform() + target_arch = self.getArchitecture() + target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform() + if not (target_arch == 'x86_64' and host_arch == + 'i386') and host_arch != target_arch: + return "skipping because target %s is not compatible with host architecture %s" % ( + target_arch, host_arch) + if target_platform != host_platform: + return "skipping because target is %s but host is %s" % ( + target_platform, host_platform) + if lldbplatformutil.match_android_device(target_arch): + return "skipping because target is android" + return None + return skipTestIfFn(is_host_incompatible_with_remote)(func) + + +def skipIfPlatform(oslist): + """Decorate the item to skip tests if running on one of the listed platforms.""" + # This decorator cannot be ported to `skipIf` yet because it is used on entire + # classes, which `skipIf` explicitly forbids. + return unittest2.skipIf(lldbplatformutil.getPlatform() in oslist, + "skip on %s" % (", ".join(oslist))) + + +def skipUnlessPlatform(oslist): + """Decorate the item to skip tests unless running on one of the listed platforms.""" + # This decorator cannot be ported to `skipIf` yet because it is used on entire + # classes, which `skipIf` explicitly forbids. + return unittest2.skipUnless(lldbplatformutil.getPlatform() in oslist, + "requires one of %s" % (", ".join(oslist))) + +def skipUnlessArch(arch): + """Decorate the item to skip tests unless running on the specified architecture.""" + + def arch_doesnt_match(self): + target_arch = self.getArchitecture() + if arch != target_arch: + return "Test only runs on " + arch + ", but target arch is " + target_arch + return None + + return skipTestIfFn(arch_doesnt_match) + +def skipIfTargetAndroid(bugnumber=None, api_levels=None, archs=None): + """Decorator to skip tests when the target is Android. + + Arguments: + api_levels - The API levels for which the test should be skipped. If + it is None, then the test will be skipped for all API levels. + arch - A sequence of architecture names specifying the architectures + for which a test is skipped. None means all architectures. + """ + return skipTestIfFn( + _skip_for_android( + "skipping for android", + api_levels, + archs), + bugnumber) + +def skipUnlessSupportedTypeAttribute(attr): + """Decorate the item to skip test unless Clang supports type __attribute__(attr).""" + def compiler_doesnt_support_struct_attribute(self): + compiler_path = self.getCompiler() + f = tempfile.NamedTemporaryFile() + cmd = [self.getCompiler(), "-x", "c++", "-c", "-o", f.name, "-"] + p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) + stdout, stderr = p.communicate('struct __attribute__((%s)) Test {};'%attr) + if attr in stderr: + return "Compiler does not support attribute %s"%(attr) + return None + return skipTestIfFn(compiler_doesnt_support_struct_attribute) + +def skipUnlessHasCallSiteInfo(func): + """Decorate the function to skip testing unless call site info from clang is available.""" + + def is_compiler_clang_with_call_site_info(self): + compiler_path = self.getCompiler() + compiler = os.path.basename(compiler_path) + if not compiler.startswith("clang"): + return "Test requires clang as compiler" + + f = tempfile.NamedTemporaryFile() + cmd = "echo 'int main() {}' | " \ + "%s -g -glldb -O1 -Xclang -femit-debug-entry-values -S -emit-llvm -x c -o %s -" % (compiler_path, f.name) + if os.popen(cmd).close() is not None: + return "Compiler can't compile with call site info enabled" + + with open(f.name, 'r') as ir_output_file: + buf = ir_output_file.read() + + if 'DIFlagAllCallsDescribed' not in buf: + return "Compiler did not introduce DIFlagAllCallsDescribed IR flag" + + return None + return skipTestIfFn(is_compiler_clang_with_call_site_info)(func) + +def skipUnlessThreadSanitizer(func): + """Decorate the item to skip test unless Clang -fsanitize=thread is supported.""" + + def is_compiler_clang_with_thread_sanitizer(self): + compiler_path = self.getCompiler() + compiler = os.path.basename(compiler_path) + if not compiler.startswith("clang"): + return "Test requires clang as compiler" + if lldbplatformutil.getPlatform() == 'windows': + return "TSAN tests not compatible with 'windows'" + # rdar://28659145 - TSAN tests don't look like they're supported on i386 + if self.getArchitecture() == 'i386' and platform.system() == 'Darwin': + return "TSAN tests not compatible with i386 targets" + f = tempfile.NamedTemporaryFile() + cmd = "echo 'int main() {}' | %s -x c -o %s -" % (compiler_path, f.name) + if os.popen(cmd).close() is not None: + return None # The compiler cannot compile at all, let's *not* skip the test + cmd = "echo 'int main() {}' | %s -fsanitize=thread -x c -o %s -" % (compiler_path, f.name) + if os.popen(cmd).close() is not None: + return "Compiler cannot compile with -fsanitize=thread" + return None + return skipTestIfFn(is_compiler_clang_with_thread_sanitizer)(func) + +def skipUnlessUndefinedBehaviorSanitizer(func): + """Decorate the item to skip test unless -fsanitize=undefined is supported.""" + + def is_compiler_clang_with_ubsan(self): + # Write out a temp file which exhibits UB. + inputf = tempfile.NamedTemporaryFile(suffix='.c', mode='w') + inputf.write('int main() { int x = 0; return x / x; }\n') + inputf.flush() + + # We need to write out the object into a named temp file for inspection. + outputf = tempfile.NamedTemporaryFile() + + # Try to compile with ubsan turned on. + cmd = '%s -fsanitize=undefined %s -o %s' % (self.getCompiler(), inputf.name, outputf.name) + if os.popen(cmd).close() is not None: + return "Compiler cannot compile with -fsanitize=undefined" + + # Check that we actually see ubsan instrumentation in the binary. + cmd = 'nm %s' % outputf.name + with os.popen(cmd) as nm_output: + if '___ubsan_handle_divrem_overflow' not in nm_output.read(): + return "Division by zero instrumentation is missing" + + # Find the ubsan dylib. + # FIXME: This check should go away once compiler-rt gains support for __ubsan_on_report. + cmd = '%s -fsanitize=undefined -x c - -o - -### 2>&1' % self.getCompiler() + with os.popen(cmd) as cc_output: + driver_jobs = cc_output.read() + m = re.search(r'"([^"]+libclang_rt.ubsan_osx_dynamic.dylib)"', driver_jobs) + if not m: + return "Could not find the ubsan dylib used by the driver" + ubsan_dylib = m.group(1) + + # Check that the ubsan dylib has special monitor hooks. + cmd = 'nm -gU %s' % ubsan_dylib + with os.popen(cmd) as nm_output: + syms = nm_output.read() + if '___ubsan_on_report' not in syms: + return "Missing ___ubsan_on_report" + if '___ubsan_get_current_report_data' not in syms: + return "Missing ___ubsan_get_current_report_data" + + # OK, this dylib + compiler works for us. + return None + + return skipTestIfFn(is_compiler_clang_with_ubsan)(func) + +def skipUnlessAddressSanitizer(func): + """Decorate the item to skip test unless Clang -fsanitize=thread is supported.""" + + def is_compiler_with_address_sanitizer(self): + compiler_path = self.getCompiler() + compiler = os.path.basename(compiler_path) + f = tempfile.NamedTemporaryFile() + if lldbplatformutil.getPlatform() == 'windows': + return "ASAN tests not compatible with 'windows'" + cmd = "echo 'int main() {}' | %s -x c -o %s -" % (compiler_path, f.name) + if os.popen(cmd).close() is not None: + return None # The compiler cannot compile at all, let's *not* skip the test + cmd = "echo 'int main() {}' | %s -fsanitize=address -x c -o %s -" % (compiler_path, f.name) + if os.popen(cmd).close() is not None: + return "Compiler cannot compile with -fsanitize=address" + return None + return skipTestIfFn(is_compiler_with_address_sanitizer)(func) + +def _get_bool_config_skip_if_decorator(key): + config = lldb.SBDebugger.GetBuildConfiguration() + value_node = config.GetValueForKey(key) + fail_value = True # More likely to notice if something goes wrong + have = value_node.GetValueForKey("value").GetBooleanValue(fail_value) + return unittest2.skipIf(not have, "requires " + key) + +def skipIfCursesSupportMissing(func): + return _get_bool_config_skip_if_decorator("curses")(func) + +def skipIfXmlSupportMissing(func): + return _get_bool_config_skip_if_decorator("xml")(func) + +def skipIfEditlineSupportMissing(func): + return _get_bool_config_skip_if_decorator("editline")(func) + +def skipIfLLVMTargetMissing(target): + config = lldb.SBDebugger.GetBuildConfiguration() + targets = config.GetValueForKey("targets").GetValueForKey("value") + found = False + for i in range(targets.GetSize()): + if targets.GetItemAtIndex(i).GetStringValue(99) == target: + found = True + break + + return unittest2.skipIf(not found, "requires " + target) + +# Call sysctl on darwin to see if a specified hardware feature is available on this machine. +def skipUnlessFeature(feature): + def is_feature_enabled(self): + if platform.system() == 'Darwin': + try: + DEVNULL = open(os.devnull, 'w') + output = subprocess.check_output(["/usr/sbin/sysctl", feature], stderr=DEVNULL).decode("utf-8") + # If 'feature: 1' was output, then this feature is available and + # the test should not be skipped. + if re.match('%s: 1\s*' % feature, output): + return None + else: + return "%s is not supported on this system." % feature + except subprocess.CalledProcessError: + return "%s is not supported on this system." % feature + return skipTestIfFn(is_feature_enabled) + +def skipIfAsan(func): + """Skip this test if the environment is set up to run LLDB itself under ASAN.""" + def is_asan(): + if ('ASAN_OPTIONS' in os.environ): + return "ASAN unsupported" + return None + return skipTestIfFn(is_asan)(func) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/dotest.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/dotest.py new file mode 100644 index 00000000000..560e47dc58d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/dotest.py @@ -0,0 +1,1154 @@ +""" +A simple testing framework for lldb using python's unit testing framework. + +Tests for lldb are written as python scripts which take advantage of the script +bridging provided by LLDB.framework to interact with lldb core. + +A specific naming pattern is followed by the .py script to be recognized as +a module which implements a test scenario, namely, Test*.py. + +To specify the directories where "Test*.py" python test scripts are located, +you need to pass in a list of directory names. By default, the current +working directory is searched if nothing is specified on the command line. + +Type: + +./dotest.py -h + +for available options. +""" + +from __future__ import absolute_import +from __future__ import print_function + +# System modules +import atexit +import datetime +import errno +import logging +import os +import platform +import re +import signal +import subprocess +import sys +import tempfile + +# Third-party modules +import six +import unittest2 + +# LLDB Modules +import lldbsuite +from . import configuration +from . import dotest_args +from . import lldbtest_config +from . import test_categories +from lldbsuite.test_event import formatter +from . import test_result +from lldbsuite.test_event.event_builder import EventBuilder +from ..support import seven + +def get_dotest_invocation(): + return ' '.join(sys.argv) + + +def is_exe(fpath): + """Returns true if fpath is an executable.""" + if fpath == None: + return False + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + +def which(program): + """Returns the full path to a program; None otherwise.""" + fpath, _ = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ["PATH"].split(os.pathsep): + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + return None + + +def usage(parser): + parser.print_help() + if configuration.verbose > 0: + print(""" +Examples: + +This is an example of using the -f option to pinpoint to a specific test class +and test method to be run: + +$ ./dotest.py -f ClassTypesTestCase.test_with_dsym_and_run_command +---------------------------------------------------------------------- +Collected 1 test + +test_with_dsym_and_run_command (TestClassTypes.ClassTypesTestCase) +Test 'frame variable this' when stopped on a class constructor. ... ok + +---------------------------------------------------------------------- +Ran 1 test in 1.396s + +OK + +And this is an example of using the -p option to run a single file (the filename +matches the pattern 'ObjC' and it happens to be 'TestObjCMethods.py'): + +$ ./dotest.py -v -p ObjC +---------------------------------------------------------------------- +Collected 4 tests + +test_break_with_dsym (TestObjCMethods.FoundationTestCase) +Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok +test_break_with_dwarf (TestObjCMethods.FoundationTestCase) +Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok +test_data_type_and_expr_with_dsym (TestObjCMethods.FoundationTestCase) +Lookup objective-c data types and evaluate expressions. ... ok +test_data_type_and_expr_with_dwarf (TestObjCMethods.FoundationTestCase) +Lookup objective-c data types and evaluate expressions. ... ok + +---------------------------------------------------------------------- +Ran 4 tests in 16.661s + +OK + +Running of this script also sets up the LLDB_TEST environment variable so that +individual test cases can locate their supporting files correctly. The script +tries to set up Python's search paths for modules by looking at the build tree +relative to this script. See also the '-i' option in the following example. + +Finally, this is an example of using the lldb.py module distributed/installed by +Xcode4 to run against the tests under the 'forward' directory, and with the '-w' +option to add some delay between two tests. It uses ARCH=x86_64 to specify that +as the architecture and CC=clang to specify the compiler used for the test run: + +$ PYTHONPATH=/Xcode4/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python ARCH=x86_64 CC=clang ./dotest.py -v -w -i forward + +Session logs for test failures/errors will go into directory '2010-11-11-13_56_16' +---------------------------------------------------------------------- +Collected 2 tests + +test_with_dsym_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase) +Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok +test_with_dwarf_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase) +Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok + +---------------------------------------------------------------------- +Ran 2 tests in 5.659s + +OK + +The 'Session ...' verbiage is recently introduced (see also the '-s' option) to +notify the directory containing the session logs for test failures or errors. +In case there is any test failure/error, a similar message is appended at the +end of the stderr output for your convenience. + +ENABLING LOGS FROM TESTS + +Option 1: + +Writing logs into different files per test case:: + +$ ./dotest.py --channel "lldb all" + +$ ./dotest.py --channel "lldb all" --channel "gdb-remote packets" + +These log files are written to: + +<session-dir>/<test-id>-host.log (logs from lldb host process) +<session-dir>/<test-id>-server.log (logs from debugserver/lldb-server) +<session-dir>/<test-id>-<test-result>.log (console logs) + +By default, logs from successful runs are deleted. Use the --log-success flag +to create reference logs for debugging. + +$ ./dotest.py --log-success + +""") + sys.exit(0) + + +def parseExclusion(exclusion_file): + """Parse an exclusion file, of the following format, where + 'skip files', 'skip methods', 'xfail files', and 'xfail methods' + are the possible list heading values: + + skip files + <file name> + <file name> + + xfail methods + <method name> + """ + excl_type = None + + with open(exclusion_file) as f: + for line in f: + line = line.strip() + if not excl_type: + excl_type = line + continue + + if not line: + excl_type = None + elif excl_type == 'skip': + if not configuration.skip_tests: + configuration.skip_tests = [] + configuration.skip_tests.append(line) + elif excl_type == 'xfail': + if not configuration.xfail_tests: + configuration.xfail_tests = [] + configuration.xfail_tests.append(line) + + +def parseOptionsAndInitTestdirs(): + """Initialize the list of directories containing our unittest scripts. + + '-h/--help as the first option prints out usage info and exit the program. + """ + + do_help = False + + platform_system = platform.system() + platform_machine = platform.machine() + + try: + parser = dotest_args.create_parser() + args = parser.parse_args() + except: + print(get_dotest_invocation()) + raise + + if args.unset_env_varnames: + for env_var in args.unset_env_varnames: + if env_var in os.environ: + # From Python Doc: When unsetenv() is supported, deletion of items in os.environ + # is automatically translated into a corresponding call to + # unsetenv(). + del os.environ[env_var] + # os.unsetenv(env_var) + + if args.set_env_vars: + for env_var in args.set_env_vars: + parts = env_var.split('=', 1) + if len(parts) == 1: + os.environ[parts[0]] = "" + else: + os.environ[parts[0]] = parts[1] + + if args.set_inferior_env_vars: + lldbtest_config.inferior_env = ' '.join(args.set_inferior_env_vars) + + # Only print the args if being verbose. + if args.v: + print(get_dotest_invocation()) + + if args.h: + do_help = True + + if args.compiler: + configuration.compiler = os.path.realpath(args.compiler) + if not is_exe(configuration.compiler): + configuration.compiler = which(args.compiler) + if not is_exe(configuration.compiler): + logging.error( + '%s is not a valid compiler executable; aborting...', + args.compiler) + sys.exit(-1) + else: + # Use a compiler appropriate appropriate for the Apple SDK if one was + # specified + if platform_system == 'Darwin' and args.apple_sdk: + configuration.compiler = seven.get_command_output( + 'xcrun -sdk "%s" -find clang 2> /dev/null' % + (args.apple_sdk)) + else: + # 'clang' on ubuntu 14.04 is 3.4 so we try clang-3.5 first + candidateCompilers = ['clang-3.5', 'clang', 'gcc'] + for candidate in candidateCompilers: + if which(candidate): + configuration.compiler = candidate + break + + if args.dsymutil: + os.environ['DSYMUTIL'] = args.dsymutil + elif platform_system == 'Darwin': + os.environ['DSYMUTIL'] = seven.get_command_output( + 'xcrun -find -toolchain default dsymutil') + + if args.filecheck: + # The lldb-dotest script produced by the CMake build passes in a path + # to a working FileCheck binary. So does one specific Xcode project + # target. However, when invoking dotest.py directly, a valid --filecheck + # option needs to be given. + configuration.filecheck = os.path.abspath(args.filecheck) + + if not configuration.get_filecheck_path(): + logging.warning('No valid FileCheck executable; some tests may fail...') + logging.warning('(Double-check the --filecheck argument to dotest.py)') + + if args.channels: + lldbtest_config.channels = args.channels + + if args.log_success: + lldbtest_config.log_success = args.log_success + + if args.out_of_tree_debugserver: + lldbtest_config.out_of_tree_debugserver = args.out_of_tree_debugserver + + # Set SDKROOT if we are using an Apple SDK + if platform_system == 'Darwin' and args.apple_sdk: + os.environ['SDKROOT'] = seven.get_command_output( + 'xcrun --sdk "%s" --show-sdk-path 2> /dev/null' % + (args.apple_sdk)) + + if args.arch: + configuration.arch = args.arch + if configuration.arch.startswith( + 'arm') and platform_system == 'Darwin' and not args.apple_sdk: + os.environ['SDKROOT'] = seven.get_command_output( + 'xcrun --sdk iphoneos.internal --show-sdk-path 2> /dev/null') + if not os.path.exists(os.environ['SDKROOT']): + os.environ['SDKROOT'] = seven.get_command_output( + 'xcrun --sdk iphoneos --show-sdk-path 2> /dev/null') + else: + configuration.arch = platform_machine + + if args.categories_list: + configuration.categories_list = set( + test_categories.validate( + args.categories_list, False)) + configuration.use_categories = True + else: + configuration.categories_list = [] + + if args.skip_categories: + configuration.skip_categories += test_categories.validate( + args.skip_categories, False) + + if args.xfail_categories: + configuration.xfail_categories += test_categories.validate( + args.xfail_categories, False) + + if args.E: + os.environ['CFLAGS_EXTRAS'] = args.E + + if args.dwarf_version: + configuration.dwarf_version = args.dwarf_version + # We cannot modify CFLAGS_EXTRAS because they're used in test cases + # that explicitly require no debug info. + os.environ['CFLAGS'] = '-gdwarf-{}'.format(configuration.dwarf_version) + + if args.settings: + for setting in args.settings: + if not len(setting) == 1 or not setting[0].count('='): + logging.error('"%s" is not a setting in the form "key=value"', + setting[0]) + sys.exit(-1) + configuration.settings.append(setting[0].split('=', 1)) + + if args.d: + sys.stdout.write( + "Suspending the process %d to wait for debugger to attach...\n" % + os.getpid()) + sys.stdout.flush() + os.kill(os.getpid(), signal.SIGSTOP) + + if args.f: + if any([x.startswith('-') for x in args.f]): + usage(parser) + configuration.filters.extend(args.f) + + if args.framework: + configuration.lldb_framework_path = args.framework + + if args.executable: + # lldb executable is passed explicitly + lldbtest_config.lldbExec = os.path.realpath(args.executable) + if not is_exe(lldbtest_config.lldbExec): + lldbtest_config.lldbExec = which(args.executable) + if not is_exe(lldbtest_config.lldbExec): + logging.error( + '%s is not a valid executable to test; aborting...', + args.executable) + sys.exit(-1) + + if args.server: + os.environ['LLDB_DEBUGSERVER_PATH'] = args.server + + if args.excluded: + for excl_file in args.excluded: + parseExclusion(excl_file) + + if args.p: + if args.p.startswith('-'): + usage(parser) + configuration.regexp = args.p + + if args.s: + configuration.sdir_name = args.s + else: + timestamp_started = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S") + configuration.sdir_name = os.path.join(os.getcwd(), timestamp_started) + + configuration.session_file_format = args.session_file_format + + if args.t: + os.environ['LLDB_COMMAND_TRACE'] = 'YES' + + if args.v: + configuration.verbose = 2 + + # argparse makes sure we have a number + if args.sharp: + configuration.count = args.sharp + + if sys.platform.startswith('win32'): + os.environ['LLDB_DISABLE_CRASH_DIALOG'] = str( + args.disable_crash_dialog) + os.environ['LLDB_LAUNCH_INFERIORS_WITHOUT_CONSOLE'] = str(True) + + if do_help: + usage(parser) + + if args.results_file: + configuration.results_filename = args.results_file + + if args.results_formatter: + configuration.results_formatter_name = args.results_formatter + if args.results_formatter_options: + configuration.results_formatter_options = args.results_formatter_options + + # Default to using the BasicResultsFormatter if no formatter is specified. + if configuration.results_formatter_name is None: + configuration.results_formatter_name = ( + "lldbsuite.test_event.formatter.results_formatter.ResultsFormatter") + + # rerun-related arguments + configuration.rerun_all_issues = args.rerun_all_issues + + if args.lldb_platform_name: + configuration.lldb_platform_name = args.lldb_platform_name + if args.lldb_platform_url: + configuration.lldb_platform_url = args.lldb_platform_url + if args.lldb_platform_working_dir: + configuration.lldb_platform_working_dir = args.lldb_platform_working_dir + if args.test_build_dir: + configuration.test_build_dir = args.test_build_dir + if args.lldb_module_cache_dir: + configuration.lldb_module_cache_dir = args.lldb_module_cache_dir + else: + configuration.lldb_module_cache_dir = os.path.join( + configuration.test_build_dir, 'module-cache-lldb') + if args.clang_module_cache_dir: + configuration.clang_module_cache_dir = args.clang_module_cache_dir + else: + configuration.clang_module_cache_dir = os.path.join( + configuration.test_build_dir, 'module-cache-clang') + + os.environ['CLANG_MODULE_CACHE_DIR'] = configuration.clang_module_cache_dir + + # Gather all the dirs passed on the command line. + if len(args.args) > 0: + configuration.testdirs = [os.path.realpath(os.path.abspath(x)) for x in args.args] + + lldbtest_config.codesign_identity = args.codesign_identity + + +def setupTestResults(): + """Sets up test results-related objects based on arg settings.""" + # Setup the results formatter configuration. + formatter_config = formatter.FormatterConfig() + formatter_config.filename = configuration.results_filename + formatter_config.formatter_name = configuration.results_formatter_name + formatter_config.formatter_options = ( + configuration.results_formatter_options) + + # Create the results formatter. + formatter_spec = formatter.create_results_formatter( + formatter_config) + if formatter_spec is not None and formatter_spec.formatter is not None: + configuration.results_formatter_object = formatter_spec.formatter + + # Send an initialize message to the formatter. + initialize_event = EventBuilder.bare_event("initialize") + initialize_event["worker_count"] = 1 + + formatter_spec.formatter.handle_event(initialize_event) + + # Make sure we clean up the formatter on shutdown. + if formatter_spec.cleanup_func is not None: + atexit.register(formatter_spec.cleanup_func) + + +def setupSysPath(): + """ + Add LLDB.framework/Resources/Python to the search paths for modules. + As a side effect, we also discover the 'lldb' executable and export it here. + """ + + # Get the directory containing the current script. + if "DOTEST_PROFILE" in os.environ and "DOTEST_SCRIPT_DIR" in os.environ: + scriptPath = os.environ["DOTEST_SCRIPT_DIR"] + else: + scriptPath = os.path.dirname(os.path.realpath(__file__)) + if not scriptPath.endswith('test'): + print("This script expects to reside in lldb's test directory.") + sys.exit(-1) + + os.environ["LLDB_TEST"] = scriptPath + + # Set up the root build directory. + builddir = configuration.test_build_dir + if not configuration.test_build_dir: + raise Exception("test_build_dir is not set") + os.environ["LLDB_BUILD"] = os.path.abspath(configuration.test_build_dir) + + # Set up the LLDB_SRC environment variable, so that the tests can locate + # the LLDB source code. + os.environ["LLDB_SRC"] = lldbsuite.lldb_root + + pluginPath = os.path.join(scriptPath, 'plugins') + toolsLLDBVSCode = os.path.join(scriptPath, 'tools', 'lldb-vscode') + toolsLLDBServerPath = os.path.join(scriptPath, 'tools', 'lldb-server') + + # Insert script dir, plugin dir and lldb-server dir to the sys.path. + sys.path.insert(0, pluginPath) + # Adding test/tools/lldb-vscode to the path makes it easy to + # "import lldb_vscode_testcase" from the VSCode tests + sys.path.insert(0, toolsLLDBVSCode) + # Adding test/tools/lldb-server to the path makes it easy + sys.path.insert(0, toolsLLDBServerPath) + # to "import lldbgdbserverutils" from the lldb-server tests + + # This is the root of the lldb git/svn checkout + # When this changes over to a package instead of a standalone script, this + # will be `lldbsuite.lldb_root` + lldbRootDirectory = lldbsuite.lldb_root + + # Some of the tests can invoke the 'lldb' command directly. + # We'll try to locate the appropriate executable right here. + + # The lldb executable can be set from the command line + # if it's not set, we try to find it now + # first, we try the environment + if not lldbtest_config.lldbExec: + # First, you can define an environment variable LLDB_EXEC specifying the + # full pathname of the lldb executable. + if "LLDB_EXEC" in os.environ: + lldbtest_config.lldbExec = os.environ["LLDB_EXEC"] + + if not lldbtest_config.lldbExec: + # Last, check the path + lldbtest_config.lldbExec = which('lldb') + + if lldbtest_config.lldbExec and not is_exe(lldbtest_config.lldbExec): + print( + "'{}' is not a path to a valid executable".format( + lldbtest_config.lldbExec)) + lldbtest_config.lldbExec = None + + if not lldbtest_config.lldbExec: + print("The 'lldb' executable cannot be located. Some of the tests may not be run as a result.") + sys.exit(-1) + + # confusingly, this is the "bin" directory + lldbLibDir = os.path.dirname(lldbtest_config.lldbExec) + os.environ["LLDB_LIB_DIR"] = lldbLibDir + lldbImpLibDir = os.path.join( + lldbLibDir, + '..', + 'lib') if sys.platform.startswith('win32') else lldbLibDir + os.environ["LLDB_IMPLIB_DIR"] = lldbImpLibDir + print("LLDB library dir:", os.environ["LLDB_LIB_DIR"]) + print("LLDB import library dir:", os.environ["LLDB_IMPLIB_DIR"]) + os.system('%s -v' % lldbtest_config.lldbExec) + + lldbDir = os.path.dirname(lldbtest_config.lldbExec) + + lldbVSCodeExec = os.path.join(lldbDir, "lldb-vscode") + if is_exe(lldbVSCodeExec): + os.environ["LLDBVSCODE_EXEC"] = lldbVSCodeExec + else: + if not configuration.shouldSkipBecauseOfCategories(["lldb-vscode"]): + print( + "The 'lldb-vscode' executable cannot be located. The lldb-vscode tests can not be run as a result.") + configuration.skip_categories.append("lldb-vscode") + + lldbPythonDir = None # The directory that contains 'lldb/__init__.py' + if not configuration.lldb_framework_path and os.path.exists(os.path.join(lldbLibDir, "LLDB.framework")): + configuration.lldb_framework_path = os.path.join(lldbLibDir, "LLDB.framework") + if configuration.lldb_framework_path: + lldbtest_config.lldb_framework_path = configuration.lldb_framework_path + candidatePath = os.path.join( + configuration.lldb_framework_path, 'Resources', 'Python') + if os.path.isfile(os.path.join(candidatePath, 'lldb/__init__.py')): + lldbPythonDir = candidatePath + if not lldbPythonDir: + print( + 'Resources/Python/lldb/__init__.py was not found in ' + + configuration.lldb_framework_path) + sys.exit(-1) + else: + # If our lldb supports the -P option, use it to find the python path: + init_in_python_dir = os.path.join('lldb', '__init__.py') + + lldb_dash_p_result = subprocess.check_output( + [lldbtest_config.lldbExec, "-P"], stderr=subprocess.STDOUT, universal_newlines=True) + + if lldb_dash_p_result and not lldb_dash_p_result.startswith( + ("<", "lldb: invalid option:")) and not lldb_dash_p_result.startswith("Traceback"): + lines = lldb_dash_p_result.splitlines() + + # Workaround for readline vs libedit issue on FreeBSD. If stdout + # is not a terminal Python executes + # rl_variable_bind ("enable-meta-key", "off"); + # This produces a warning with FreeBSD's libedit because the + # enable-meta-key variable is unknown. Not an issue on Apple + # because cpython commit f0ab6f9f0603 added a #ifndef __APPLE__ + # around the call. See http://bugs.python.org/issue19884 for more + # information. For now we just discard the warning output. + if len(lines) >= 1 and lines[0].startswith( + "bind: Invalid command"): + lines.pop(0) + + # Taking the last line because lldb outputs + # 'Cannot read termcap database;\nusing dumb terminal settings.\n' + # before the path + if len(lines) >= 1 and os.path.isfile( + os.path.join(lines[-1], init_in_python_dir)): + lldbPythonDir = lines[-1] + if "freebsd" in sys.platform or "linux" in sys.platform: + os.environ['LLDB_LIB_DIR'] = os.path.join( + lldbPythonDir, '..', '..') + + if not lldbPythonDir: + print( + "Unable to load lldb extension module. Possible reasons for this include:") + print(" 1) LLDB was built with LLDB_ENABLE_PYTHON=0") + print( + " 2) PYTHONPATH and PYTHONHOME are not set correctly. PYTHONHOME should refer to") + print( + " the version of Python that LLDB built and linked against, and PYTHONPATH") + print( + " should contain the Lib directory for the same python distro, as well as the") + print(" location of LLDB\'s site-packages folder.") + print( + " 3) A different version of Python than that which was built against is exported in") + print(" the system\'s PATH environment variable, causing conflicts.") + print( + " 4) The executable '%s' could not be found. Please check " % + lldbtest_config.lldbExec) + print(" that it exists and is executable.") + + if lldbPythonDir: + lldbPythonDir = os.path.normpath(lldbPythonDir) + # Some of the code that uses this path assumes it hasn't resolved the Versions... link. + # If the path we've constructed looks like that, then we'll strip out + # the Versions/A part. + (before, frameWithVersion, after) = lldbPythonDir.rpartition( + "LLDB.framework/Versions/A") + if frameWithVersion != "": + lldbPythonDir = before + "LLDB.framework" + after + + lldbPythonDir = os.path.abspath(lldbPythonDir) + + # If tests need to find LLDB_FRAMEWORK, now they can do it + os.environ["LLDB_FRAMEWORK"] = os.path.dirname( + os.path.dirname(lldbPythonDir)) + + # This is to locate the lldb.py module. Insert it right after + # sys.path[0]. + sys.path[1:1] = [lldbPythonDir] + + +def visit_file(dir, name): + # Try to match the regexp pattern, if specified. + if configuration.regexp: + if not re.search(configuration.regexp, name): + # We didn't match the regex, we're done. + return + + if configuration.skip_tests: + for file_regexp in configuration.skip_tests: + if re.search(file_regexp, name): + return + + # We found a match for our test. 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] + + # Thoroughly check the filterspec against the base module and admit + # the (base, filterspec) combination only when it makes sense. + + def check(obj, parts): + for part in parts: + try: + parent, obj = obj, getattr(obj, part) + except AttributeError: + # The filterspec has failed. + return False + return True + + module = __import__(base) + + def iter_filters(): + for filterspec in configuration.filters: + parts = filterspec.split('.') + if check(module, parts): + yield filterspec + elif parts[0] == base and len(parts) > 1 and check(module, parts[1:]): + yield '.'.join(parts[1:]) + else: + for key,value in module.__dict__.items(): + if check(value, parts): + yield key + '.' + filterspec + + filtered = False + for filterspec in iter_filters(): + filtered = True + print("adding filter spec %s to module %s" % (filterspec, repr(module))) + tests = unittest2.defaultTestLoader.loadTestsFromName(filterspec, module) + configuration.suite.addTests(tests) + + # Forgo this module if the (base, filterspec) combo is invalid + if configuration.filters and not filtered: + return + + if not filtered: + # Add the entire file's worth of tests since we're not filtered. + # Also the fail-over case when the filterspec branch + # (base, filterspec) combo doesn't make sense. + configuration.suite.addTests( + unittest2.defaultTestLoader.loadTestsFromName(base)) + + +def visit(prefix, dir, names): + """Visitor function for os.path.walk(path, visit, arg).""" + + dir_components = set(dir.split(os.sep)) + excluded_components = set(['.svn', '.git']) + if dir_components.intersection(excluded_components): + return + + # Gather all the Python test file names that follow the Test*.py pattern. + python_test_files = [ + name + for name in names + if name.endswith('.py') and name.startswith(prefix)] + + # Visit all the python test files. + for name in python_test_files: + try: + # Ensure we error out if we have multiple tests with the same + # base name. + # Future improvement: find all the places where we work with base + # names and convert to full paths. We have directory structure + # to disambiguate these, so we shouldn't need this constraint. + if name in configuration.all_tests: + raise Exception("Found multiple tests with the name %s" % name) + configuration.all_tests.add(name) + + # Run the relevant tests in the python file. + visit_file(dir, name) + except Exception as ex: + # Convert this exception to a test event error for the file. + test_filename = os.path.abspath(os.path.join(dir, name)) + if configuration.results_formatter_object is not None: + # Grab the backtrace for the exception. + import traceback + backtrace = traceback.format_exc() + + # Generate the test event. + configuration.results_formatter_object.handle_event( + EventBuilder.event_for_job_test_add_error( + test_filename, ex, backtrace)) + raise + + +def setSetting(setting, value): + import lldb + ci = lldb.DBG.GetCommandInterpreter() + res = lldb.SBCommandReturnObject() + cmd = 'setting set %s %s'%(setting, value) + print(cmd) + ci.HandleCommand(cmd, res, False) + if not res.Succeeded(): + raise Exception('failed to run "%s"'%cmd) + +# ======================================== # +# # +# Execution of the test driver starts here # +# # +# ======================================== # + + +def checkDsymForUUIDIsNotOn(): + cmd = ["defaults", "read", "com.apple.DebugSymbols"] + process = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + cmd_output = process.stdout.read() + output_str = cmd_output.decode("utf-8") + if "DBGFileMappedPaths = " in output_str: + print("%s =>" % ' '.join(cmd)) + print(output_str) + print( + "Disable automatic lookup and caching of dSYMs before running the test suite!") + print("Exiting...") + sys.exit(0) + + +def exitTestSuite(exitCode=None): + import lldb + lldb.SBDebugger.Terminate() + if exitCode: + sys.exit(exitCode) + + +def getVersionForSDK(sdk): + sdk = str.lower(sdk) + full_path = seven.get_command_output('xcrun -sdk %s --show-sdk-path' % sdk) + basename = os.path.basename(full_path) + basename = os.path.splitext(basename)[0] + basename = str.lower(basename) + ver = basename.replace(sdk, '') + return ver + + +def setDefaultTripleForPlatform(): + if configuration.lldb_platform_name == 'ios-simulator': + triple_str = 'x86_64-apple-ios%s' % ( + getVersionForSDK('iphonesimulator')) + os.environ['TRIPLE'] = triple_str + return {'TRIPLE': triple_str} + return {} + + +def checkCompiler(): + # Add some intervention here to sanity check that the compiler requested is sane. + # If found not to be an executable program, we abort. + c = configuration.compiler + if which(c): + return + + if not sys.platform.startswith("darwin"): + raise Exception(c + " is not a valid compiler") + + pipe = subprocess.Popen( + ['xcrun', '-find', c], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + cmd_output = pipe.stdout.read() + if not cmd_output or "not found" in cmd_output: + raise Exception(c + " is not a valid compiler") + + configuration.compiler = cmd_output.split('\n')[0] + print("'xcrun -find %s' returning %s" % (c, configuration.compiler)) + +def canRunLibcxxTests(): + from lldbsuite.test import lldbplatformutil + + platform = lldbplatformutil.getPlatform() + + if lldbplatformutil.target_is_android() or lldbplatformutil.platformIsDarwin(): + return True, "libc++ always present" + + if platform == "linux": + if os.path.isdir("/usr/include/c++/v1"): + return True, "Headers found, let's hope they work" + with tempfile.NamedTemporaryFile() as f: + cmd = [configuration.compiler, "-xc++", "-stdlib=libc++", "-o", f.name, "-"] + p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) + _, stderr = p.communicate("#include <algorithm>\nint main() {}") + if not p.returncode: + return True, "Compiling with -stdlib=libc++ works" + return False, "Compiling with -stdlib=libc++ fails with the error: %s" % stderr + + return False, "Don't know how to build with libc++ on %s" % platform + +def checkLibcxxSupport(): + result, reason = canRunLibcxxTests() + if result: + return # libc++ supported + if "libc++" in configuration.categories_list: + return # libc++ category explicitly requested, let it run. + print("Libc++ tests will not be run because: " + reason) + configuration.skip_categories.append("libc++") + +def canRunLibstdcxxTests(): + from lldbsuite.test import lldbplatformutil + + platform = lldbplatformutil.getPlatform() + if lldbplatformutil.target_is_android(): + platform = "android" + if platform == "linux": + return True, "libstdcxx always present" + return False, "Don't know how to build with libstdcxx on %s" % platform + +def checkLibstdcxxSupport(): + result, reason = canRunLibstdcxxTests() + if result: + return # libstdcxx supported + if "libstdcxx" in configuration.categories_list: + return # libstdcxx category explicitly requested, let it run. + print("libstdcxx tests will not be run because: " + reason) + configuration.skip_categories.append("libstdcxx") + +def canRunWatchpointTests(): + from lldbsuite.test import lldbplatformutil + + platform = lldbplatformutil.getPlatform() + if platform == "netbsd": + if os.geteuid() == 0: + return True, "root can always write dbregs" + try: + output = subprocess.check_output(["/sbin/sysctl", "-n", + "security.models.extensions.user_set_dbregs"]).decode().strip() + if output == "1": + return True, "security.models.extensions.user_set_dbregs enabled" + except subprocess.CalledProcessError: + pass + return False, "security.models.extensions.user_set_dbregs disabled" + return True, "watchpoint support available" + +def checkWatchpointSupport(): + result, reason = canRunWatchpointTests() + if result: + return # watchpoints supported + if "watchpoint" in configuration.categories_list: + return # watchpoint category explicitly requested, let it run. + print("watchpoint tests will not be run because: " + reason) + configuration.skip_categories.append("watchpoint") + +def checkDebugInfoSupport(): + import lldb + + platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2] + compiler = configuration.compiler + skipped = [] + for cat in test_categories.debug_info_categories: + if cat in configuration.categories_list: + continue # Category explicitly requested, let it run. + if test_categories.is_supported_on_platform(cat, platform, compiler): + continue + configuration.skip_categories.append(cat) + skipped.append(cat) + if skipped: + print("Skipping following debug info categories:", skipped) + +def run_suite(): + # On MacOS X, check to make sure that domain for com.apple.DebugSymbols defaults + # does not exist before proceeding to running the test suite. + if sys.platform.startswith("darwin"): + checkDsymForUUIDIsNotOn() + + # Start the actions by first parsing the options while setting up the test + # directories, followed by setting up the search paths for lldb utilities; + # then, we walk the directory trees and collect the tests into our test suite. + # + parseOptionsAndInitTestdirs() + + # Setup test results (test results formatter and output handling). + setupTestResults() + + setupSysPath() + + + # For the time being, let's bracket the test runner within the + # lldb.SBDebugger.Initialize()/Terminate() pair. + import lldb + + # Now we can also import lldbutil + from lldbsuite.test import lldbutil + + # Create a singleton SBDebugger in the lldb namespace. + lldb.DBG = lldb.SBDebugger.Create() + + if configuration.lldb_platform_name: + print("Setting up remote platform '%s'" % + (configuration.lldb_platform_name)) + lldb.remote_platform = lldb.SBPlatform( + configuration.lldb_platform_name) + if not lldb.remote_platform.IsValid(): + print( + "error: unable to create the LLDB platform named '%s'." % + (configuration.lldb_platform_name)) + exitTestSuite(1) + if configuration.lldb_platform_url: + # We must connect to a remote platform if a LLDB platform URL was + # specified + print( + "Connecting to remote platform '%s' at '%s'..." % + (configuration.lldb_platform_name, configuration.lldb_platform_url)) + platform_connect_options = lldb.SBPlatformConnectOptions( + configuration.lldb_platform_url) + err = lldb.remote_platform.ConnectRemote(platform_connect_options) + if err.Success(): + print("Connected.") + else: + print("error: failed to connect to remote platform using URL '%s': %s" % ( + configuration.lldb_platform_url, err)) + exitTestSuite(1) + else: + configuration.lldb_platform_url = None + + platform_changes = setDefaultTripleForPlatform() + first = True + for key in platform_changes: + if first: + print("Environment variables setup for platform support:") + first = False + print("%s = %s" % (key, platform_changes[key])) + + if configuration.lldb_platform_working_dir: + print("Setting remote platform working directory to '%s'..." % + (configuration.lldb_platform_working_dir)) + error = lldb.remote_platform.MakeDirectory( + configuration.lldb_platform_working_dir, 448) # 448 = 0o700 + if error.Fail(): + raise Exception("making remote directory '%s': %s" % ( + configuration.lldb_platform_working_dir, error)) + + if not lldb.remote_platform.SetWorkingDirectory( + configuration.lldb_platform_working_dir): + raise Exception("failed to set working directory '%s'" % configuration.lldb_platform_working_dir) + lldb.DBG.SetSelectedPlatform(lldb.remote_platform) + else: + lldb.remote_platform = None + configuration.lldb_platform_working_dir = None + configuration.lldb_platform_url = None + + # Set up the working directory. + # Note that it's not dotest's job to clean this directory. + build_dir = configuration.test_build_dir + lldbutil.mkdir_p(build_dir) + + target_platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2] + + checkLibcxxSupport() + checkLibstdcxxSupport() + checkWatchpointSupport() + checkDebugInfoSupport() + + # Don't do debugserver tests on anything except OS X. + configuration.dont_do_debugserver_test = ( + "linux" in target_platform or + "freebsd" in target_platform or + "netbsd" in target_platform or + "windows" in target_platform) + + # Don't do lldb-server (llgs) tests on anything except Linux and Windows. + configuration.dont_do_llgs_test = not ( + "linux" in target_platform or + "netbsd" in target_platform or + "windows" in target_platform) + + # Collect tests from the specified testing directories. If a test + # subdirectory filter is explicitly specified, limit the search to that + # subdirectory. + exclusive_test_subdir = configuration.get_absolute_path_to_exclusive_test_subdir() + if exclusive_test_subdir: + dirs_to_search = [exclusive_test_subdir] + else: + dirs_to_search = configuration.testdirs + for testdir in dirs_to_search: + for (dirpath, dirnames, filenames) in os.walk(testdir): + visit('Test', dirpath, filenames) + + # + # Now that we have loaded all the test cases, run the whole test suite. + # + + # Set any user-overridden settings. + for key, value in configuration.settings: + setSetting(key, value) + + # Install the control-c handler. + unittest2.signals.installHandler() + + lldbutil.mkdir_p(configuration.sdir_name) + os.environ["LLDB_SESSION_DIRNAME"] = configuration.sdir_name + + sys.stderr.write( + "\nSession logs for test failures/errors/unexpected successes" + " will go into directory '%s'\n" % + configuration.sdir_name) + sys.stderr.write("Command invoked: %s\n" % get_dotest_invocation()) + + # + # Invoke the default TextTestRunner to run the test suite + # + checkCompiler() + + if configuration.verbose: + print("compiler=%s" % configuration.compiler) + + # Iterating over all possible architecture and compiler combinations. + os.environ["ARCH"] = configuration.arch + os.environ["CC"] = configuration.compiler + configString = "arch=%s compiler=%s" % (configuration.arch, + configuration.compiler) + + # Output the configuration. + if configuration.verbose: + sys.stderr.write("\nConfiguration: " + configString + "\n") + + # First, write out the number of collected test cases. + if configuration.verbose: + sys.stderr.write(configuration.separator + "\n") + sys.stderr.write( + "Collected %d test%s\n\n" % + (configuration.suite.countTestCases(), + configuration.suite.countTestCases() != 1 and "s" or "")) + + # Invoke the test runner. + if configuration.count == 1: + result = unittest2.TextTestRunner( + stream=sys.stderr, + verbosity=configuration.verbose, + resultclass=test_result.LLDBTestResult).run( + configuration.suite) + else: + # We are invoking the same test suite more than once. In this case, + # mark __ignore_singleton__ flag as True so the signleton pattern is + # not enforced. + test_result.LLDBTestResult.__ignore_singleton__ = True + for i in range(configuration.count): + + result = unittest2.TextTestRunner( + stream=sys.stderr, + verbosity=configuration.verbose, + resultclass=test_result.LLDBTestResult).run( + configuration.suite) + + configuration.failed = not result.wasSuccessful() + + if configuration.sdir_has_content and configuration.verbose: + sys.stderr.write( + "Session logs for test failures/errors/unexpected successes" + " can be found in directory '%s'\n" % + configuration.sdir_name) + + if configuration.use_categories and len( + configuration.failures_per_category) > 0: + sys.stderr.write("Failures per category:\n") + for category in configuration.failures_per_category: + sys.stderr.write( + "%s - %d\n" % + (category, configuration.failures_per_category[category])) + + # Exiting. + exitTestSuite(configuration.failed) + +if __name__ == "__main__": + print( + __file__ + + " is for use as a module only. It should not be run as a standalone script.") + sys.exit(-1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/dotest_args.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/dotest_args.py new file mode 100644 index 00000000000..7ec5fa2a78e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/dotest_args.py @@ -0,0 +1,266 @@ +from __future__ import absolute_import + +# System modules +import argparse +import sys +import os +import textwrap + +# LLDB modules +from . import configuration + + +def create_parser(): + parser = argparse.ArgumentParser( + description='description', + prefix_chars='+-', + add_help=False) + group = None + + # Helper function for boolean options (group will point to the current + # group when executing X) + X = lambda optstr, helpstr, **kwargs: group.add_argument( + optstr, help=helpstr, action='store_true', **kwargs) + + group = parser.add_argument_group('Help') + group.add_argument( + '-h', + '--help', + dest='h', + action='store_true', + help="Print this help message and exit. Add '-v' for more detailed help.") + + # C and Python toolchain options + group = parser.add_argument_group('Toolchain options') + group.add_argument( + '-A', + '--arch', + metavar='arch', + dest='arch', + help=textwrap.dedent('''Specify the architecture(s) to test. This option can be specified more than once''')) + group.add_argument('-C', '--compiler', metavar='compiler', dest='compiler', help=textwrap.dedent( + '''Specify the compiler(s) used to build the inferior executables. The compiler path can be an executable basename or a full path to a compiler executable. This option can be specified multiple times.''')) + if sys.platform == 'darwin': + group.add_argument('--apple-sdk', metavar='apple_sdk', dest='apple_sdk', default="macosx", help=textwrap.dedent( + '''Specify the name of the Apple SDK (macosx, macosx.internal, iphoneos, iphoneos.internal, or path to SDK) and use the appropriate tools from that SDK's toolchain.''')) + # FIXME? This won't work for different extra flags according to each arch. + group.add_argument( + '-E', + metavar='extra-flags', + help=textwrap.dedent('''Specify the extra flags to be passed to the toolchain when building the inferior programs to be debugged + suggestions: do not lump the "-A arch1 -A arch2" together such that the -E option applies to only one of the architectures''')) + + group.add_argument('--dsymutil', metavar='dsymutil', dest='dsymutil', help=textwrap.dedent('Specify which dsymutil to use.')) + + group.add_argument('--filecheck', metavar='filecheck', dest='filecheck', help=textwrap.dedent('Specify which FileCheck binary to use.')) + + # Test filtering options + group = parser.add_argument_group('Test filtering options') + group.add_argument( + '-f', + metavar='filterspec', + action='append', + help=('Specify a filter, which looks like "TestModule.TestClass.test_name". '+ + 'You may also use shortened filters, such as '+ + '"TestModule.TestClass", "TestClass.test_name", or just "test_name".')) + group.add_argument( + '-p', + metavar='pattern', + help='Specify a regexp filename pattern for inclusion in the test suite') + group.add_argument('--excluded', metavar='exclusion-file', action='append', help=textwrap.dedent( + '''Specify a file for tests to exclude. File should contain lists of regular expressions for test files or methods, + with each list under a matching header (xfail files, xfail methods, skip files, skip methods)''')) + group.add_argument( + '-G', + '--category', + metavar='category', + action='append', + dest='categories_list', + help=textwrap.dedent('''Specify categories of test cases of interest. Can be specified more than once.''')) + group.add_argument( + '--skip-category', + metavar='category', + action='append', + dest='skip_categories', + help=textwrap.dedent('''Specify categories of test cases to skip. Takes precedence over -G. Can be specified more than once.''')) + group.add_argument( + '--xfail-category', + metavar='category', + action='append', + dest='xfail_categories', + help=textwrap.dedent('''Specify categories of test cases that are expected to fail. Can be specified more than once.''')) + + # Configuration options + group = parser.add_argument_group('Configuration options') + group.add_argument( + '--framework', + metavar='framework-path', + help='The path to LLDB.framework') + group.add_argument( + '--executable', + metavar='executable-path', + help='The path to the lldb executable') + group.add_argument( + '--server', + metavar='server-path', + help='The path to the debug server executable to use') + group.add_argument( + '--out-of-tree-debugserver', + dest='out_of_tree_debugserver', + action='store_true', + help='A flag to indicate an out-of-tree debug server is being used') + group.add_argument( + '--dwarf-version', + metavar='dwarf_version', + dest='dwarf_version', + type=int, + help='Override the DWARF version.') + group.add_argument( + '--setting', + metavar='SETTING=VALUE', + dest='settings', + type=str, + nargs=1, + action='append', + help='Run "setting set SETTING VALUE" before executing any test.') + group.add_argument( + '-s', + metavar='name', + help='Specify the name of the dir created to store the session files of tests with errored or failed status. If not specified, the test driver uses the timestamp as the session dir name') + group.add_argument( + '-S', + '--session-file-format', + default=configuration.session_file_format, + metavar='format', + help='Specify session file name format. See configuration.py for a description.') + group.add_argument( + '-y', + type=int, + metavar='count', + help="Specify the iteration count used to collect our benchmarks. An example is the number of times to do 'thread step-over' to measure stepping speed.") + group.add_argument( + '-#', + type=int, + metavar='sharp', + dest='sharp', + help='Repeat the test suite for a specified number of times') + group.add_argument('--channel', metavar='channel', dest='channels', action='append', help=textwrap.dedent( + "Specify the log channels (and optional categories) e.g. 'lldb all' or 'gdb-remote packets' if no categories are specified, 'default' is used")) + group.add_argument( + '--log-success', + dest='log_success', + action='store_true', + help="Leave logs/traces even for successful test runs (useful for creating reference log files during debugging.)") + group.add_argument( + '--codesign-identity', + metavar='Codesigning identity', + default='lldb_codesign', + help='The codesigning identity to use') + group.add_argument( + '--build-dir', + dest='test_build_dir', + metavar='Test build directory', + default='lldb-test-build.noindex', + help='The root build directory for the tests. It will be removed before running.') + group.add_argument( + '--lldb-module-cache-dir', + dest='lldb_module_cache_dir', + metavar='The clang module cache directory used by LLDB', + help='The clang module cache directory used by LLDB. Defaults to <test build directory>/module-cache-lldb.') + group.add_argument( + '--clang-module-cache-dir', + dest='clang_module_cache_dir', + metavar='The clang module cache directory used by Clang', + help='The clang module cache directory used in the Make files by Clang while building tests. Defaults to <test build directory>/module-cache-clang.') + + # Configuration options + group = parser.add_argument_group('Remote platform options') + group.add_argument( + '--platform-name', + dest='lldb_platform_name', + metavar='platform-name', + help='The name of a remote platform to use') + group.add_argument( + '--platform-url', + dest='lldb_platform_url', + metavar='platform-url', + help='A LLDB platform URL to use when connecting to a remote platform to run the test suite') + group.add_argument( + '--platform-working-dir', + dest='lldb_platform_working_dir', + metavar='platform-working-dir', + help='The directory to use on the remote platform.') + + # Test-suite behaviour + group = parser.add_argument_group('Runtime behaviour options') + X('-d', 'Suspend the process after launch to wait indefinitely for a debugger to attach') + X('-t', 'Turn on tracing of lldb command and other detailed test executions') + group.add_argument( + '-u', + dest='unset_env_varnames', + metavar='variable', + action='append', + help='Specify an environment variable to unset before running the test cases. e.g., -u DYLD_INSERT_LIBRARIES -u MallocScribble') + group.add_argument( + '--env', + dest='set_env_vars', + metavar='variable', + action='append', + help='Specify an environment variable to set to the given value before running the test cases e.g.: --env CXXFLAGS=-O3 --env DYLD_INSERT_LIBRARIES') + group.add_argument( + '--inferior-env', + dest='set_inferior_env_vars', + metavar='variable', + action='append', + help='Specify an environment variable to set to the given value for the inferior.') + X('-v', 'Do verbose mode of unittest framework (print out each test case invocation)') + group.add_argument( + '--enable-crash-dialog', + dest='disable_crash_dialog', + action='store_false', + help='(Windows only) When LLDB crashes, display the Windows crash dialog.') + group.set_defaults(disable_crash_dialog=True) + + # Test results support. + group = parser.add_argument_group('Test results options') + group.add_argument( + '--results-file', + action='store', + help=('Specifies the file where test results will be written ' + 'according to the results-formatter class used')) + group.add_argument( + '--results-formatter', + action='store', + help=('Specifies the full package/module/class name used to translate ' + 'test events into some kind of meaningful report, written to ' + 'the designated output results file-like object')) + group.add_argument( + '--results-formatter-option', + '-O', + action='append', + dest='results_formatter_options', + help=('Specify an option to pass to the formatter. ' + 'Use --results-formatter-option="--option1=val1" ' + 'syntax. Note the "=" is critical, don\'t include whitespace.')) + + # Re-run related arguments + group = parser.add_argument_group('Test Re-run Options') + group.add_argument( + '--rerun-all-issues', + action='store_true', + help=('Re-run all issues that occurred during the test run ' + 'irrespective of the test method\'s marking as flakey. ' + 'Default behavior is to apply re-runs only to flakey ' + 'tests that generate issues.')) + + # Remove the reference to our helper function + del X + + group = parser.add_argument_group('Test directories') + group.add_argument( + 'args', + metavar='test-dir', + nargs='*', + help='Specify a list of directory names to search for test modules named after Test*.py (test discovery). If empty, search from the current working directory instead.') + + return parser diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/driver/batch_mode/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/driver/batch_mode/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/driver/batch_mode/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py new file mode 100644 index 00000000000..9639c707a25 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py @@ -0,0 +1,164 @@ +""" +Test that the lldb driver's batch mode works correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +from lldbsuite.test.lldbpexpect import PExpectTest + + +class DriverBatchModeTest(PExpectTest): + + mydir = TestBase.compute_mydir(__file__) + source = 'main.c' + + @skipIfRemote # test not remote-ready llvm.org/pr24813 + @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") + def test_batch_mode_run_crash(self): + """Test that the lldb driver's batch mode works correctly.""" + self.build() + + exe = self.getBuildArtifact("a.out") + + # Pass CRASH so the process will crash and stop in batch mode. + extra_args = ['-b', + '-o', 'break set -n main', + '-o', 'run', + '-o', 'continue', + '-k', 'frame var touch_me_not', + '--', 'CRASH', + ] + self.launch(executable=exe, extra_args=extra_args) + child = self.child + + # We should see the "run": + child.expect_exact("run") + # We should have hit the breakpoint & continued: + child.expect_exact("continue") + # The App should have crashed: + child.expect_exact("About to crash") + # The -k option should have printed the frame variable once: + child.expect_exact('(char *) touch_me_not') + # Then we should have a live prompt: + self.expect_prompt() + self.expect("frame variable touch_me_not", substrs='(char *) touch_me_not') + + @skipIfRemote # test not remote-ready llvm.org/pr24813 + @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") + def test_batch_mode_run_exit(self): + """Test that the lldb driver's batch mode works correctly.""" + self.build() + + exe = self.getBuildArtifact("a.out") + + # Now do it again, and make sure if we don't crash, we quit: + extra_args = ['-b', + '-o', 'break set -n main', + '-o', 'run', + '-o', 'continue', + '--', 'NOCRASH', + ] + self.launch(executable=exe, extra_args=extra_args) + child = self.child + + # We should see the "run": + child.expect_exact("run") + # We should have hit the breakpoint & continued: + child.expect_exact("continue") + # The App should have not have crashed: + child.expect_exact("Got there on time and it did not crash.") + + # Then lldb should exit. + child.expect_exact("exited") + import pexpect + child.expect(pexpect.EOF) + + @skipIfRemote + @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") + def test_batch_mode_launch_stop_at_entry(self): + """Test that the lldb driver's batch mode works correctly for process launch.""" + self.build() + + exe = self.getBuildArtifact("a.out") + + # Launch with the option '--stop-at-entry' stops with a signal (usually SIGSTOP) + # that should be suppressed since it doesn't imply a crash and + # this is not a reason to exit batch mode. + extra_args = ['-b', + '-o', 'process launch --stop-at-entry', + '-o', 'continue', + ] + self.launch(executable=exe, extra_args=extra_args) + child = self.child + + # Check that the process has been launched: + child.expect("Process ([0-9]+) launched:") + # We should have continued: + child.expect_exact("continue") + # The App should have not have crashed: + child.expect_exact("Got there on time and it did not crash.") + + # Then lldb should exit. + child.expect_exact("exited") + import pexpect + child.expect(pexpect.EOF) + + def closeVictim(self): + if self.victim is not None: + self.victim.close() + self.victim = None + + @skipIfRemote # test not remote-ready llvm.org/pr24813 + @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") + @expectedFailureNetBSD + def test_batch_mode_attach_exit(self): + """Test that the lldb driver's batch mode works correctly.""" + self.build() + self.setTearDownCleanup() + + exe = self.getBuildArtifact("a.out") + + # Start up the process by hand, attach to it, and wait for its completion. + # Attach is funny, since it looks like it stops with a signal on most Unixen so + # care must be taken not to treat that as a reason to exit batch mode. + + # Start up the process by hand and wait for it to get to the wait loop. + import pexpect + self.victim = pexpect.spawn('%s WAIT' % (exe)) + if self.victim is None: + self.fail("Could not spawn ", exe, ".") + + self.addTearDownHook(self.closeVictim) + + self.victim.expect("PID: ([0-9]+) END") + victim_pid = int(self.victim.match.group(1)) + + self.victim.expect("Waiting") + + extra_args = [ + '-b', + '-o', 'process attach -p %d'%victim_pid, + '-o', "breakpoint set --file '%s' -p 'Stop here to unset keep_waiting' -N keep_waiting"%self.source, + '-o', 'continue', + '-o', 'break delete keep_waiting', + '-o', 'expr keep_waiting = 0', + '-o', 'continue', + ] + self.launch(executable=exe, extra_args=extra_args) + child = self.child + + child.expect_exact("attach") + + child.expect_exact(self.PROMPT + "continue") + + child.expect_exact(self.PROMPT + "continue") + + # Then we should see the process exit: + child.expect_exact("Process %d exited with status" % (victim_pid)) + + self.victim.expect(pexpect.EOF) + child.expect(pexpect.EOF) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/driver/batch_mode/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/driver/batch_mode/main.c new file mode 100644 index 00000000000..c85a0f272d2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/driver/batch_mode/main.c @@ -0,0 +1,41 @@ +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +int +main (int argc, char **argv) +{ + lldb_enable_attach(); + + int do_crash = 0; + int do_wait = 0; + + int idx; + for (idx = 1; idx < argc; idx++) + { + if (strcmp(argv[idx], "CRASH") == 0) + do_crash = 1; + if (strcmp(argv[idx], "WAIT") == 0) + do_wait = 1; + } + printf("PID: %d END\n", getpid()); + + if (do_wait) + { + int keep_waiting = 1; + while (keep_waiting) + { + printf ("Waiting\n"); + sleep(1); // Stop here to unset keep_waiting + } + } + + if (do_crash) + { + char *touch_me_not = (char *) 0; + printf ("About to crash.\n"); + touch_me_not[0] = 'a'; + } + printf ("Got there on time and it did not crash.\n"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/.categories new file mode 100644 index 00000000000..3a3f4df6416 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/.categories @@ -0,0 +1 @@ +cmdline diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py new file mode 100644 index 00000000000..4a129bbcd3e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py @@ -0,0 +1,107 @@ +""" +Test some lldb command abbreviations and aliases for proper resolution. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class AbbreviationsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_command_abbreviations_and_aliases(self): + command_interpreter = self.dbg.GetCommandInterpreter() + self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER) + result = lldb.SBCommandReturnObject() + + # Check that abbreviations are expanded to the full command. + command_interpreter.ResolveCommand("ap script", result) + self.assertTrue(result.Succeeded()) + self.assertEqual("apropos script", result.GetOutput()) + + command_interpreter.ResolveCommand("h", result) + self.assertTrue(result.Succeeded()) + self.assertEqual("help", result.GetOutput()) + + # Check resolution of abbreviations for multi-word commands. + command_interpreter.ResolveCommand("lo li", result) + self.assertTrue(result.Succeeded()) + self.assertEqual("log list", result.GetOutput()) + + command_interpreter.ResolveCommand("br s", result) + self.assertTrue(result.Succeeded()) + self.assertEqual("breakpoint set", result.GetOutput()) + + # Try an ambiguous abbreviation. + # "pl" could be "platform" or "plugin". + command_interpreter.ResolveCommand("pl", result) + self.assertFalse(result.Succeeded()) + self.assertTrue(result.GetError().startswith("Ambiguous command")) + + # Make sure an unabbreviated command is not mangled. + command_interpreter.ResolveCommand( + "breakpoint set --name main --line 123", result) + self.assertTrue(result.Succeeded()) + self.assertEqual( + "breakpoint set --name main --line 123", + result.GetOutput()) + + # Create some aliases. + self.runCmd("com a alias com al") + self.runCmd("alias gurp help") + + # Check that an alias is replaced with the actual command + command_interpreter.ResolveCommand("gurp target create", result) + self.assertTrue(result.Succeeded()) + self.assertEqual("help target create", result.GetOutput()) + + # Delete the alias and make sure it no longer has an effect. + self.runCmd("com u gurp") + command_interpreter.ResolveCommand("gurp", result) + self.assertFalse(result.Succeeded()) + + # Check aliases with text replacement. + self.runCmd("alias pltty process launch -s -o %1 -e %1") + command_interpreter.ResolveCommand("pltty /dev/tty0", result) + self.assertTrue(result.Succeeded()) + self.assertEqual( + "process launch -s -o /dev/tty0 -e /dev/tty0", + result.GetOutput()) + + self.runCmd("alias xyzzy breakpoint set -n %1 -l %2") + command_interpreter.ResolveCommand("xyzzy main 123", result) + self.assertTrue(result.Succeeded()) + self.assertEqual( + "breakpoint set -n main -l 123", + result.GetOutput().strip()) + + # And again, without enough parameters. + command_interpreter.ResolveCommand("xyzzy main", result) + self.assertFalse(result.Succeeded()) + + # Check a command that wants the raw input. + command_interpreter.ResolveCommand( + r'''sc print("\n\n\tHello!\n")''', result) + self.assertTrue(result.Succeeded()) + self.assertEqual( + r'''script print("\n\n\tHello!\n")''', + result.GetOutput()) + + # Prompt changing stuff should be tested, but this doesn't seem like the + # right test to do it in. It has nothing to do with aliases or abbreviations. + #self.runCmd("com sou ./change_prompt.lldb") + # self.expect("settings show prompt", + # startstr = 'prompt (string) = "[with-three-trailing-spaces] "') + #self.runCmd("settings clear prompt") + # self.expect("settings show prompt", + # startstr = 'prompt (string) = "(lldb) "') + #self.runCmd("se se prompt 'Sycamore> '") + # self.expect("se sh prompt", + # startstr = 'prompt (string) = "Sycamore> "') + #self.runCmd("se cl prompt") + # self.expect("set sh prompt", + # startstr = 'prompt (string) = "(lldb) "') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py new file mode 100644 index 00000000000..9e4b3bb9d2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py @@ -0,0 +1,38 @@ +""" +Test some lldb command abbreviations to make sure the common short spellings of +many commands remain available even after we add/delete commands in the future. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CommonShortSpellingsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_abbrevs2(self): + command_interpreter = self.dbg.GetCommandInterpreter() + self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER) + result = lldb.SBCommandReturnObject() + + abbrevs = [ + ('br s', 'breakpoint set'), + ('disp', '_regexp-display'), # a.k.a., 'display' + ('di', 'disassemble'), + ('dis', 'disassemble'), + ('ta st a', 'target stop-hook add'), + ('fr v', 'frame variable'), + ('f 1', 'frame select 1'), + ('ta st li', 'target stop-hook list'), + ] + + for (short_val, long_val) in abbrevs: + command_interpreter.ResolveCommand(short_val, result) + self.assertTrue(result.Succeeded()) + self.assertEqual(long_val, result.GetOutput()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/alias/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/alias/.categories new file mode 100644 index 00000000000..3a3f4df6416 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/alias/.categories @@ -0,0 +1 @@ +cmdline diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/Makefile new file mode 100644 index 00000000000..4d1950cf34a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/Makefile @@ -0,0 +1,7 @@ +C_SOURCES := main.c + +MAKE_DSYM := NO +ARCHIVE_NAME := libfoo.a +ARCHIVE_C_SOURCES := a.c b.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/README b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/README new file mode 100644 index 00000000000..d327f4585c6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/README @@ -0,0 +1,62 @@ +a.out file refers to libfoo.a for a.o and b.o, which is what we want to accomplish for +this test case. + +[16:17:44] johnny:/Volumes/data/lldb/svn/latest/test/functionalities/archives $ dsymutil -s a.out +---------------------------------------------------------------------- +Symbol table for: 'a.out' (x86_64) +---------------------------------------------------------------------- +Index n_strx n_type n_sect n_desc n_value +======== -------- ------------------ ------ ------ ---------------- +[ 0] 00000002 64 (N_SO ) 00 0000 0000000000000000 '/Volumes/data/lldb/svn/latest/test/functionalities/archives/' +[ 1] 0000003f 64 (N_SO ) 00 0000 0000000000000000 'main.c' +[ 2] 00000046 66 (N_OSO ) 03 0001 000000004f0f780c '/Volumes/data/lldb/svn/latest/test/functionalities/archives/main.o' +[ 3] 00000001 2e (N_BNSYM ) 01 0000 0000000100000d70 +[ 4] 00000089 24 (N_FUN ) 01 0000 0000000100000d70 '_main' +[ 5] 00000001 24 (N_FUN ) 00 0000 000000000000005d +[ 6] 00000001 4e (N_ENSYM ) 01 0000 000000000000005d +[ 7] 00000001 64 (N_SO ) 01 0000 0000000000000000 +[ 8] 00000002 64 (N_SO ) 00 0000 0000000000000000 '/Volumes/data/lldb/svn/latest/test/functionalities/archives/' +[ 9] 0000008f 64 (N_SO ) 00 0000 0000000000000000 'a.c' +[ 10] 00000093 66 (N_OSO ) 03 0001 000000004f0f780c '/Volumes/data/lldb/svn/latest/test/functionalities/archives/libfoo.a(a.o)' +[ 11] 00000001 2e (N_BNSYM ) 01 0000 0000000100000dd0 +[ 12] 000000dd 24 (N_FUN ) 01 0000 0000000100000dd0 '_a' +[ 13] 00000001 24 (N_FUN ) 00 0000 0000000000000020 +[ 14] 00000001 4e (N_ENSYM ) 01 0000 0000000000000020 +[ 15] 00000001 2e (N_BNSYM ) 01 0000 0000000100000df0 +[ 16] 000000e0 24 (N_FUN ) 01 0000 0000000100000df0 '_aa' +[ 17] 00000001 24 (N_FUN ) 00 0000 0000000000000018 +[ 18] 00000001 4e (N_ENSYM ) 01 0000 0000000000000018 +[ 19] 000000e4 20 (N_GSYM ) 00 0000 0000000000000000 '___a_global' +[ 20] 00000001 64 (N_SO ) 01 0000 0000000000000000 +[ 21] 00000002 64 (N_SO ) 00 0000 0000000000000000 '/Volumes/data/lldb/svn/latest/test/functionalities/archives/' +[ 22] 000000f0 64 (N_SO ) 00 0000 0000000000000000 'b.c' +[ 23] 000000f4 66 (N_OSO ) 03 0001 000000004f0f780c '/Volumes/data/lldb/svn/latest/test/functionalities/archives/libfoo.a(b.o)' +[ 24] 00000001 2e (N_BNSYM ) 01 0000 0000000100000e10 +[ 25] 0000013e 24 (N_FUN ) 01 0000 0000000100000e10 '_b' +[ 26] 00000001 24 (N_FUN ) 00 0000 0000000000000020 +[ 27] 00000001 4e (N_ENSYM ) 01 0000 0000000000000020 +[ 28] 00000001 2e (N_BNSYM ) 01 0000 0000000100000e30 +[ 29] 00000141 24 (N_FUN ) 01 0000 0000000100000e30 '_bb' +[ 30] 00000001 24 (N_FUN ) 00 0000 0000000000000018 +[ 31] 00000001 4e (N_ENSYM ) 01 0000 0000000000000018 +[ 32] 00000145 26 (N_STSYM ) 0a 0000 000000010000104c '___b_global' +[ 33] 00000001 64 (N_SO ) 01 0000 0000000000000000 +[ 34] 00000151 0e ( SECT ) 07 0000 0000000100001000 '_pvars' +[ 35] 00000158 0e ( SECT ) 0a 0000 000000010000104c '___b_global' +[ 36] 00000164 0f ( SECT EXT) 0b 0000 0000000100001050 '_NXArgc' +[ 37] 0000016c 0f ( SECT EXT) 0b 0000 0000000100001058 '_NXArgv' +[ 38] 00000174 0f ( SECT EXT) 0a 0000 0000000100001048 '___a_global' +[ 39] 00000180 0f ( SECT EXT) 0b 0000 0000000100001068 '___progname' +[ 40] 0000018c 03 ( ABS EXT) 01 0010 0000000100000000 '__mh_execute_header' +[ 41] 000001a0 0f ( SECT EXT) 01 0000 0000000100000dd0 '_a' +[ 42] 000001a3 0f ( SECT EXT) 01 0000 0000000100000df0 '_aa' +[ 43] 000001a7 0f ( SECT EXT) 01 0000 0000000100000e10 '_b' +[ 44] 000001aa 0f ( SECT EXT) 01 0000 0000000100000e30 '_bb' +[ 45] 000001ae 0f ( SECT EXT) 0b 0000 0000000100001060 '_environ' +[ 46] 000001b7 0f ( SECT EXT) 01 0000 0000000100000d70 '_main' +[ 47] 000001bd 0f ( SECT EXT) 01 0000 0000000100000d30 'start' +[ 48] 000001c3 01 ( UNDF EXT) 00 0100 0000000000000000 '_exit' +[ 49] 000001c9 01 ( UNDF EXT) 00 0100 0000000000000000 '_printf' +[ 50] 000001d1 01 ( UNDF EXT) 00 0100 0000000000000000 'dyld_stub_binder' + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py new file mode 100644 index 00000000000..b412ac4c135 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py @@ -0,0 +1,61 @@ +"""Test breaking inside functions defined within a BSD archive file libfoo.a.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BSDArchivesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number in a(int) to break at. + self.line = line_number( + 'a.c', '// Set file and line breakpoint inside a().') + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24527. Makefile.rules doesn't know how to build static libs on Windows") + def test(self): + """Break inside a() and b() defined within libfoo.a.""" + self.build() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside a() by file and line first. + lldbutil.run_break_set_by_file_and_line( + self, "a.c", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Break at a(int) first. + self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int) arg = 1']) + self.expect("frame variable __a_global", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int) __a_global = 1']) + + # Set breakpoint for b() next. + lldbutil.run_break_set_by_symbol( + self, "b", num_expected_locations=1, sym_exact=True) + + # Continue the program, we should break at b(int) next. + self.runCmd("continue") + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int) arg = 2']) + self.expect("frame variable __b_global", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int) __b_global = 2']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/a.c new file mode 100644 index 00000000000..c8d226ab9de --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/a.c @@ -0,0 +1,18 @@ +//===-- a.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +int __a_global = 1; + +int a(int arg) { + int result = arg + __a_global; + return result; // Set file and line breakpoint inside a(). +} + +int aa(int arg1) { + int result1 = arg1 - __a_global; + return result1; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/b.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/b.c new file mode 100644 index 00000000000..6510b978f37 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/b.c @@ -0,0 +1,18 @@ +//===-- b.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +static int __b_global = 2; + +int b(int arg) { + int result = arg + __b_global; + return result; +} + +int bb(int arg1) { + int result2 = arg1 - __b_global; + return result2; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/main.c new file mode 100644 index 00000000000..1525a1a5e38 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/archives/main.c @@ -0,0 +1,16 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +extern int a(int); +extern int b(int); +int main (int argc, char const *argv[]) +{ + printf ("a(1) returns %d\n", a(1)); + printf ("b(2) returns %d\n", b(2)); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/Makefile new file mode 100644 index 00000000000..4913a18d8cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=address -g -gcolumn-info + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py new file mode 100644 index 00000000000..4df315127f6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py @@ -0,0 +1,129 @@ +""" +Test that ASan memory history provider returns correct stack traces +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbplatform +from lldbsuite.test import lldbutil + + +class AsanTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureNetBSD + @skipUnlessAddressSanitizer + def test(self): + self.build() + self.asan_tests() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.line_malloc = line_number('main.c', '// malloc line') + self.line_malloc2 = line_number('main.c', '// malloc2 line') + self.line_free = line_number('main.c', '// free line') + self.line_breakpoint = line_number('main.c', '// break line') + + def asan_tests(self): + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.registerSanitizerLibrariesWithTarget(target) + + self.runCmd("breakpoint set -f main.c -l %d" % self.line_breakpoint) + + # "memory history" command should not work without a process + self.expect("memory history 0", + error=True, + substrs=["invalid process"]) + + self.runCmd("run") + + stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + if stop_reason == lldb.eStopReasonExec: + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. + self.runCmd("continue") + + # the stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # test that the ASan dylib is present + self.expect( + "image lookup -n __asan_describe_address", + "__asan_describe_address should be present", + substrs=['1 match found']) + + # test the 'memory history' command + self.expect( + "memory history 'pointer'", + substrs=[ + 'Memory allocated by Thread', + 'a.out`f1', + 'main.c:%d' % + self.line_malloc, + 'Memory deallocated by Thread', + 'a.out`f2', + 'main.c:%d' % + self.line_free]) + + # do the same using SB API + process = self.dbg.GetSelectedTarget().process + val = process.GetSelectedThread().GetSelectedFrame().EvaluateExpression("pointer") + addr = val.GetValueAsUnsigned() + threads = process.GetHistoryThreads(addr) + self.assertEqual(threads.GetSize(), 2) + + history_thread = threads.GetThreadAtIndex(0) + self.assertTrue(history_thread.num_frames >= 2) + self.assertEqual(history_thread.frames[1].GetLineEntry( + ).GetFileSpec().GetFilename(), "main.c") + self.assertEqual( + history_thread.frames[1].GetLineEntry().GetLine(), + self.line_free) + + history_thread = threads.GetThreadAtIndex(1) + self.assertTrue(history_thread.num_frames >= 2) + self.assertEqual(history_thread.frames[1].GetLineEntry( + ).GetFileSpec().GetFilename(), "main.c") + self.assertEqual( + history_thread.frames[1].GetLineEntry().GetLine(), + self.line_malloc) + + # let's free the container (SBThreadCollection) and see if the + # SBThreads still live + threads = None + self.assertTrue(history_thread.num_frames >= 2) + self.assertEqual(history_thread.frames[1].GetLineEntry( + ).GetFileSpec().GetFilename(), "main.c") + self.assertEqual( + history_thread.frames[1].GetLineEntry().GetLine(), + self.line_malloc) + + # ASan will break when a report occurs and we'll try the API then + self.runCmd("continue") + + self.expect( + "thread list", + "Process should be stopped due to ASan report", + substrs=[ + 'stopped', + 'stop reason = Use of deallocated memory']) + + # make sure the 'memory history' command still works even when we're + # generating a report now + self.expect( + "memory history 'another_pointer'", + substrs=[ + 'Memory allocated by Thread', + 'a.out`f1', + 'main.c:%d' % + self.line_malloc2]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py new file mode 100644 index 00000000000..0ca48435e82 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py @@ -0,0 +1,91 @@ +""" +Test the AddressSanitizer runtime support for report breakpoint and data extraction. +""" + + + +import json +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class AsanTestReportDataCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @expectedFailureNetBSD + @skipUnlessAddressSanitizer + @skipIf(archs=['i386'], bugnumber="llvm.org/PR36710") + def test(self): + self.build() + self.asan_tests() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.line_malloc = line_number('main.c', '// malloc line') + self.line_malloc2 = line_number('main.c', '// malloc2 line') + self.line_free = line_number('main.c', '// free line') + self.line_breakpoint = line_number('main.c', '// break line') + self.line_crash = line_number('main.c', '// BOOM line') + self.col_crash = 16 + + def asan_tests(self): + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.registerSanitizerLibrariesWithTarget(target) + + self.runCmd("run") + + stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + if stop_reason == lldb.eStopReasonExec: + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. + self.runCmd("continue") + + self.expect( + "thread list", + "Process should be stopped due to ASan report", + substrs=[ + 'stopped', + 'stop reason = Use of deallocated memory']) + + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), + lldb.eStopReasonInstrumentation) + + self.expect("bt", "The backtrace should show the crashing line", + substrs=['main.c:%d:%d' % (self.line_crash, self.col_crash)]) + + self.expect( + "thread info -s", + "The extended stop info should contain the ASan provided fields", + substrs=[ + "access_size", + "access_type", + "address", + "pc", + "description", + "heap-use-after-free"]) + + output_lines = self.res.GetOutput().split('\n') + json_line = '\n'.join(output_lines[2:]) + data = json.loads(json_line) + self.assertEqual(data["description"], "heap-use-after-free") + self.assertEqual(data["instrumentation_class"], "AddressSanitizer") + self.assertEqual(data["stop_type"], "fatal_error") + + # now let's try the SB API + process = self.dbg.GetSelectedTarget().process + thread = process.GetSelectedThread() + + s = lldb.SBStream() + self.assertTrue(thread.GetStopReasonExtendedInfoAsJSON(s)) + s = s.GetData() + data2 = json.loads(s) + self.assertEqual(data, data2) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/main.c new file mode 100644 index 00000000000..45f9f4f9fb7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/asan/main.c @@ -0,0 +1,33 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdlib.h> + +char *pointer; +char *another_pointer; + +void f1() { + pointer = malloc(10); // malloc line + another_pointer = malloc(20); // malloc2 line +} + +void f2() { + free(pointer); // free line +} + +int main (int argc, char const *argv[]) +{ + f1(); + f2(); + + printf("Hello world!\n"); // break line + + pointer[0] = 'A'; // BOOM line + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py new file mode 100644 index 00000000000..a984254fff9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py @@ -0,0 +1,106 @@ +""" +Test whether a process started by lldb has no extra file descriptors open. +""" + + + +import lldb +from lldbsuite.test import lldbutil +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + + +def python_leaky_fd_version(test): + import sys + # Python random module leaks file descriptors on some versions. + if sys.version_info >= (2, 7, 8) and sys.version_info < (2, 7, 10): + return "Python random module leaks file descriptors in this python version" + return None + + +class AvoidsFdLeakTestCase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailure(python_leaky_fd_version, "bugs.freebsd.org/197376") + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr25624 still failing with Python 2.7.10") + # The check for descriptor leakage needs to be implemented differently + # here. + @skipIfWindows + @skipIfTargetAndroid() # Android have some other file descriptors open by the shell + @skipIfDarwinEmbedded # <rdar://problem/33888742> # debugserver on ios has an extra fd open on launch + def test_fd_leak_basic(self): + self.do_test([]) + + @expectedFailure(python_leaky_fd_version, "bugs.freebsd.org/197376") + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr25624 still failing with Python 2.7.10") + # The check for descriptor leakage needs to be implemented differently + # here. + @skipIfWindows + @skipIfTargetAndroid() # Android have some other file descriptors open by the shell + @skipIfDarwinEmbedded # <rdar://problem/33888742> # debugserver on ios has an extra fd open on launch + def test_fd_leak_log(self): + self.do_test(["log enable -f '/dev/null' lldb commands"]) + + def do_test(self, commands): + self.build() + exe = self.getBuildArtifact("a.out") + + for c in commands: + self.runCmd(c) + + target = self.dbg.CreateTarget(exe) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + self.assertTrue( + process.GetState() == lldb.eStateExited, + "Process should have exited.") + self.assertTrue( + process.GetExitStatus() == 0, + "Process returned non-zero status. Were incorrect file descriptors passed?") + + @expectedFailure(python_leaky_fd_version, "bugs.freebsd.org/197376") + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr25624 still failing with Python 2.7.10") + # The check for descriptor leakage needs to be implemented differently + # here. + @skipIfWindows + @skipIfTargetAndroid() # Android have some other file descriptors open by the shell + @skipIfDarwinEmbedded # <rdar://problem/33888742> # debugserver on ios has an extra fd open on launch + def test_fd_leak_multitarget(self): + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + breakpoint = target.BreakpointCreateBySourceRegex( + 'Set breakpoint here', lldb.SBFileSpec("main.c", False)) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + process1 = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process1, PROCESS_IS_VALID) + self.assertTrue( + process1.GetState() == lldb.eStateStopped, + "Process should have been stopped.") + + target2 = self.dbg.CreateTarget(exe) + process2 = target2.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process2, PROCESS_IS_VALID) + + self.assertTrue( + process2.GetState() == lldb.eStateExited, + "Process should have exited.") + self.assertTrue( + process2.GetExitStatus() == 0, + "Process returned non-zero status. Were incorrect file descriptors passed?") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/main.c new file mode 100644 index 00000000000..5bdf227928e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/main.c @@ -0,0 +1,28 @@ +#include <sys/types.h> +#include <sys/stat.h> +#include <unistd.h> +#include <errno.h> +#include <stdio.h> + +int +main (int argc, char const **argv) +{ + struct stat buf; + int i, rv = 0; // Set breakpoint here. + + // Make sure stdin/stdout/stderr exist. + for (i = 0; i <= 2; ++i) { + if (fstat(i, &buf) != 0) + return 1; + } + + // Make sure no other file descriptors are open. + for (i = 3; i <= 256; ++i) { + if (fstat(i, &buf) == 0 || errno != EBADF) { + fprintf(stderr, "File descriptor %d is open.\n", i); + rv = 2; + } + } + + return rv; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/backticks/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/backticks/.categories new file mode 100644 index 00000000000..3a3f4df6416 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/backticks/.categories @@ -0,0 +1 @@ +cmdline diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py new file mode 100644 index 00000000000..fdef89c6e05 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py @@ -0,0 +1,21 @@ +""" +Test that backticks without a target should work (not infinite looping). +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BackticksWithNoTargetTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_backticks_no_target(self): + """A simple test of backticks without a target.""" + self.expect("print `1+2-3`", + substrs=[' = 0']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/Makefile new file mode 100644 index 00000000000..695335e068c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py new file mode 100644 index 00000000000..6b42b51d16a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py @@ -0,0 +1,91 @@ +""" +Test address breakpoints set with shared library of SBAddress work correctly. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class AddressBreakpointTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test_address_breakpoints(self): + """Test address breakpoints set with shared library of SBAddress work correctly.""" + self.build() + self.address_breakpoints() + + def address_breakpoints(self): + """Test address breakpoints set with shared library of SBAddress work correctly.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here", lldb.SBFileSpec("main.c")) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Get the breakpoint location from breakpoint after we verified that, + # indeed, it has one location. + location = breakpoint.GetLocationAtIndex(0) + self.assertTrue(location and + location.IsEnabled(), + VALID_BREAKPOINT_LOCATION) + + # Next get the address from the location, and create an address breakpoint using + # that address: + + address = location.GetAddress() + target.BreakpointDelete(breakpoint.GetID()) + + breakpoint = target.BreakpointCreateBySBAddress(address) + + # Disable ASLR. This will allow us to actually test (on platforms that support this flag) + # that the breakpoint was able to track the module. + + launch_info = lldb.SBLaunchInfo(None) + flags = launch_info.GetLaunchFlags() + flags &= ~lldb.eLaunchFlagDisableASLR + launch_info.SetLaunchFlags(flags) + + error = lldb.SBError() + + process = target.Launch(launch_info, error) + self.assertTrue(process, PROCESS_IS_VALID) + + # Did we hit our breakpoint? + from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint + threads = get_threads_stopped_at_breakpoint(process, breakpoint) + self.assertTrue( + len(threads) == 1, + "There should be a thread stopped at our breakpoint") + + # The hit count for the breakpoint should be 1. + self.assertTrue(breakpoint.GetHitCount() == 1) + + process.Kill() + + # Now re-launch and see that we hit the breakpoint again: + launch_info.Clear() + launch_info.SetLaunchFlags(flags) + + process = target.Launch(launch_info, error) + self.assertTrue(process, PROCESS_IS_VALID) + + thread = get_threads_stopped_at_breakpoint(process, breakpoint) + self.assertTrue( + len(threads) == 1, + "There should be a thread stopped at our breakpoint") + + # The hit count for the breakpoint should now be 2. + self.assertTrue(breakpoint.GetHitCount() == 2) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py new file mode 100644 index 00000000000..6d468e0fd64 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestBadAddressBreakpoints.py @@ -0,0 +1,42 @@ +""" +Test that breakpoints set on a bad address say they are bad. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class BadAddressBreakpointTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test_bad_address_breakpoints(self): + """Test that breakpoints set on a bad address say they are bad.""" + self.build() + self.address_breakpoints() + + def address_breakpoints(self): + """Test that breakpoints set on a bad address say they are bad.""" + target, process, thread, bkpt = \ + lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", + lldb.SBFileSpec("main.c")) + + # Now see if we can read from 0. If I can't do that, I don't + # have a good way to know what an illegal address is... + error = lldb.SBError() + + ptr = process.ReadPointerFromMemory(0x0, error) + + if not error.Success(): + bkpt = target.BreakpointCreateByAddress(0x0) + for bp_loc in bkpt: + self.assertTrue(bp_loc.IsResolved() == False) + else: + self.fail( + "Could not find an illegal address at which to set a bad breakpoint.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/main.c new file mode 100644 index 00000000000..6b779296e18 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/main.c @@ -0,0 +1,8 @@ +#include <stdio.h> + +int +main() +{ + printf ("Set a breakpoint here.\n"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/auto_continue/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/auto_continue/Makefile new file mode 100644 index 00000000000..695335e068c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/auto_continue/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/auto_continue/TestBreakpointAutoContinue.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/auto_continue/TestBreakpointAutoContinue.py new file mode 100644 index 00000000000..e0b727e9734 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/auto_continue/TestBreakpointAutoContinue.py @@ -0,0 +1,96 @@ +""" +Test that the breakpoint auto-continue flag works correctly. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class BreakpointAutoContinue(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test_breakpoint_auto_continue(self): + """Make sure the auto continue continues with no other complications""" + self.build() + self.simple_auto_continue() + + def test_auto_continue_with_command(self): + """Add a command, make sure the command gets run""" + self.build() + self.auto_continue_with_command() + + def test_auto_continue_on_location(self): + """Set auto-continue on a location and make sure only that location continues""" + self.build() + self.auto_continue_location() + + def make_target_and_bkpt(self, additional_options=None, num_expected_loc=1, + pattern="Set a breakpoint here"): + exe = self.getBuildArtifact("a.out") + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target.IsValid(), "Target is not valid") + + extra_options_txt = "--auto-continue 1 " + if additional_options: + extra_options_txt += additional_options + bpno = lldbutil.run_break_set_by_source_regexp(self, pattern, + extra_options = extra_options_txt, + num_expected_locations = num_expected_loc) + return bpno + + def launch_it (self, expected_state): + error = lldb.SBError() + launch_info = lldb.SBLaunchInfo(None) + launch_info.SetWorkingDirectory(self.get_process_working_directory()) + + process = self.target.Launch(launch_info, error) + self.assertTrue(error.Success(), "Launch failed.") + + state = process.GetState() + self.assertEqual(state, expected_state, "Didn't get expected state") + + return process + + def simple_auto_continue(self): + bpno = self.make_target_and_bkpt() + process = self.launch_it(lldb.eStateExited) + + bkpt = self.target.FindBreakpointByID(bpno) + self.assertEqual(bkpt.GetHitCount(), 2, "Should have run through the breakpoint twice") + + def auto_continue_with_command(self): + bpno = self.make_target_and_bkpt("-N BKPT -C 'break modify --auto-continue 0 BKPT'") + process = self.launch_it(lldb.eStateStopped) + state = process.GetState() + self.assertEqual(state, lldb.eStateStopped, "Process should be stopped") + bkpt = self.target.FindBreakpointByID(bpno) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, bkpt) + self.assertEqual(len(threads), 1, "There was a thread stopped at our breakpoint") + self.assertEqual(bkpt.GetHitCount(), 2, "Should have hit the breakpoint twice") + + def auto_continue_location(self): + bpno = self.make_target_and_bkpt(pattern="Set a[^ ]* breakpoint here", num_expected_loc=2) + bkpt = self.target.FindBreakpointByID(bpno) + bkpt.SetAutoContinue(False) + + loc = lldb.SBBreakpointLocation() + for i in range(0,2): + func_name = bkpt.location[i].GetAddress().function.name + if func_name == "main": + loc = bkpt.location[i] + + self.assertTrue(loc.IsValid(), "Didn't find a location in main") + loc.SetAutoContinue(True) + + process = self.launch_it(lldb.eStateStopped) + + threads = lldbutil.get_threads_stopped_at_breakpoint(process, bkpt) + self.assertEqual(len(threads), 1, "Didn't get one thread stopped at our breakpoint") + func_name = threads[0].frame[0].function.name + self.assertEqual(func_name, "call_me") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/auto_continue/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/auto_continue/main.c new file mode 100644 index 00000000000..a37f05e0290 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/auto_continue/main.c @@ -0,0 +1,19 @@ +#include <stdio.h> + +void +call_me() +{ + printf("Set another breakpoint here.\n"); +} + +int +main() +{ + int change_me = 0; + for (int i = 0; i < 2; i++) + { + printf ("Set a breakpoint here: %d with: %d.\n", i, change_me); + } + call_me(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_by_line_and_column/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_by_line_and_column/Makefile new file mode 100644 index 00000000000..ad42b20df4e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_by_line_and_column/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 -gcolumn-info + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_by_line_and_column/TestBreakpointByLineAndColumn.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_by_line_and_column/TestBreakpointByLineAndColumn.py new file mode 100644 index 00000000000..98fe4335cc2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_by_line_and_column/TestBreakpointByLineAndColumn.py @@ -0,0 +1,44 @@ +""" +Test setting a breakpoint by line and column. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointByLineAndColumnTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + ## Skip gcc version less 7.1 since it doesn't support -gcolumn-info + @skipIf(compiler="gcc", compiler_version=['<', '7.1']) + def testBreakpointByLineAndColumn(self): + self.build() + main_c = lldb.SBFileSpec("main.c") + _, _, _, breakpoint = lldbutil.run_to_line_breakpoint(self, + main_c, 19, 50) + self.expect("fr v did_call", substrs='1') + in_then = False + for i in range(breakpoint.GetNumLocations()): + b_loc = breakpoint.GetLocationAtIndex(i).GetAddress().GetLineEntry() + self.assertEqual(b_loc.GetLine(), 19) + in_then |= b_loc.GetColumn() == 50 + self.assertTrue(in_then) + + ## Skip gcc version less 7.1 since it doesn't support -gcolumn-info + @skipIf(compiler="gcc", compiler_version=['<', '7.1']) + def testBreakpointByLine(self): + self.build() + main_c = lldb.SBFileSpec("main.c") + _, _, _, breakpoint = lldbutil.run_to_line_breakpoint(self, main_c, 19) + self.expect("fr v did_call", substrs='0') + in_condition = False + for i in range(breakpoint.GetNumLocations()): + b_loc = breakpoint.GetLocationAtIndex(i).GetAddress().GetLineEntry() + self.assertEqual(b_loc.GetLine(), 19) + in_condition |= b_loc.GetColumn() < 30 + self.assertTrue(in_condition) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_by_line_and_column/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_by_line_and_column/main.c new file mode 100644 index 00000000000..f9adad30575 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_by_line_and_column/main.c @@ -0,0 +1,22 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int square(int x) +{ + return x * x; +} + +int main (int argc, char const *argv[]) +{ + int did_call = 0; + + // Line 20. v Column 50. + if(square(argc+1) != 0) { did_call = 1; return square(argc); } + // ^ + return square(0); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/Makefile new file mode 100644 index 00000000000..8d669cbfd2b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c a.c b.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py new file mode 100644 index 00000000000..77db8f745d7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py @@ -0,0 +1,287 @@ +""" +Test lldb breakpoint command add/list/delete. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import side_effect + + +class BreakpointCommandTestCase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528") + def not_test_breakpoint_command_sequence(self): + """Test a sequence of breakpoint command add, list, and delete.""" + self.build() + self.breakpoint_command_sequence() + + @skipIf(oslist=["windows"], bugnumber="llvm.org/pr44431") + def test_script_parameters(self): + """Test a sequence of breakpoint command add, list, and delete.""" + self.build() + self.breakpoint_command_script_parameters() + + def test_commands_on_creation(self): + self.build() + self.breakpoint_commands_on_creation() + + def setUp(self): + # 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.') + # disable "There is a running process, kill it and restart?" prompt + self.runCmd("settings set auto-confirm true") + self.addTearDownHook( + lambda: self.runCmd("settings clear auto-confirm")) + + def test_delete_all_breakpoints(self): + """Test that deleting all breakpoints works.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_symbol(self, "main") + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("breakpoint delete") + self.runCmd("process continue") + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* exited with status = 0']) + + + def breakpoint_command_sequence(self): + """Test a sequence of breakpoint command add, list, and delete.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add three breakpoints on the same line. The first time we don't specify the file, + # since the default file is the one containing main: + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + # Breakpoint 4 - set at the same location as breakpoint 1 to test + # setting breakpoint commands on two breakpoints at a time + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_locations=1, loc_exact=True) + # Make sure relative path source breakpoints work as expected. We test + # with partial paths with and without "./" prefixes. + lldbutil.run_break_set_by_file_and_line( + self, "./main.c", self.line, + num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "breakpoint_command/main.c", self.line, + num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "./breakpoint_command/main.c", self.line, + num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "breakpoint/breakpoint_command/main.c", self.line, + num_expected_locations=1, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "./breakpoint/breakpoint_command/main.c", self.line, + num_expected_locations=1, loc_exact=True) + # Test relative breakpoints with incorrect paths and make sure we get + # no breakpoint locations + lldbutil.run_break_set_by_file_and_line( + self, "invalid/main.c", self.line, + num_expected_locations=0, loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, "./invalid/main.c", self.line, + num_expected_locations=0, loc_exact=True) + # Now add callbacks for the breakpoints just created. + self.runCmd( + "breakpoint command add -s command -o 'frame variable --show-types --scope' 1 4") + self.runCmd( + "breakpoint command add -s python -o 'import side_effect; side_effect.one_liner = \"one liner was here\"' 2") + + import side_effect + self.runCmd("command script import --allow-reload ./bktptcmd.py") + + self.runCmd( + "breakpoint command add --python-function bktptcmd.function 3") + + # Check that the breakpoint commands are correctly set. + + # The breakpoint list now only contains breakpoint 1. + self.expect( + "breakpoint list", "Breakpoints 1 & 2 created", substrs=[ + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % + self.line], patterns=[ + "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % + self.line]) + + self.expect( + "breakpoint list -f", + "Breakpoints 1 & 2 created", + substrs=[ + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % + self.line], + patterns=[ + "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % + self.line, + "1.1: .+at main.c:%d:?[0-9]*, .+unresolved, hit count = 0" % + self.line, + "2.1: .+at main.c:%d:?[0-9]*, .+unresolved, hit count = 0" % + self.line]) + + self.expect("breakpoint command list 1", "Breakpoint 1 command ok", + substrs=["Breakpoint commands:", + "frame variable --show-types --scope"]) + self.expect("breakpoint command list 2", "Breakpoint 2 command ok", + substrs=["Breakpoint commands (Python):", + "import side_effect", + "side_effect.one_liner"]) + self.expect("breakpoint command list 3", "Breakpoint 3 command ok", + substrs=["Breakpoint commands (Python):", + "bktptcmd.function(frame, bp_loc, internal_dict)"]) + + self.expect("breakpoint command list 4", "Breakpoint 4 command ok", + substrs=["Breakpoint commands:", + "frame variable --show-types --scope"]) + + self.runCmd("breakpoint delete 4") + + # Next lets try some other breakpoint kinds. First break with a regular expression + # and then specify only one file. The first time we should get two locations, + # the second time only one: + + lldbutil.run_break_set_by_regexp( + self, r"._MyFunction", num_expected_locations=2) + + lldbutil.run_break_set_by_regexp( + self, + r"._MyFunction", + extra_options="-f a.c", + num_expected_locations=1) + + lldbutil.run_break_set_by_regexp( + self, + r"._MyFunction", + extra_options="-f a.c -f b.c", + num_expected_locations=2) + + # Now try a source regex breakpoint: + lldbutil.run_break_set_by_source_regexp( + self, + r"is about to return [12]0", + extra_options="-f a.c -f b.c", + num_expected_locations=2) + + lldbutil.run_break_set_by_source_regexp( + self, + r"is about to return [12]0", + extra_options="-f a.c", + num_expected_locations=1) + + # Reset our canary variables and run the program. + side_effect.one_liner = None + side_effect.bktptcmd = None + self.runCmd("run", RUN_SUCCEEDED) + + # Check the value of canary variables. + self.assertEquals("one liner was here", side_effect.one_liner) + self.assertEquals("function was here", side_effect.bktptcmd) + + # Finish the program. + self.runCmd("process continue") + + # Remove the breakpoint command associated with breakpoint 1. + self.runCmd("breakpoint command delete 1") + + # Remove breakpoint 2. + self.runCmd("breakpoint delete 2") + + self.expect( + "breakpoint command list 1", + startstr="Breakpoint 1 does not have an associated command.") + self.expect( + "breakpoint command list 2", + error=True, + startstr="error: '2' is not a currently valid breakpoint ID.") + + # The breakpoint list now only contains breakpoint 1. + self.expect( + "breakpoint list -f", + "Breakpoint 1 exists", + patterns=[ + "1: file = '.*main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" % + self.line, + "hit count = 1"]) + + # Not breakpoint 2. + self.expect( + "breakpoint list -f", + "No more breakpoint 2", + matching=False, + substrs=[ + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" % + self.line]) + + # Run the program again, with breakpoint 1 remaining. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to breakpoint 1. + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 2. + self.expect("breakpoint list -f", BREAKPOINT_HIT_TWICE, + substrs=['resolved, hit count = 2']) + + def breakpoint_command_script_parameters(self): + """Test that the frame and breakpoint location are being properly passed to the script breakpoint command function.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Add a breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + + # Now add callbacks for the breakpoints just created. + self.runCmd("breakpoint command add -s python -o 'import side_effect; side_effect.frame = str(frame); side_effect.bp_loc = str(bp_loc)' 1") + + # Reset canary variables and run. + side_effect.frame = None + side_effect.bp_loc = None + self.runCmd("run", RUN_SUCCEEDED) + + self.expect(side_effect.frame, exe=False, startstr="frame #0:") + self.expect(side_effect.bp_loc, exe=False, + patterns=["1.* where = .*main .* resolved, hit count = 1"]) + + def breakpoint_commands_on_creation(self): + """Test that setting breakpoint commands when creating the breakpoint works""" + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target.IsValid(), "Created an invalid target.") + + # Add a breakpoint. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True, + extra_options='-C bt -C "thread list" -C continue') + + bkpt = target.FindBreakpointByID(1) + self.assertTrue(bkpt.IsValid(), "Couldn't find breakpoint 1") + com_list = lldb.SBStringList() + bkpt.GetCommandLineCommands(com_list) + self.assertEqual(com_list.GetSize(), 3, "Got the wrong number of commands") + self.assertEqual(com_list.GetStringAtIndex(0), "bt", "First bt") + self.assertEqual(com_list.GetStringAtIndex(1), "thread list", "Next thread list") + self.assertEqual(com_list.GetStringAtIndex(2), "continue", "Last continue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py new file mode 100644 index 00000000000..15a31201c56 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py @@ -0,0 +1,174 @@ +""" +Test that you can set breakpoint commands successfully with the Python API's: +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import side_effect + + +class PythonBreakpointCommandSettingTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + def test_step_out_python(self): + """Test stepping out using a python breakpoint command.""" + self.build() + self.do_set_python_command_from_python() + + def test_bkpt_cmd_bad_arguments(self): + """Test what happens when pass structured data to a command:""" + self.build() + self.do_bad_args_to_python_command() + + def setUp(self): + TestBase.setUp(self) + self.main_source = "main.c" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + def do_set_python_command_from_python(self): + exe = self.getBuildArtifact("a.out") + error = lldb.SBError() + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + body_bkpt = self.target.BreakpointCreateBySourceRegex( + "Set break point at this line.", self.main_source_spec) + self.assertTrue(body_bkpt, VALID_BREAKPOINT) + + func_bkpt = self.target.BreakpointCreateBySourceRegex( + "Set break point at this line.", self.main_source_spec) + self.assertTrue(func_bkpt, VALID_BREAKPOINT) + + fancy_bkpt = self.target.BreakpointCreateBySourceRegex( + "Set break point at this line.", self.main_source_spec) + self.assertTrue(fancy_bkpt, VALID_BREAKPOINT) + + fancier_bkpt = self.target.BreakpointCreateBySourceRegex( + "Set break point at this line.", self.main_source_spec) + self.assertTrue(fancier_bkpt, VALID_BREAKPOINT) + + not_so_fancy_bkpt = self.target.BreakpointCreateBySourceRegex( + "Set break point at this line.", self.main_source_spec) + self.assertTrue(not_so_fancy_bkpt, VALID_BREAKPOINT) + + # Also test that setting a source regex breakpoint with an empty file + # spec list sets it on all files: + no_files_bkpt = self.target.BreakpointCreateBySourceRegex( + "Set a breakpoint here", lldb.SBFileSpecList(), lldb.SBFileSpecList()) + self.assertTrue(no_files_bkpt, VALID_BREAKPOINT) + num_locations = no_files_bkpt.GetNumLocations() + self.assertTrue( + num_locations >= 2, + "Got at least two breakpoint locations") + got_one_in_A = False + got_one_in_B = False + for idx in range(0, num_locations): + comp_unit = no_files_bkpt.GetLocationAtIndex(idx).GetAddress().GetSymbolContext( + lldb.eSymbolContextCompUnit).GetCompileUnit().GetFileSpec() + print("Got comp unit: ", comp_unit.GetFilename()) + if comp_unit.GetFilename() == "a.c": + got_one_in_A = True + elif comp_unit.GetFilename() == "b.c": + got_one_in_B = True + + self.assertTrue(got_one_in_A, "Failed to match the pattern in A") + self.assertTrue(got_one_in_B, "Failed to match the pattern in B") + self.target.BreakpointDelete(no_files_bkpt.GetID()) + + error = lldb.SBError() + error = body_bkpt.SetScriptCallbackBody( + "import side_effect; side_effect.callback = 'callback was here'") + self.assertTrue( + error.Success(), + "Failed to set the script callback body: %s." % + (error.GetCString())) + + self.expect("command script import --allow-reload ./bktptcmd.py") + + func_bkpt.SetScriptCallbackFunction("bktptcmd.function") + + extra_args = lldb.SBStructuredData() + stream = lldb.SBStream() + stream.Print('{"side_effect" : "I am fancy"}') + extra_args.SetFromJSON(stream) + error = fancy_bkpt.SetScriptCallbackFunction("bktptcmd.another_function", extra_args) + self.assertTrue(error.Success(), "Failed to add callback %s"%(error.GetCString())) + + stream.Clear() + stream.Print('{"side_effect" : "I am so much fancier"}') + extra_args.SetFromJSON(stream) + + # Fancier's callback is set up from the command line + id = fancier_bkpt.GetID() + self.expect("breakpoint command add -F bktptcmd.a_third_function -k side_effect -v 'I am fancier' %d"%(id)) + + # Not so fancy gets an empty extra_args: + empty_args = lldb.SBStructuredData() + error = not_so_fancy_bkpt.SetScriptCallbackFunction("bktptcmd.empty_extra_args", empty_args) + self.assertTrue(error.Success(), "Failed to add callback %s"%(error.GetCString())) + + # Clear out canary variables + side_effect.bktptcmd = None + side_effect.callback = None + side_effect.fancy = None + side_effect.fancier = None + side_effect.not_so_fancy = None + + # Now launch the process, and do not stop at entry point. + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(self.process, PROCESS_IS_VALID) + + # Now finish, and make sure the return value is correct. + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, body_bkpt) + self.assertEquals(len(threads), 1, "Stopped at inner breakpoint.") + self.thread = threads[0] + + self.assertEquals("callback was here", side_effect.callback) + self.assertEquals("function was here", side_effect.bktptcmd) + self.assertEquals("I am fancy", side_effect.fancy) + self.assertEquals("I am fancier", side_effect.fancier) + self.assertEquals("Not so fancy", side_effect.not_so_fancy) + + def do_bad_args_to_python_command(self): + exe = self.getBuildArtifact("a.out") + error = lldb.SBError() + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + + self.expect("command script import --allow-reload ./bktptcmd.py") + + bkpt = self.target.BreakpointCreateBySourceRegex( + "Set break point at this line.", self.main_source_spec) + self.assertTrue(bkpt, VALID_BREAKPOINT) + + # Pass a breakpoint command function that doesn't take extra_args, + # but pass it extra args: + + extra_args = lldb.SBStructuredData() + stream = lldb.SBStream() + stream.Print('{"side_effect" : "I am fancy"}') + extra_args.SetFromJSON(stream) + + error = bkpt.SetScriptCallbackFunction("bktptcmd.function", extra_args) + self.assertTrue(error.Fail(), "Can't pass extra args if the function doesn't take them") + + error = bkpt.SetScriptCallbackFunction("bktptcmd.useless_function", extra_args) + self.assertTrue(error.Fail(), "Can't pass extra args if the function has wrong number of args.") + + error = bkpt.SetScriptCallbackFunction("bktptcmd.nosuch_function", extra_args) + self.assertTrue(error.Fail(), "Can't pass extra args if the function doesn't exist.") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py new file mode 100644 index 00000000000..ed462653d24 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py @@ -0,0 +1,70 @@ +""" +Test _regexp-break command which uses regular expression matching to dispatch to other built in breakpoint commands. +""" + + + +import os +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class RegexpBreakCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test(self): + """Test _regexp-break command.""" + self.build() + self.regexp_break_command() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.c' + self.line = line_number( + self.source, '// Set break point at this line.') + + def regexp_break_command(self): + """Test the super consie "b" command, which is analias for _regexp-break.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + break_results = lldbutil.run_break_set_command( + self, "b %d" % + self.line) + lldbutil.check_breakpoint_result( + self, + break_results, + file_name='main.c', + line_number=self.line, + num_locations=1) + + break_results = lldbutil.run_break_set_command( + self, "b %s:%d" % (self.source, self.line)) + lldbutil.check_breakpoint_result( + self, + break_results, + file_name='main.c', + line_number=self.line, + num_locations=1) + + # Check breakpoint with full file path. + full_path = os.path.join(self.getSourceDir(), self.source) + break_results = lldbutil.run_break_set_command( + self, "b %s:%d" % (full_path, self.line)) + lldbutil.check_breakpoint_result( + self, + break_results, + file_name='main.c', + line_number=self.line, + num_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=['stopped', + 'stop reason = breakpoint']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/a.c new file mode 100644 index 00000000000..870e4a6ab16 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/a.c @@ -0,0 +1,9 @@ +#include <stdio.h> + +int +a_MyFunction () +{ + // Set a breakpoint here. + printf ("a is about to return 10.\n"); + return 10; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/b.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/b.c new file mode 100644 index 00000000000..02b78e7bd85 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/b.c @@ -0,0 +1,9 @@ +#include <stdio.h> + +int +b_MyFunction () +{ + // Set a breakpoint here. + printf ("b is about to return 20.\n"); + return 20; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py new file mode 100644 index 00000000000..e839de57fb7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py @@ -0,0 +1,23 @@ +from __future__ import print_function +import side_effect + +def useless_function(first, second): + print("I have the wrong number of arguments.") + +def function(frame, bp_loc, dict): + side_effect.bktptcmd = "function was here" + +def another_function(frame, bp_loc, extra_args, dict): + se_value = extra_args.GetValueForKey("side_effect") + se_string = se_value.GetStringValue(100) + side_effect.fancy = se_string + +def a_third_function(frame, bp_loc, extra_args, dict): + se_value = extra_args.GetValueForKey("side_effect") + se_string = se_value.GetStringValue(100) + side_effect.fancier = se_string + +def empty_extra_args(frame, bp_loc, extra_args, dict): + if extra_args.IsValid(): + side_effect.not_so_fancy = "Extra args should not be valid" + side_effect.not_so_fancy = "Not so fancy" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/main.c new file mode 100644 index 00000000000..8bebb9455a6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/main.c @@ -0,0 +1,16 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main (int argc, char const *argv[]) +{ + // Add a body to the function, so we can set more than one + // breakpoint in it. + static volatile int var = 0; + var++; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/side_effect.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/side_effect.py new file mode 100644 index 00000000000..ef4ab2b159c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/side_effect.py @@ -0,0 +1,5 @@ +""" +A dummy module for testing the execution of various breakpoint commands. A +command will modify a global variable in this module and test will check its +value. +""" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/Makefile new file mode 100644 index 00000000000..695335e068c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py new file mode 100644 index 00000000000..de9a47d8c20 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py @@ -0,0 +1,223 @@ +""" +Test breakpoint conditions with 'breakpoint modify -c <expr> id'. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointConditionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_breakpoint_condition_and_run_command(self): + """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'.""" + self.build() + self.breakpoint_conditions() + + def test_breakpoint_condition_inline_and_run_command(self): + """Exercise breakpoint condition inline with 'breakpoint set'.""" + self.build() + self.breakpoint_conditions(inline=True) + + @add_test_categories(['pyapi']) + def test_breakpoint_condition_and_python_api(self): + """Use Python APIs to set breakpoint conditions.""" + self.build() + self.breakpoint_conditions_python() + + @add_test_categories(['pyapi']) + def test_breakpoint_invalid_condition_and_python_api(self): + """Use Python APIs to set breakpoint conditions.""" + self.build() + self.breakpoint_invalid_conditions_python() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to of function 'c'. + self.line1 = line_number( + 'main.c', '// Find the line number of function "c" here.') + self.line2 = line_number( + 'main.c', "// Find the line number of c's parent call here.") + + def breakpoint_conditions(self, inline=False): + """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + if inline: + # Create a breakpoint by function name 'c' and set the condition. + lldbutil.run_break_set_by_symbol( + self, + "c", + extra_options="-c 'val == 3'", + num_expected_locations=1, + sym_exact=True) + else: + # Create a breakpoint by function name 'c'. + lldbutil.run_break_set_by_symbol( + self, "c", num_expected_locations=1, sym_exact=True) + + # 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) + + # The process should be stopped at this point. + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* stopped']) + + # 'frame variable --show-types val' should return 3 due to breakpoint condition. + self.expect( + "frame variable --show-types val", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) val = 3') + + # Also check the hit count, which should be 3, by design. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=["resolved = 1", + "Condition: val == 3", + "hit count = 1"]) + + # The frame #0 should correspond to main.c:36, the executable statement + # in function name 'c'. And the parent frame should point to + # main.c:24. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_CONDITION, + #substrs = ["stop reason = breakpoint"], + patterns=["frame #0.*main.c:%d" % self.line1, + "frame #1.*main.c:%d" % self.line2]) + + # Test that "breakpoint modify -c ''" clears the condition for the last + # created breakpoint, so that when the breakpoint hits, val == 1. + self.runCmd("process kill") + self.runCmd("breakpoint modify -c ''") + self.expect( + "breakpoint list -f", + BREAKPOINT_STATE_CORRECT, + matching=False, + substrs=["Condition:"]) + + # Now run the program again. + self.runCmd("run", RUN_SUCCEEDED) + + # The process should be stopped at this point. + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* stopped']) + + # 'frame variable --show-types val' should return 1 since it is the first breakpoint hit. + self.expect( + "frame variable --show-types val", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) val = 1') + + self.runCmd("process kill") + + def breakpoint_conditions_python(self): + """Use Python APIs to set breakpoint conditions.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # We didn't associate a thread index with the breakpoint, so it should + # be invalid. + self.assertTrue(breakpoint.GetThreadIndex() == lldb.UINT32_MAX, + "The thread index should be invalid") + # The thread name should be invalid, too. + self.assertTrue(breakpoint.GetThreadName() is None, + "The thread name should be invalid") + + # Let's set the thread index for this breakpoint and verify that it is, + # indeed, being set correctly. + # There's only one thread for the process. + breakpoint.SetThreadIndex(1) + self.assertTrue(breakpoint.GetThreadIndex() == 1, + "The thread index has been set correctly") + + # Get the breakpoint location from breakpoint after we verified that, + # indeed, it has one location. + location = breakpoint.GetLocationAtIndex(0) + self.assertTrue(location and + location.IsEnabled(), + VALID_BREAKPOINT_LOCATION) + + # Set the condition on the breakpoint location. + location.SetCondition('val == 3') + self.expect(location.GetCondition(), exe=False, + startstr='val == 3') + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.line1 and the break condition should hold. + from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + var = frame0.FindValue('val', lldb.eValueTypeVariableArgument) + self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1 and + var.GetValue() == '3') + + # The hit count for the breakpoint should be 1. + self.assertTrue(breakpoint.GetHitCount() == 1) + + # Test that the condition expression didn't create a result variable: + options = lldb.SBExpressionOptions() + value = frame0.EvaluateExpression("$0", options) + self.assertTrue(value.GetError().Fail(), + "Conditions should not make result variables.") + process.Continue() + + def breakpoint_invalid_conditions_python(self): + """Use Python APIs to set breakpoint conditions.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Set the condition on the breakpoint. + breakpoint.SetCondition('no_such_variable == not_this_one_either') + self.expect(breakpoint.GetCondition(), exe=False, + startstr='no_such_variable == not_this_one_either') + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.line1 and the break condition should hold. + from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + var = frame0.FindValue('val', lldb.eValueTypeVariableArgument) + self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1) + + # The hit count for the breakpoint should be 1. + self.assertTrue(breakpoint.GetHitCount() == 1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/main.c new file mode 100644 index 00000000000..c830b17a3ce --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/main.c @@ -0,0 +1,53 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// 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); // Find the line number of c's parent call here. + + 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); + + for (int i = 0; i < 2; ++i) + printf("Loop\n"); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_hit_count/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_hit_count/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_hit_count/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_hit_count/TestBreakpointHitCount.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_hit_count/TestBreakpointHitCount.py new file mode 100644 index 00000000000..0254bf02366 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_hit_count/TestBreakpointHitCount.py @@ -0,0 +1,133 @@ +""" +Test breakpoint hit count features. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointHitCountTestCase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + def test_breakpoint_location_hit_count(self): + """Use Python APIs to check breakpoint hit count.""" + self.build() + self.do_test_breakpoint_location_hit_count() + + def test_breakpoint_one_shot(self): + """Check that one-shot breakpoints trigger only once.""" + self.build() + + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.runCmd("tb a") + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + + frame0 = thread.GetFrameAtIndex(0) + self.assertTrue(frame0.GetFunctionName() == "a(int)" or frame0.GetFunctionName() == "int a(int)"); + + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateExited) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.a_int_body_line_no = line_number( + 'main.cpp', '// Breakpoint Location 1') + self.a_float_body_line_no = line_number( + 'main.cpp', '// Breakpoint Location 2') + + def do_test_breakpoint_location_hit_count(self): + """Use Python APIs to check breakpoint hit count.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create a breakpoint in main.cpp by name 'a', + # there should be two locations. + breakpoint = target.BreakpointCreateByName('a', 'a.out') + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 2, + VALID_BREAKPOINT) + + # Verify all breakpoint locations are enabled. + location1 = breakpoint.GetLocationAtIndex(0) + self.assertTrue(location1 and + location1.IsEnabled(), + VALID_BREAKPOINT_LOCATION) + + location2 = breakpoint.GetLocationAtIndex(1) + self.assertTrue(location2 and + location2.IsEnabled(), + VALID_BREAKPOINT_LOCATION) + + # Launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Verify 1st breakpoint location is hit. + from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + + frame0 = thread.GetFrameAtIndex(0) + location1 = breakpoint.FindLocationByAddress(frame0.GetPC()) + self.assertTrue( + frame0.GetLineEntry().GetLine() == self.a_int_body_line_no, + "Stopped in int a(int)") + self.assertTrue(location1) + self.assertEqual(location1.GetHitCount(), 1) + self.assertEqual(breakpoint.GetHitCount(), 1) + + process.Continue() + + # Verify 2nd breakpoint location is hit. + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + + frame0 = thread.GetFrameAtIndex(0) + location2 = breakpoint.FindLocationByAddress(frame0.GetPC()) + self.assertTrue( + frame0.GetLineEntry().GetLine() == self.a_float_body_line_no, + "Stopped in float a(float)") + self.assertTrue(location2) + self.assertEqual(location2.GetHitCount(), 1) + self.assertEqual(location1.GetHitCount(), 1) + self.assertEqual(breakpoint.GetHitCount(), 2) + + process.Continue() + + # Verify 2nd breakpoint location is hit again. + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + + self.assertEqual(location2.GetHitCount(), 2) + self.assertEqual(location1.GetHitCount(), 1) + self.assertEqual(breakpoint.GetHitCount(), 3) + + process.Continue() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_hit_count/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_hit_count/main.cpp new file mode 100644 index 00000000000..9fc133f2400 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_hit_count/main.cpp @@ -0,0 +1,26 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int a(int val) +{ + return val; // Breakpoint Location 1 +} + +float a(float val) +{ + return val; // Breakpoint Location 2 +} + +int main (int argc, char const *argv[]) +{ + int A1 = a(1); + float A2 = a(2.0f); + float A3 = a(3.0f); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/Makefile new file mode 100644 index 00000000000..2c00681fa22 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/Makefile @@ -0,0 +1,8 @@ +CXX_SOURCES := main.cpp + +ifneq (,$(findstring icc,$(CC))) + CXXFLAGS_EXTRAS := -debug inline-debug-info +endif + + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py new file mode 100644 index 00000000000..82f554e2a2b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py @@ -0,0 +1,57 @@ +""" +Test lldb breakpoint ids. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class BreakpointIDTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test(self): + self.build() + + exe = self.getBuildArtifact("a.out") + self.expect("file " + exe, + patterns=["Current executable set to .*a.out"]) + + bpno = lldbutil.run_break_set_by_symbol( + self, 'product', num_expected_locations=-1, sym_exact=False) + self.assertTrue(bpno == 1, "First breakpoint number is 1.") + + bpno = lldbutil.run_break_set_by_symbol( + self, 'sum', num_expected_locations=-1, sym_exact=False) + self.assertTrue(bpno == 2, "Second breakpoint number is 2.") + + bpno = lldbutil.run_break_set_by_symbol( + self, 'junk', num_expected_locations=0, sym_exact=False) + self.assertTrue(bpno == 3, "Third breakpoint number is 3.") + + self.expect( + "breakpoint disable 1.1 - 2.2 ", + COMMAND_FAILED_AS_EXPECTED, + error=True, + startstr="error: Invalid range: Ranges that specify particular breakpoint locations must be within the same major breakpoint; you specified two different major breakpoints, 1 and 2.") + + self.expect( + "breakpoint disable 2 - 2.2", + COMMAND_FAILED_AS_EXPECTED, + error=True, + startstr="error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.") + + self.expect( + "breakpoint disable 2.1 - 2", + COMMAND_FAILED_AS_EXPECTED, + error=True, + startstr="error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.") + + self.expect("breakpoint disable 2.1 - 2.2", + startstr="2 breakpoints disabled.") + + self.expect("breakpoint enable 2.*", + patterns=[".* breakpoints enabled."]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/main.cpp new file mode 100644 index 00000000000..3c98e147f22 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/main.cpp @@ -0,0 +1,64 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <cstdlib> +#include <string> +#include <fstream> +#include <iostream> + + +#define INLINE inline __attribute__((always_inline)) + +INLINE int +product (int x, int y) +{ + int result = x * y; + return result; +} + +INLINE int +sum (int a, int b) +{ + int result = a + b; + return result; +} + +int +strange_max (int m, int n) +{ + if (m > n) + return m; + else if (n > m) + return n; + else + return 0; +} + +int +foo (int i, int j) +{ + if (strange_max (i, j) == i) + return product (i, j); + else if (strange_max (i, j) == j) + return sum (i, j); + else + return product (sum (i, i), sum (j, j)); +} + +int +main(int argc, char const *argv[]) +{ + + int array[3]; + + array[0] = foo (1238, 78392); + array[1] = foo (379265, 23674); + array[2] = foo (872934, 234); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py new file mode 100644 index 00000000000..3fa81aeadf9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py @@ -0,0 +1,150 @@ +""" +Test breakpoint ignore count features. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointIgnoreCountTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfWindows # This test will hang on windows llvm.org/pr21753 + def test_with_run_command(self): + """Exercise breakpoint ignore count with 'breakpoint set -i <count>'.""" + self.build() + self.breakpoint_ignore_count() + + @add_test_categories(['pyapi']) + @skipIfWindows # This test will hang on windows llvm.org/pr21753 + def test_with_python_api(self): + """Use Python APIs to set breakpoint ignore count.""" + self.build() + self.breakpoint_ignore_count_python() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to of function 'c'. + self.line1 = line_number( + 'main.c', '// Find the line number of function "c" here.') + self.line2 = line_number( + 'main.c', '// b(2) -> c(2) Find the call site of b(2).') + self.line3 = line_number( + 'main.c', '// a(3) -> c(3) Find the call site of c(3).') + self.line4 = line_number( + 'main.c', '// a(3) -> c(3) Find the call site of a(3).') + self.line5 = line_number( + 'main.c', '// Find the call site of c in main.') + + def breakpoint_ignore_count(self): + """Exercise breakpoint ignore count with 'breakpoint set -i <count>'.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Create a breakpoint in main.c at line1. + lldbutil.run_break_set_by_file_and_line( + self, + 'main.c', + self.line1, + extra_options='-i 1', + num_expected_locations=1, + loc_exact=True) + + # Now run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # The process should be stopped at this point. + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* stopped']) + + # Also check the hit count, which should be 2, due to ignore count of + # 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_THRICE, + substrs=["resolved = 1", + "hit count = 2"]) + + # The frame #0 should correspond to main.c:37, the executable statement + # in function name 'c'. And frame #2 should point to main.c:45. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT, + #substrs = ["stop reason = breakpoint"], + patterns=["frame #0.*main.c:%d" % self.line1, + "frame #2.*main.c:%d" % self.line2]) + + # continue -i 1 is the same as setting the ignore count to 1 again, try that: + # Now run the program. + self.runCmd("process continue -i 1", RUN_SUCCEEDED) + + # The process should be stopped at this point. + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* stopped']) + + # Also check the hit count, which should be 2, due to ignore count of + # 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_THRICE, + substrs=["resolved = 1", + "hit count = 4"]) + + # The frame #0 should correspond to main.c:37, the executable statement + # in function name 'c'. And frame #2 should point to main.c:45. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT, + #substrs = ["stop reason = breakpoint"], + patterns=["frame #0.*main.c:%d" % self.line1, + "frame #1.*main.c:%d" % self.line5]) + + def breakpoint_ignore_count_python(self): + """Use Python APIs to set breakpoint ignore count.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Get the breakpoint location from breakpoint after we verified that, + # indeed, it has one location. + location = breakpoint.GetLocationAtIndex(0) + self.assertTrue(location and + location.IsEnabled(), + VALID_BREAKPOINT_LOCATION) + + # Set the ignore count on the breakpoint location. + location.SetIgnoreCount(2) + self.assertTrue(location.GetIgnoreCount() == 2, + "SetIgnoreCount() works correctly") + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame#0 should be on main.c:37, frame#1 should be on main.c:25, and + # frame#2 should be on main.c:48. + # lldbutil.print_stacktraces(process) + from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + frame0 = thread.GetFrameAtIndex(0) + frame1 = thread.GetFrameAtIndex(1) + frame2 = thread.GetFrameAtIndex(2) + self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1 and + frame1.GetLineEntry().GetLine() == self.line3 and + frame2.GetLineEntry().GetLine() == self.line4, + STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT) + + # The hit count for the breakpoint should be 3. + self.assertTrue(breakpoint.GetHitCount() == 3) + + process.Continue() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/main.c new file mode 100644 index 00000000000..b1ed4465c1d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/main.c @@ -0,0 +1,53 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to demonstrate the capability of the lldb command +// "breakpoint modify -i <count> breakpt-id" to set the number of times a +// breakpoint is skipped before stopping. Ignore count can also be set upon +// breakpoint creation by 'breakpoint set ... -i <count>'. + +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); // a(3) -> c(3) Find the call site of c(3). + + 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) Find the call site of b(2). + printf("b(2) returns %d\n", B2); + + int A3 = a(3); // a(3) -> c(3) Find the call site of a(3). + printf("a(3) returns %d\n", A3); + + int C1 = c(5); // Find the call site of c in main. + printf ("c(5) returns %d\n", C1); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/Makefile new file mode 100644 index 00000000000..692ba173228 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c + +include Makefile.rules + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py new file mode 100644 index 00000000000..ff087159f61 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/TestAvoidBreakpointInDelaySlot.py @@ -0,0 +1,87 @@ +""" +Test specific to MIPS +""" + +from __future__ import print_function + +import re +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class AvoidBreakpointInDelaySlotAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(archs=no_match(re.compile('mips*'))) + def test(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.expect("file " + exe, + patterns=["Current executable set to .*a.out.*"]) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByName('main', 'a.out') + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + list = target.FindFunctions('foo', lldb.eFunctionNameTypeAuto) + self.assertTrue(list.GetSize() == 1) + sc = list.GetContextAtIndex(0) + self.assertTrue(sc.GetSymbol().GetName() == "foo") + function = sc.GetFunction() + self.assertTrue(function) + self.function(function, target) + + def function(self, function, target): + """Iterate over instructions in function and place a breakpoint on delay slot instruction""" + # Get the list of all instructions in the function + insts = function.GetInstructions(target) + print(insts) + i = 0 + for inst in insts: + if (inst.HasDelaySlot()): + # Remember the address of branch instruction. + branchinstaddress = inst.GetAddress().GetLoadAddress(target) + + # Get next instruction i.e delay slot instruction. + delayinst = insts.GetInstructionAtIndex(i + 1) + delayinstaddr = delayinst.GetAddress().GetLoadAddress(target) + + # Set breakpoint on delay slot instruction + breakpoint = target.BreakpointCreateByAddress(delayinstaddr) + + # Verify the breakpoint. + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + # Get the location from breakpoint + location = breakpoint.GetLocationAtIndex(0) + + # Get the address where breakpoint is actually set. + bpaddr = location.GetLoadAddress() + + # Breakpoint address should be adjusted to the address of + # branch instruction. + self.assertTrue(branchinstaddress == bpaddr) + i += 1 + else: + i += 1 + +if __name__ == '__main__': + import atexit + lldb.SBDebugger.Initialize() + atexit.register(lambda: lldb.SBDebugger.Terminate()) + unittest2.main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/main.c new file mode 100644 index 00000000000..bc3eceea769 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_in_delayslot/main.c @@ -0,0 +1,21 @@ +#include <stdio.h> + +foo (int a, int b) +{ + int c; + if (a<=b) + c=b-a; + else + c=b+a; + return c; +} + +int main() +{ + int a=7, b=8, c; + + c = foo(a, b); + +return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/Makefile new file mode 100644 index 00000000000..283cc1b8944 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := a.c +CXX_SOURCES := main.cpp b.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py new file mode 100644 index 00000000000..ceffb11f8b7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py @@ -0,0 +1,127 @@ +""" +Test that the language option for breakpoints works correctly +parser. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class TestBreakpointLanguage(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def check_location_file(self, bp, loc, test_name): + bp_loc = bp.GetLocationAtIndex(loc) + addr = bp_loc.GetAddress() + comp_unit = addr.GetCompileUnit() + comp_name = comp_unit.GetFileSpec().GetFilename() + return comp_name == test_name + + def test_regex_breakpoint_language(self): + """Test that the name regex breakpoint commands obey the language filter.""" + + self.build() + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + error = lldb.SBError() + # Don't read in dependencies so we don't come across false matches that + # add unwanted breakpoint hits. + self.target = self.dbg.CreateTarget(exe, None, None, False, error) + self.assertTrue(self.target, VALID_TARGET) + + cpp_bp = self.target.BreakpointCreateByRegex( + "func_from", + lldb.eLanguageTypeC_plus_plus, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + cpp_bp.GetNumLocations() == 1, + "Only one C++ symbol matches") + self.assertTrue(self.check_location_file(cpp_bp, 0, "b.cpp")) + + c_bp = self.target.BreakpointCreateByRegex( + "func_from", + lldb.eLanguageTypeC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + c_bp.GetNumLocations() == 1, + "Only one C symbol matches") + self.assertTrue(self.check_location_file(c_bp, 0, "a.c")) + + objc_bp = self.target.BreakpointCreateByRegex( + "func_from", + lldb.eLanguageTypeObjC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + objc_bp.GetNumLocations() == 0, + "No ObjC symbol matches") + + def test_by_name_breakpoint_language(self): + """Test that the name regex breakpoint commands obey the language filter.""" + + self.build() + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + error = lldb.SBError() + # Don't read in dependencies so we don't come across false matches that + # add unwanted breakpoint hits. + self.target = self.dbg.CreateTarget(exe, None, None, False, error) + self.assertTrue(self.target, VALID_TARGET) + + cpp_bp = self.target.BreakpointCreateByName( + "func_from_cpp", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeC_plus_plus, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + cpp_bp.GetNumLocations() == 1, + "Only one C++ symbol matches") + self.assertTrue(self.check_location_file(cpp_bp, 0, "b.cpp")) + + no_cpp_bp = self.target.BreakpointCreateByName( + "func_from_c", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeC_plus_plus, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + no_cpp_bp.GetNumLocations() == 0, + "And the C one doesn't match") + + c_bp = self.target.BreakpointCreateByName( + "func_from_c", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + c_bp.GetNumLocations() == 1, + "Only one C symbol matches") + self.assertTrue(self.check_location_file(c_bp, 0, "a.c")) + + no_c_bp = self.target.BreakpointCreateByName( + "func_from_cpp", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + no_c_bp.GetNumLocations() == 0, + "And the C++ one doesn't match") + + objc_bp = self.target.BreakpointCreateByName( + "func_from_cpp", + lldb.eFunctionNameTypeAuto, + lldb.eLanguageTypeObjC, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + objc_bp.GetNumLocations() == 0, + "No ObjC symbol matches") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/a.c new file mode 100644 index 00000000000..b90e2bdcca5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/a.c @@ -0,0 +1,5 @@ +int +func_from_c () +{ + return 5; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/b.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/b.cpp new file mode 100644 index 00000000000..89373445b9a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/b.cpp @@ -0,0 +1,5 @@ +int +func_from_cpp() +{ + return 10; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/main.cpp new file mode 100644 index 00000000000..b7d00a60202 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/main.cpp @@ -0,0 +1,11 @@ +#include <stdio.h> +extern "C" int func_from_c(); +extern int func_from_cpp(); + +int +main() +{ + func_from_c(); + func_from_cpp(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/Makefile new file mode 100644 index 00000000000..9645fd9cc8d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/Makefile @@ -0,0 +1,7 @@ +C_SOURCES := main.c + +ifneq (,$(findstring icc,$(CC))) + CFLAGS_EXTRAS := -debug inline-debug-info +endif + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py new file mode 100644 index 00000000000..334b0f0f159 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py @@ -0,0 +1,196 @@ +""" +Test breakpoint commands for a breakpoint ID with multiple locations. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointLocationsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528") + def test_enable(self): + """Test breakpoint enable/disable for a breakpoint ID with multiple locations.""" + self.build() + self.breakpoint_locations_test() + + def test_shadowed_cond_options(self): + """Test that options set on the breakpoint and location behave correctly.""" + self.build() + self.shadowed_bkpt_cond_test() + + def test_shadowed_command_options(self): + """Test that options set on the breakpoint and location behave correctly.""" + self.build() + self.shadowed_bkpt_command_test() + + def setUp(self): + # 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.') + + def set_breakpoint (self): + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, "Target %s is not valid"%(exe)) + + # This should create a breakpoint with 3 locations. + + bkpt = target.BreakpointCreateByLocation("main.c", self.line) + + # The breakpoint list should show 3 locations. + self.assertEqual(bkpt.GetNumLocations(), 3, "Wrong number of locations") + + self.expect( + "breakpoint list -f", + "Breakpoint locations shown correctly", + substrs=[ + "1: file = 'main.c', line = %d, exact_match = 0, locations = 3" % + self.line], + patterns=[ + "where = a.out`func_inlined .+unresolved, hit count = 0", + "where = a.out`main .+\[inlined\].+unresolved, hit count = 0"]) + + return bkpt + + def shadowed_bkpt_cond_test(self): + """Test that options set on the breakpoint and location behave correctly.""" + # Breakpoint option propagation from bkpt to loc used to be done the first time + # a breakpoint location option was specifically set. After that the other options + # on that location would stop tracking the breakpoint. That got fixed, and this test + # makes sure only the option touched is affected. + + bkpt = self.set_breakpoint() + bkpt_cond = "1 == 0" + bkpt.SetCondition(bkpt_cond) + self.assertEqual(bkpt.GetCondition(), bkpt_cond,"Successfully set condition") + self.assertTrue(bkpt.location[0].GetCondition() == bkpt.GetCondition(), "Conditions are the same") + + # Now set a condition on the locations, make sure that this doesn't effect the bkpt: + bkpt_loc_1_cond = "1 == 1" + bkpt.location[0].SetCondition(bkpt_loc_1_cond) + self.assertEqual(bkpt.location[0].GetCondition(), bkpt_loc_1_cond, "Successfully changed location condition") + self.assertNotEqual(bkpt.GetCondition(), bkpt_loc_1_cond, "Changed location changed Breakpoint condition") + self.assertEqual(bkpt.location[1].GetCondition(), bkpt_cond, "Changed another location's condition") + + # Now make sure that setting one options doesn't fix the value of another: + bkpt.SetIgnoreCount(10) + self.assertEqual(bkpt.GetIgnoreCount(), 10, "Set the ignore count successfully") + self.assertEqual(bkpt.location[0].GetIgnoreCount(), 10, "Location doesn't track top-level bkpt.") + + # Now make sure resetting the condition to "" resets the tracking: + bkpt.location[0].SetCondition("") + bkpt_new_cond = "1 == 3" + bkpt.SetCondition(bkpt_new_cond) + self.assertEqual(bkpt.location[0].GetCondition(), bkpt_new_cond, "Didn't go back to tracking condition") + + def shadowed_bkpt_command_test(self): + """Test that options set on the breakpoint and location behave correctly.""" + # Breakpoint option propagation from bkpt to loc used to be done the first time + # a breakpoint location option was specifically set. After that the other options + # on that location would stop tracking the breakpoint. That got fixed, and this test + # makes sure only the option touched is affected. + + bkpt = self.set_breakpoint() + commands = ["AAAAAA", "BBBBBB", "CCCCCC"] + str_list = lldb.SBStringList() + str_list.AppendList(commands, len(commands)) + + bkpt.SetCommandLineCommands(str_list) + cmd_list = lldb.SBStringList() + bkpt.GetCommandLineCommands(cmd_list) + list_size = str_list.GetSize() + self.assertEqual(cmd_list.GetSize() , list_size, "Added the right number of commands") + for i in range(0,list_size): + self.assertEqual(str_list.GetStringAtIndex(i), cmd_list.GetStringAtIndex(i), "Mismatched commands.") + + commands = ["DDDDDD", "EEEEEE", "FFFFFF", "GGGGGG"] + loc_list = lldb.SBStringList() + loc_list.AppendList(commands, len(commands)) + bkpt.location[1].SetCommandLineCommands(loc_list) + loc_cmd_list = lldb.SBStringList() + bkpt.location[1].GetCommandLineCommands(loc_cmd_list) + + loc_list_size = loc_list.GetSize() + + # Check that the location has the right commands: + self.assertEqual(loc_cmd_list.GetSize() , loc_list_size, "Added the right number of commands to location") + for i in range(0,loc_list_size): + self.assertEqual(loc_list.GetStringAtIndex(i), loc_cmd_list.GetStringAtIndex(i), "Mismatched commands.") + + # Check that we didn't mess up the breakpoint level commands: + self.assertEqual(cmd_list.GetSize() , list_size, "Added the right number of commands") + for i in range(0,list_size): + self.assertEqual(str_list.GetStringAtIndex(i), cmd_list.GetStringAtIndex(i), "Mismatched commands.") + + # And check we didn't mess up another location: + untouched_loc_cmds = lldb.SBStringList() + bkpt.location[0].GetCommandLineCommands(untouched_loc_cmds) + self.assertEqual(untouched_loc_cmds.GetSize() , 0, "Changed the wrong location") + + def breakpoint_locations_test(self): + """Test breakpoint enable/disable for a breakpoint ID with multiple locations.""" + self.set_breakpoint() + + # The 'breakpoint disable 3.*' command should fail gracefully. + self.expect("breakpoint disable 3.*", + "Disabling an invalid breakpoint should fail gracefully", + error=True, + startstr="error: '3' is not a valid breakpoint ID.") + + # The 'breakpoint disable 1.*' command should disable all 3 locations. + self.expect( + "breakpoint disable 1.*", + "All 3 breakpoint locatons disabled correctly", + startstr="3 breakpoints disabled.") + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should not stopped on any breakpoint at all. + self.expect("process status", "No stopping on any disabled breakpoint", + patterns=["^Process [0-9]+ exited with status = 0"]) + + # The 'breakpoint enable 1.*' command should enable all 3 breakpoints. + self.expect( + "breakpoint enable 1.*", + "All 3 breakpoint locatons enabled correctly", + startstr="3 breakpoints enabled.") + + # The 'breakpoint disable 1.1' command should disable 1 location. + self.expect( + "breakpoint disable 1.1", + "1 breakpoint locatons disabled correctly", + startstr="1 breakpoints disabled.") + + # Run the program again. We should stop on the two breakpoint + # locations. + self.runCmd("run", RUN_SUCCEEDED) + + # Stopped once. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."]) + + # Continue the program, there should be another stop. + self.runCmd("process continue") + + # Stopped again. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."]) + + # At this point, 1.1 has a hit count of 0 and the other a hit count of + # 1". + self.expect( + "breakpoint list -f", + "The breakpoints should report correct hit counts", + patterns=[ + "1\.1: .+ unresolved, hit count = 0 +Options: disabled", + "1\.2: .+ resolved, hit count = 1", + "1\.3: .+ resolved, hit count = 1"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/main.c new file mode 100644 index 00000000000..7ec3ded67b7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/main.c @@ -0,0 +1,43 @@ +#include <stdio.h> + +#define INLINE inline __attribute__((always_inline)) + +int +func_not_inlined (void) +{ + printf ("Called func_not_inlined.\n"); + return 0; +} + +INLINE int +func_inlined (void) +{ + static int func_inline_call_count = 0; + 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; // Set break point at this line. +} + +extern int func_inlined (void); + +int +main (int argc, char **argv) +{ + printf ("Starting...\n"); + + int (*func_ptr) (void); + func_ptr = func_inlined; + + int a = func_inlined(); + printf("First call to func_inlined() returns: %d.\n", a); + + func_not_inlined (); + + func_ptr (); + + printf("Last call to func_inlined() returns: %d.\n", func_inlined ()); + return 0; +} + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_names/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_names/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_names/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_names/TestBreakpointNames.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_names/TestBreakpointNames.py new file mode 100644 index 00000000000..1212ad46d28 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_names/TestBreakpointNames.py @@ -0,0 +1,370 @@ +""" +Test breakpoint names. +""" + + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointNames(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + def test_setting_names(self): + """Use Python APIs to test that we can set breakpoint names.""" + self.build() + self.setup_target() + self.do_check_names() + + def test_illegal_names(self): + """Use Python APIs to test that we don't allow illegal names.""" + self.build() + self.setup_target() + self.do_check_illegal_names() + + def test_using_names(self): + """Use Python APIs to test that operations on names works correctly.""" + self.build() + self.setup_target() + self.do_check_using_names() + + def test_configuring_names(self): + """Use Python APIs to test that configuring options on breakpoint names works correctly.""" + self.build() + self.make_a_dummy_name() + self.setup_target() + self.do_check_configuring_names() + + def test_configuring_permissions_sb(self): + """Use Python APIs to test that configuring permissions on names works correctly.""" + self.build() + self.setup_target() + self.do_check_configuring_permissions_sb() + + def test_configuring_permissions_cli(self): + """Use Python APIs to test that configuring permissions on names works correctly.""" + self.build() + self.setup_target() + self.do_check_configuring_permissions_cli() + + def setup_target(self): + exe = self.getBuildArtifact("a.out") + + # Create a targets we are making breakpoint in and copying to: + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + self.main_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "main.c")) + + def check_name_in_target(self, bkpt_name): + name_list = lldb.SBStringList() + self.target.GetBreakpointNames(name_list) + found_it = False + for name in name_list: + if name == bkpt_name: + found_it = True + break + self.assertTrue(found_it, "Didn't find the name %s in the target's name list:"%(bkpt_name)) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # These are the settings we're going to be putting into names & breakpoints: + self.bp_name_string = "ABreakpoint" + self.is_one_shot = True + self.ignore_count = 1000 + self.condition = "1 == 2" + self.auto_continue = True + self.tid = 0xaaaa + self.tidx = 10 + self.thread_name = "Fooey" + self.queue_name = "Blooey" + self.cmd_list = lldb.SBStringList() + self.cmd_list.AppendString("frame var") + self.cmd_list.AppendString("bt") + self.help_string = "I do something interesting" + + + def do_check_names(self): + """Use Python APIs to check that we can set & retrieve breakpoint names""" + bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) + bkpt_name = "ABreakpoint" + other_bkpt_name = "_AnotherBreakpoint" + + # Add a name and make sure we match it: + success = bkpt.AddName(bkpt_name) + self.assertTrue(success, "We couldn't add a legal name to a breakpoint.") + + matches = bkpt.MatchesName(bkpt_name) + self.assertTrue(matches, "We didn't match the name we just set") + + # Make sure we don't match irrelevant names: + matches = bkpt.MatchesName("NotABreakpoint") + self.assertTrue(not matches, "We matched a name we didn't set.") + + # Make sure the name is also in the target: + self.check_name_in_target(bkpt_name) + + # Add another name, make sure that works too: + bkpt.AddName(other_bkpt_name) + + matches = bkpt.MatchesName(bkpt_name) + self.assertTrue(matches, "Adding a name means we didn't match the name we just set") + self.check_name_in_target(other_bkpt_name) + + # Remove the name and make sure we no longer match it: + bkpt.RemoveName(bkpt_name) + matches = bkpt.MatchesName(bkpt_name) + self.assertTrue(not matches,"We still match a name after removing it.") + + # Make sure the name list has the remaining name: + name_list = lldb.SBStringList() + bkpt.GetNames(name_list) + num_names = name_list.GetSize() + self.assertTrue(num_names == 1, "Name list has %d items, expected 1."%(num_names)) + + name = name_list.GetStringAtIndex(0) + self.assertTrue(name == other_bkpt_name, "Remaining name was: %s expected %s."%(name, other_bkpt_name)) + + def do_check_illegal_names(self): + """Use Python APIs to check that we reject illegal names.""" + bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) + bad_names = ["-CantStartWithADash", + "1CantStartWithANumber", + "^CantStartWithNonAlpha", + "CantHave-ADash", + "Cant Have Spaces"] + for bad_name in bad_names: + success = bkpt.AddName(bad_name) + self.assertTrue(not success,"We allowed an illegal name: %s"%(bad_name)) + bp_name = lldb.SBBreakpointName(self.target, bad_name) + self.assertFalse(bp_name.IsValid(), "We made a breakpoint name with an illegal name: %s"%(bad_name)); + + retval =lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand("break set -n whatever -N '%s'"%(bad_name), retval) + self.assertTrue(not retval.Succeeded(), "break set succeeded with: illegal name: %s"%(bad_name)) + + def do_check_using_names(self): + """Use Python APIs to check names work in place of breakpoint ID's.""" + + # Create a dummy breakpoint to use up ID 1 + _ = self.target.BreakpointCreateByLocation(self.main_file_spec, 30) + + # Create a breakpiont to test with + bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) + bkpt_name = "ABreakpoint" + bkpt_id = bkpt.GetID() + other_bkpt_name= "_AnotherBreakpoint" + + # Add a name and make sure we match it: + success = bkpt.AddName(bkpt_name) + self.assertTrue(success, "We couldn't add a legal name to a breakpoint.") + + bkpts = lldb.SBBreakpointList(self.target) + self.target.FindBreakpointsByName(bkpt_name, bkpts) + + self.assertTrue(bkpts.GetSize() == 1, "One breakpoint matched.") + found_bkpt = bkpts.GetBreakpointAtIndex(0) + self.assertTrue(bkpt.GetID() == found_bkpt.GetID(),"The right breakpoint.") + self.assertTrue(bkpt.GetID() == bkpt_id,"With the same ID as before.") + + retval = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand("break disable %s"%(bkpt_name), retval) + self.assertTrue(retval.Succeeded(), "break disable failed with: %s."%(retval.GetError())) + self.assertTrue(not bkpt.IsEnabled(), "We didn't disable the breakpoint.") + + # Also make sure we don't apply commands to non-matching names: + self.dbg.GetCommandInterpreter().HandleCommand("break modify --one-shot 1 %s"%(other_bkpt_name), retval) + self.assertTrue(retval.Succeeded(), "break modify failed with: %s."%(retval.GetError())) + self.assertTrue(not bkpt.IsOneShot(), "We applied one-shot to the wrong breakpoint.") + + def check_option_values(self, bp_object): + self.assertEqual(bp_object.IsOneShot(), self.is_one_shot, "IsOneShot") + self.assertEqual(bp_object.GetIgnoreCount(), self.ignore_count, "IgnoreCount") + self.assertEqual(bp_object.GetCondition(), self.condition, "Condition") + self.assertEqual(bp_object.GetAutoContinue(), self.auto_continue, "AutoContinue") + self.assertEqual(bp_object.GetThreadID(), self.tid, "Thread ID") + self.assertEqual(bp_object.GetThreadIndex(), self.tidx, "Thread Index") + self.assertEqual(bp_object.GetThreadName(), self.thread_name, "Thread Name") + self.assertEqual(bp_object.GetQueueName(), self.queue_name, "Queue Name") + set_cmds = lldb.SBStringList() + bp_object.GetCommandLineCommands(set_cmds) + self.assertEqual(set_cmds.GetSize(), self.cmd_list.GetSize(), "Size of command line commands") + for idx in range(0, set_cmds.GetSize()): + self.assertEqual(self.cmd_list.GetStringAtIndex(idx), set_cmds.GetStringAtIndex(idx), "Command %d"%(idx)) + + def make_a_dummy_name(self): + "This makes a breakpoint name in the dummy target to make sure it gets copied over" + + dummy_target = self.dbg.GetDummyTarget() + self.assertTrue(dummy_target.IsValid(), "Dummy target was not valid.") + + def cleanup (): + self.dbg.GetDummyTarget().DeleteBreakpointName(self.bp_name_string) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Now find it in the dummy target, and make sure these settings took: + bp_name = lldb.SBBreakpointName(dummy_target, self.bp_name_string) + # Make sure the name is right: + self.assertTrue (bp_name.GetName() == self.bp_name_string, "Wrong bp_name: %s"%(bp_name.GetName())) + bp_name.SetOneShot(self.is_one_shot) + bp_name.SetIgnoreCount(self.ignore_count) + bp_name.SetCondition(self.condition) + bp_name.SetAutoContinue(self.auto_continue) + bp_name.SetThreadID(self.tid) + bp_name.SetThreadIndex(self.tidx) + bp_name.SetThreadName(self.thread_name) + bp_name.SetQueueName(self.queue_name) + bp_name.SetCommandLineCommands(self.cmd_list) + + # Now look it up again, and make sure it got set correctly. + bp_name = lldb.SBBreakpointName(dummy_target, self.bp_name_string) + self.assertTrue(bp_name.IsValid(), "Failed to make breakpoint name.") + self.check_option_values(bp_name) + + def do_check_configuring_names(self): + """Use Python APIs to check that configuring breakpoint names works correctly.""" + other_bp_name_string = "AnotherBreakpointName" + cl_bp_name_string = "CLBreakpointName" + + # Now find the version copied in from the dummy target, and make sure these settings took: + bp_name = lldb.SBBreakpointName(self.target, self.bp_name_string) + self.assertTrue(bp_name.IsValid(), "Failed to make breakpoint name.") + self.check_option_values(bp_name) + + # Now add this name to a breakpoint, and make sure it gets configured properly + bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) + success = bkpt.AddName(self.bp_name_string) + self.assertTrue(success, "Couldn't add this name to the breakpoint") + self.check_option_values(bkpt) + + # Now make a name from this breakpoint, and make sure the new name is properly configured: + new_name = lldb.SBBreakpointName(bkpt, other_bp_name_string) + self.assertTrue(new_name.IsValid(), "Couldn't make a valid bp_name from a breakpoint.") + self.check_option_values(bkpt) + + # Now change the name's option and make sure it gets propagated to + # the breakpoint: + new_auto_continue = not self.auto_continue + bp_name.SetAutoContinue(new_auto_continue) + self.assertEqual(bp_name.GetAutoContinue(), new_auto_continue, "Couldn't change auto-continue on the name") + self.assertEqual(bkpt.GetAutoContinue(), new_auto_continue, "Option didn't propagate to the breakpoint.") + + # Now make this same breakpoint name - but from the command line + cmd_str = "breakpoint name configure %s -o %d -i %d -c '%s' -G %d -t %d -x %d -T '%s' -q '%s' -H '%s'"%(cl_bp_name_string, + self.is_one_shot, + self.ignore_count, + self.condition, + self.auto_continue, + self.tid, + self.tidx, + self.thread_name, + self.queue_name, + self.help_string) + for cmd in self.cmd_list: + cmd_str += " -C '%s'"%(cmd) + + self.runCmd(cmd_str, check=True) + # Now look up this name again and check its options: + cl_name = lldb.SBBreakpointName(self.target, cl_bp_name_string) + self.check_option_values(cl_name) + # Also check the help string: + self.assertEqual(self.help_string, cl_name.GetHelpString(), "Help string didn't match") + # Change the name and make sure that works: + new_help = "I do something even more interesting" + cl_name.SetHelpString(new_help) + self.assertEqual(new_help, cl_name.GetHelpString(), "SetHelpString didn't") + + # We should have three names now, make sure the target can list them: + name_list = lldb.SBStringList() + self.target.GetBreakpointNames(name_list) + for name_string in [self.bp_name_string, other_bp_name_string, cl_bp_name_string]: + self.assertTrue(name_string in name_list, "Didn't find %s in names"%(name_string)) + + # Delete the name from the current target. Make sure that works and deletes the + # name from the breakpoint as well: + self.target.DeleteBreakpointName(self.bp_name_string) + name_list.Clear() + self.target.GetBreakpointNames(name_list) + self.assertTrue(self.bp_name_string not in name_list, "Didn't delete %s from a real target"%(self.bp_name_string)) + # Also make sure the name got removed from breakpoints holding it: + self.assertFalse(bkpt.MatchesName(self.bp_name_string), "Didn't remove the name from the breakpoint.") + + # Test that deleting the name we injected into the dummy target works (there's also a + # cleanup that will do this, but that won't test the result... + dummy_target = self.dbg.GetDummyTarget() + dummy_target.DeleteBreakpointName(self.bp_name_string) + name_list.Clear() + dummy_target.GetBreakpointNames(name_list) + self.assertTrue(self.bp_name_string not in name_list, "Didn't delete %s from the dummy target"%(self.bp_name_string)) + # Also make sure the name got removed from breakpoints holding it: + self.assertFalse(bkpt.MatchesName(self.bp_name_string), "Didn't remove the name from the breakpoint.") + + def check_permission_results(self, bp_name): + self.assertEqual(bp_name.GetAllowDelete(), False, "Didn't set allow delete.") + protected_bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) + protected_id = protected_bkpt.GetID() + + unprotected_bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) + unprotected_id = unprotected_bkpt.GetID() + + success = protected_bkpt.AddName(self.bp_name_string) + self.assertTrue(success, "Couldn't add this name to the breakpoint") + + self.target.DisableAllBreakpoints() + self.assertEqual(protected_bkpt.IsEnabled(), True, "Didnt' keep breakpoint from being disabled") + self.assertEqual(unprotected_bkpt.IsEnabled(), False, "Protected too many breakpoints from disabling.") + + # Try from the command line too: + unprotected_bkpt.SetEnabled(True) + result = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand("break disable", result) + self.assertTrue(result.Succeeded()) + self.assertEqual(protected_bkpt.IsEnabled(), True, "Didnt' keep breakpoint from being disabled") + self.assertEqual(unprotected_bkpt.IsEnabled(), False, "Protected too many breakpoints from disabling.") + + self.target.DeleteAllBreakpoints() + bkpt = self.target.FindBreakpointByID(protected_id) + self.assertTrue(bkpt.IsValid(), "Didn't keep the breakpoint from being deleted.") + bkpt = self.target.FindBreakpointByID(unprotected_id) + self.assertFalse(bkpt.IsValid(), "Protected too many breakpoints from deletion.") + + # Remake the unprotected breakpoint and try again from the command line: + unprotected_bkpt = self.target.BreakpointCreateByLocation(self.main_file_spec, 10) + unprotected_id = unprotected_bkpt.GetID() + + self.dbg.GetCommandInterpreter().HandleCommand("break delete -f", result) + self.assertTrue(result.Succeeded()) + bkpt = self.target.FindBreakpointByID(protected_id) + self.assertTrue(bkpt.IsValid(), "Didn't keep the breakpoint from being deleted.") + bkpt = self.target.FindBreakpointByID(unprotected_id) + self.assertFalse(bkpt.IsValid(), "Protected too many breakpoints from deletion.") + + def do_check_configuring_permissions_sb(self): + bp_name = lldb.SBBreakpointName(self.target, self.bp_name_string) + + # Make a breakpoint name with delete disallowed: + bp_name = lldb.SBBreakpointName(self.target, self.bp_name_string) + self.assertTrue(bp_name.IsValid(), "Failed to make breakpoint name for valid name.") + + bp_name.SetAllowDelete(False) + bp_name.SetAllowDisable(False) + bp_name.SetAllowList(False) + self.check_permission_results(bp_name) + + def do_check_configuring_permissions_cli(self): + # Make the name with the right options using the command line: + self.runCmd("breakpoint name configure -L 0 -D 0 -A 0 %s"%(self.bp_name_string), check=True) + # Now look up the breakpoint we made, and check that it works. + bp_name = lldb.SBBreakpointName(self.target, self.bp_name_string) + self.assertTrue(bp_name.IsValid(), "Didn't make a breakpoint name we could find.") + self.check_permission_results(bp_name) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_names/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_names/main.c new file mode 100644 index 00000000000..b1ed4465c1d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_names/main.c @@ -0,0 +1,53 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to demonstrate the capability of the lldb command +// "breakpoint modify -i <count> breakpt-id" to set the number of times a +// breakpoint is skipped before stopping. Ignore count can also be set upon +// breakpoint creation by 'breakpoint set ... -i <count>'. + +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); // a(3) -> c(3) Find the call site of c(3). + + 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) Find the call site of b(2). + printf("b(2) returns %d\n", B2); + + int A3 = a(3); // a(3) -> c(3) Find the call site of a(3). + printf("a(3) returns %d\n", A3); + + int C1 = c(5); // Find the call site of c in main. + printf ("c(5) returns %d\n", C1); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/Makefile new file mode 100644 index 00000000000..7df22699c57 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp foo.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py new file mode 100644 index 00000000000..0419b4df5dd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py @@ -0,0 +1,113 @@ +""" +Test breakpoint command for different options. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class BreakpointOptionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test(self): + """Test breakpoint command for different options.""" + self.build() + self.breakpoint_options_test() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + + def breakpoint_options_test(self): + """Test breakpoint command for different options.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint with 1 locations. + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line, + extra_options="-K 1", + num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line, + extra_options="-K 0", + num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Stopped once. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 2."]) + + # Check the list of breakpoint. + self.expect( + "breakpoint list -f", + "Breakpoint locations shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.line, + "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.line]) + + # Continue the program, there should be another stop. + self.runCmd("process continue") + + # Stopped again. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."]) + + # Continue the program, we should exit. + self.runCmd("process continue") + + # We should exit. + self.expect("process status", "Process exited successfully", + patterns=["^Process [0-9]+ exited with status = 0"]) + + def breakpoint_options_language_test(self): + """Test breakpoint command for language option.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint with 1 locations. + lldbutil.run_break_set_by_symbol( + self, + 'ns::func', + sym_exact=False, + extra_options="-L c++", + num_expected_locations=1) + + # This should create a breakpoint with 0 locations. + lldbutil.run_break_set_by_symbol( + self, + 'ns::func', + sym_exact=False, + extra_options="-L c", + num_expected_locations=0) + self.runCmd("settings set target.language c") + lldbutil.run_break_set_by_symbol( + self, 'ns::func', sym_exact=False, num_expected_locations=0) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Stopped once. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."]) + + # Continue the program, we should exit. + self.runCmd("process continue") + + # We should exit. + self.expect("process status", "Process exited successfully", + patterns=["^Process [0-9]+ exited with status = 0"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/foo.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/foo.cpp new file mode 100644 index 00000000000..e5d0e09803e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/foo.cpp @@ -0,0 +1,12 @@ + +namespace ns { + int func(void) + { + return 0; + } +} + +extern "C" int foo(void) +{ + return ns::func(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/main.cpp new file mode 100644 index 00000000000..b2e8f523c84 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/main.cpp @@ -0,0 +1,4 @@ +extern "C" int foo(void); +int main (int argc, char **argv) { // Set break point at this line. + return foo(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py new file mode 100644 index 00000000000..40a20a04b76 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/TestBreakpointSetRestart.py @@ -0,0 +1,50 @@ +""" +Test inferior restart when breakpoint is set on running target. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class BreakpointSetRestart(TestBase): + + mydir = TestBase.compute_mydir(__file__) + BREAKPOINT_TEXT = 'Set a breakpoint here' + + @skipIfNetBSD + def test_breakpoint_set_restart(self): + self.build() + + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.dbg.SetAsync(True) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + event = lldb.SBEvent() + # Wait for inferior to transition to running state + while self.dbg.GetListener().WaitForEvent(2, event): + if lldb.SBProcess.GetStateFromEvent(event) == lldb.eStateRunning: + break + + bp = target.BreakpointCreateBySourceRegex( + self.BREAKPOINT_TEXT, lldb.SBFileSpec('main.cpp')) + self.assertTrue( + bp.IsValid() and bp.GetNumLocations() == 1, + VALID_BREAKPOINT) + + while self.dbg.GetListener().WaitForEvent(2, event): + if lldb.SBProcess.GetStateFromEvent( + event) == lldb.eStateStopped and lldb.SBProcess.GetRestartedFromEvent(event): + continue + if lldb.SBProcess.GetStateFromEvent(event) == lldb.eStateRunning: + continue + self.fail( + "Setting a breakpoint generated an unexpected event: %s" % + lldb.SBDebugger.StateAsCString( + lldb.SBProcess.GetStateFromEvent(event))) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/main.cpp new file mode 100644 index 00000000000..46682ec264d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_set_restart/main.cpp @@ -0,0 +1,24 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <chrono> +#include <stdio.h> +#include <thread> + + +int main(int argc, char const *argv[]) +{ + static bool done = false; + while (!done) + { + std::this_thread::sleep_for(std::chrono::milliseconds{100}); + } + printf("Set a breakpoint here.\n"); + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/Makefile new file mode 100644 index 00000000000..7c6a18b0f24 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/Makefile @@ -0,0 +1,12 @@ +CXX_SOURCES := relative.cpp + +EXE := CompDirSymLink + +include Makefile.rules + +# Force relative filenames by copying it into the build directory. +relative.cpp: main.cpp + cp -f $< $@ + +clean:: + rm -rf relative.cpp diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py new file mode 100644 index 00000000000..0e372c73249 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py @@ -0,0 +1,78 @@ +""" +Test breakpoint command with AT_comp_dir set to symbolic link. +""" + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +_EXE_NAME = 'CompDirSymLink' # Must match Makefile +_SRC_FILE = 'relative.cpp' +_COMP_DIR_SYM_LINK_PROP = 'plugin.symbol-file.dwarf.comp-dir-symlink-paths' + + +class CompDirSymLinkTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number( + os.path.join(self.getSourceDir(), "main.cpp"), + '// Set break point at this line.') + + @skipIf(hostoslist=["windows"]) + def test_symlink_paths_set(self): + pwd_symlink = self.create_src_symlink() + self.doBuild(pwd_symlink) + self.runCmd( + "settings set %s %s" % + (_COMP_DIR_SYM_LINK_PROP, pwd_symlink)) + src_path = self.getBuildArtifact(_SRC_FILE) + lldbutil.run_break_set_by_file_and_line(self, src_path, self.line) + + @skipIf(hostoslist=no_match(["linux"])) + def test_symlink_paths_set_procselfcwd(self): + os.chdir(self.getBuildDir()) + pwd_symlink = '/proc/self/cwd' + self.doBuild(pwd_symlink) + self.runCmd( + "settings set %s %s" % + (_COMP_DIR_SYM_LINK_PROP, pwd_symlink)) + src_path = self.getBuildArtifact(_SRC_FILE) + # /proc/self/cwd points to a realpath form of current directory. + src_path = os.path.realpath(src_path) + lldbutil.run_break_set_by_file_and_line(self, src_path, self.line) + + @skipIf(hostoslist=["windows"]) + def test_symlink_paths_unset(self): + pwd_symlink = self.create_src_symlink() + self.doBuild(pwd_symlink) + self.runCmd('settings clear ' + _COMP_DIR_SYM_LINK_PROP) + src_path = self.getBuildArtifact(_SRC_FILE) + self.assertRaises( + AssertionError, + lldbutil.run_break_set_by_file_and_line, + self, + src_path, + self.line) + + def create_src_symlink(self): + pwd_symlink = self.getBuildArtifact('pwd_symlink') + if os.path.exists(pwd_symlink): + os.unlink(pwd_symlink) + os.symlink(self.getBuildDir(), pwd_symlink) + self.addTearDownHook(lambda: os.remove(pwd_symlink)) + return pwd_symlink + + def doBuild(self, pwd_symlink): + self.build(None, None, {'PWD': pwd_symlink}) + + exe = self.getBuildArtifact(_EXE_NAME) + self.runCmd('file ' + exe, CURRENT_EXECUTABLE_SET) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/main.cpp new file mode 100644 index 00000000000..13e5e3e891f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/main.cpp @@ -0,0 +1,12 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main (int argc, char const *argv[]) +{ + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/Makefile new file mode 100644 index 00000000000..2c00681fa22 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/Makefile @@ -0,0 +1,8 @@ +CXX_SOURCES := main.cpp + +ifneq (,$(findstring icc,$(CC))) + CXXFLAGS_EXTRAS := -debug inline-debug-info +endif + + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py new file mode 100644 index 00000000000..cf36f143838 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/TestConsecutiveBreakpoints.py @@ -0,0 +1,103 @@ +""" +Test that we handle breakpoints on consecutive instructions correctly. +""" + + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ConsecutiveBreakpointsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def prepare_test(self): + self.build() + + (self.target, self.process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set breakpoint here", lldb.SBFileSpec("main.cpp")) + + # Set breakpoint to the next instruction + frame = self.thread.GetFrameAtIndex(0) + + address = frame.GetPCAddress() + instructions = self.target.ReadInstructions(address, 2) + self.assertTrue(len(instructions) == 2) + self.bkpt_address = instructions[1].GetAddress() + self.breakpoint2 = self.target.BreakpointCreateByAddress( + self.bkpt_address.GetLoadAddress(self.target)) + self.assertTrue( + self.breakpoint2 and self.breakpoint2.GetNumLocations() == 1, + VALID_BREAKPOINT) + + def finish_test(self): + # Run the process until termination + self.process.Continue() + self.assertEquals(self.process.GetState(), lldb.eStateExited) + + @no_debug_info_test + def test_continue(self): + """Test that continue stops at the second breakpoint.""" + self.prepare_test() + + self.process.Continue() + self.assertEquals(self.process.GetState(), lldb.eStateStopped) + # We should be stopped at the second breakpoint + self.thread = lldbutil.get_one_thread_stopped_at_breakpoint( + self.process, self.breakpoint2) + self.assertIsNotNone( + self.thread, + "Expected one thread to be stopped at breakpoint 2") + + self.finish_test() + + @no_debug_info_test + def test_single_step(self): + """Test that single step stops at the second breakpoint.""" + self.prepare_test() + + step_over = False + self.thread.StepInstruction(step_over) + + self.assertEquals(self.process.GetState(), lldb.eStateStopped) + self.assertEquals( + self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress( + self.target), self.bkpt_address.GetLoadAddress( + self.target)) + self.thread = lldbutil.get_one_thread_stopped_at_breakpoint( + self.process, self.breakpoint2) + self.assertIsNotNone( + self.thread, + "Expected one thread to be stopped at breakpoint 2") + + self.finish_test() + + @no_debug_info_test + def test_single_step_thread_specific(self): + """Test that single step stops, even though the second breakpoint is not valid.""" + self.prepare_test() + + # Choose a thread other than the current one. A non-existing thread is + # fine. + thread_index = self.process.GetNumThreads() + 1 + self.assertFalse(self.process.GetThreadAtIndex(thread_index).IsValid()) + self.breakpoint2.SetThreadIndex(thread_index) + + step_over = False + self.thread.StepInstruction(step_over) + + self.assertEquals(self.process.GetState(), lldb.eStateStopped) + self.assertEquals( + self.thread.GetFrameAtIndex(0).GetPCAddress().GetLoadAddress( + self.target), self.bkpt_address.GetLoadAddress( + self.target)) + self.assertEquals( + self.thread.GetStopReason(), + lldb.eStopReasonPlanComplete, + "Stop reason should be 'plan complete'") + + self.finish_test() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/main.cpp new file mode 100644 index 00000000000..94d0a0415d7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoints/main.cpp @@ -0,0 +1,18 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int +main(int argc, char const *argv[]) +{ + int a = 0; + int b = 1; + a = b + 1; // Set breakpoint here + b = a + 1; + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/Makefile new file mode 100644 index 00000000000..2c00681fa22 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/Makefile @@ -0,0 +1,8 @@ +CXX_SOURCES := main.cpp + +ifneq (,$(findstring icc,$(CC))) + CXXFLAGS_EXTRAS := -debug inline-debug-info +endif + + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py new file mode 100644 index 00000000000..be21c6eea13 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py @@ -0,0 +1,112 @@ +""" +Test lldb breakpoint ids. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestCPPBreakpointLocations(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") + def test(self): + self.build() + self.breakpoint_id_tests() + + def verify_breakpoint_locations(self, target, bp_dict): + + name = bp_dict['name'] + names = bp_dict['loc_names'] + bp = target.BreakpointCreateByName(name) + self.assertEquals( + bp.GetNumLocations(), + len(names), + "Make sure we find the right number of breakpoint locations") + + bp_loc_names = list() + for bp_loc in bp: + bp_loc_names.append(bp_loc.GetAddress().GetFunction().GetName()) + + for name in names: + found = name in bp_loc_names + if not found: + print("Didn't find '%s' in: %s" % (name, bp_loc_names)) + self.assertTrue(found, "Make sure we find all required locations") + + def breakpoint_id_tests(self): + + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + bp_dicts = [ + {'name': 'func1', 'loc_names': ['a::c::func1()', 'b::c::func1()']}, + {'name': 'func2', 'loc_names': ['a::c::func2()', 'c::d::func2()']}, + {'name': 'func3', 'loc_names': ['a::c::func3()', 'b::c::func3()', 'c::d::func3()']}, + {'name': 'c::func1', 'loc_names': ['a::c::func1()', 'b::c::func1()']}, + {'name': 'c::func2', 'loc_names': ['a::c::func2()']}, + {'name': 'c::func3', 'loc_names': ['a::c::func3()', 'b::c::func3()']}, + {'name': 'a::c::func1', 'loc_names': ['a::c::func1()']}, + {'name': 'b::c::func1', 'loc_names': ['b::c::func1()']}, + {'name': 'c::d::func2', 'loc_names': ['c::d::func2()']}, + {'name': 'a::c::func1()', 'loc_names': ['a::c::func1()']}, + {'name': 'b::c::func1()', 'loc_names': ['b::c::func1()']}, + {'name': 'c::d::func2()', 'loc_names': ['c::d::func2()']}, + ] + + for bp_dict in bp_dicts: + self.verify_breakpoint_locations(target, bp_dict) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") + def test_destructors(self): + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + + # Don't skip prologue, so we can check the breakpoint address more + # easily + self.runCmd("settings set target.skip-prologue false") + try: + names = ['~c', 'c::~c', 'c::~c()'] + loc_names = {'a::c::~c()', 'b::c::~c()'} + # TODO: For windows targets we should put windows mangled names + # here + symbols = [ + '_ZN1a1cD1Ev', + '_ZN1a1cD2Ev', + '_ZN1b1cD1Ev', + '_ZN1b1cD2Ev'] + + for name in names: + bp = target.BreakpointCreateByName(name) + + bp_loc_names = {bp_loc.GetAddress().GetFunction().GetName() + for bp_loc in bp} + self.assertEquals( + bp_loc_names, + loc_names, + "Breakpoint set on the correct symbol") + + bp_addresses = {bp_loc.GetLoadAddress() for bp_loc in bp} + symbol_addresses = set() + for symbol in symbols: + sc_list = target.FindSymbols(symbol, lldb.eSymbolTypeCode) + self.assertEquals( + sc_list.GetSize(), 1, "Found symbol " + symbol) + symbol = sc_list.GetContextAtIndex(0).GetSymbol() + symbol_addresses.add( + symbol.GetStartAddress().GetLoadAddress(target)) + + self.assertEquals( + symbol_addresses, + bp_addresses, + "Breakpoint set on correct address") + finally: + self.runCmd("settings clear target.skip-prologue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/main.cpp new file mode 100644 index 00000000000..4afabcbd36e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/main.cpp @@ -0,0 +1,82 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +namespace a { + class c { + public: + c(); + ~c(); + void func1() + { + puts (__PRETTY_FUNCTION__); + } + void func2() + { + puts (__PRETTY_FUNCTION__); + } + void func3() + { + puts (__PRETTY_FUNCTION__); + } + }; + + c::c() {} + c::~c() {} +} + +namespace b { + class c { + public: + c(); + ~c(); + void func1() + { + puts (__PRETTY_FUNCTION__); + } + void func3() + { + puts (__PRETTY_FUNCTION__); + } + }; + + c::c() {} + c::~c() {} +} + +namespace c { + class d { + public: + d () {} + ~d() {} + void func2() + { + puts (__PRETTY_FUNCTION__); + } + void func3() + { + puts (__PRETTY_FUNCTION__); + } + }; +} + +int main (int argc, char const *argv[]) +{ + a::c ac; + b::c bc; + c::d cd; + ac.func1(); + ac.func2(); + ac.func3(); + bc.func1(); + bc.func3(); + cd.func2(); + cd.func3(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py new file mode 100644 index 00000000000..ba8e94eddca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py @@ -0,0 +1,86 @@ +""" +Test that you can set breakpoint and hit the C++ language exception breakpoint +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestCPPExceptionBreakpoint (TestBase): + + mydir = TestBase.compute_mydir(__file__) + my_var = 10 + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24538") + @expectedFailureNetBSD + def test_cpp_exception_breakpoint(self): + """Test setting and hitting the C++ exception breakpoint.""" + self.build() + self.do_cpp_exception_bkpt() + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24538") + @expectedFailureNetBSD + def test_dummy_target_cpp_exception_breakpoint(self): + """Test setting and hitting the C++ exception breakpoint from dummy target.""" + self.build() + self.do_dummy_target_cpp_exception_bkpt() + + def setUp(self): + TestBase.setUp(self) + self.main_source = "main.c" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + def do_cpp_exception_bkpt(self): + exe = self.getBuildArtifact("a.out") + error = lldb.SBError() + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + exception_bkpt = self.target.BreakpointCreateForException( + lldb.eLanguageTypeC_plus_plus, False, True) + self.assertTrue( + exception_bkpt.IsValid(), + "Created exception breakpoint.") + + process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, exception_bkpt) + self.assertTrue(len(thread_list) == 1, + "One thread stopped at the exception breakpoint.") + + def do_dummy_target_cpp_exception_bkpt(self): + exe = self.getBuildArtifact("a.out") + error = lldb.SBError() + + dummy_exception_bkpt = self.dbg.GetDummyTarget().BreakpointCreateForException( + lldb.eLanguageTypeC_plus_plus, False, True) + self.assertTrue( + dummy_exception_bkpt.IsValid(), + "Created exception breakpoint in dummy target.") + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + exception_bkpt = self.target.GetBreakpointAtIndex(0) + self.assertTrue( + exception_bkpt.IsValid(), + "Target primed with exception breakpoint from dummy target.") + + process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, exception_bkpt) + self.assertTrue(len(thread_list) == 1, + "One thread stopped at the exception breakpoint.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/main.cpp new file mode 100644 index 00000000000..76cb22735a7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/main.cpp @@ -0,0 +1,13 @@ +#include <exception> + +void +throws_int () +{ + throw 5; +} + +int +main () +{ + throws_int(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/TestDebugBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/TestDebugBreak.py new file mode 100644 index 00000000000..2164ddfb8f6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/TestDebugBreak.py @@ -0,0 +1,57 @@ +""" +Test embedded breakpoints, like `asm int 3;` in x86 or or `__debugbreak` on Windows. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DebugBreakTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(archs=no_match(["i386", "i686", "x86_64"])) + @no_debug_info_test + def test_asm_int_3(self): + """Test that intrinsics like `__debugbreak();` and `asm {"int3"}` are treated like breakpoints.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Run the program. + target = self.dbg.CreateTarget(exe) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # We've hit the first stop, so grab the frame. + self.assertEqual(process.GetState(), lldb.eStateStopped) + stop_reason = lldb.eStopReasonException if (lldbplatformutil.getPlatform( + ) == "windows" or lldbplatformutil.getPlatform() == "macosx") else lldb.eStopReasonSignal + thread = lldbutil.get_stopped_thread(process, stop_reason) + self.assertIsNotNone( + thread, "Unable to find thread stopped at the __debugbreak()") + frame = thread.GetFrameAtIndex(0) + + # We should be in funciton 'bar'. + self.assertTrue(frame.IsValid()) + function_name = frame.GetFunctionName() + self.assertTrue('bar' in function_name, + "Unexpected function name {}".format(function_name)) + + # We should be able to evaluate the parameter foo. + value = frame.EvaluateExpression('*foo') + self.assertEqual(value.GetValueAsSigned(), 42) + + # The counter should be 1 at the first stop and increase by 2 for each + # subsequent stop. + counter = 1 + while counter < 20: + value = frame.EvaluateExpression('count') + self.assertEqual(value.GetValueAsSigned(), counter) + counter += 2 + process.Continue() + + # The inferior should exit after the last iteration. + self.assertEqual(process.GetState(), lldb.eStateExited) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/main.c new file mode 100644 index 00000000000..5f936327e4e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/debugbreak/main.c @@ -0,0 +1,29 @@ +#ifdef _MSC_VER +#include <intrin.h> +#define BREAKPOINT_INTRINSIC() __debugbreak() +#else +#define BREAKPOINT_INTRINSIC() __asm__ __volatile__ ("int3") +#endif + +int +bar(int const *foo) +{ + int count = 0, i = 0; + for (; i < 10; ++i) + { + count += 1; + BREAKPOINT_INTRINSIC(); + count += 1; + } + return *foo; +} + +int +main(int argc, char **argv) +{ + int foo = 42; + bar(&foo); + return 0; +} + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/Makefile new file mode 100644 index 00000000000..9645fd9cc8d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/Makefile @@ -0,0 +1,7 @@ +C_SOURCES := main.c + +ifneq (,$(findstring icc,$(CC))) + CFLAGS_EXTRAS := -debug inline-debug-info +endif + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py new file mode 100644 index 00000000000..e3f293a4a55 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py @@ -0,0 +1,71 @@ +""" +Test breakpoint commands set before we have a target +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class BreakpointInDummyTarget (TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test(self): + """Test breakpoint set before we have a target. """ + self.build() + self.dummy_breakpoint_test() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.c', 'Set a breakpoint on this line.') + self.line2 = line_number('main.c', 'Set another on this line.') + + def dummy_breakpoint_test(self): + """Test breakpoint set before we have a target. """ + + # This should create a breakpoint with 3 locations. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=0) + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line2, num_expected_locations=0) + + # This is the function to remove breakpoints from the dummy target + # to get a clean slate for the next test case. + def cleanup(): + self.runCmd('breakpoint delete -D -f', check=False) + self.runCmd('breakpoint list', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # The breakpoint list should show 3 locations. + self.expect( + "breakpoint list -f", + "Breakpoint locations shown correctly", + substrs=[ + "1: file = 'main.c', line = %d, exact_match = 0, locations = 1" % + self.line, + "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % + self.line2]) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Stopped once. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."]) + + # Continue the program, there should be another stop. + self.runCmd("process continue") + + # Stopped again. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 2."]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/main.c new file mode 100644 index 00000000000..e1f03237cd1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/main.c @@ -0,0 +1,11 @@ +#include <stdio.h> + +int +main (int argc, char **argv) +{ + printf ("Set a breakpoint on this line.\n"); + + return 0; // Set another on this line. +} + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/Makefile new file mode 100644 index 00000000000..4b3098cf7da --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/Makefile @@ -0,0 +1,5 @@ +DYLIB_NAME := foo +DYLIB_CXX_SOURCES := foo.cpp +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/TestBreakpointInGlobalConstructor.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/TestBreakpointInGlobalConstructor.py new file mode 100644 index 00000000000..4439607d91c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/TestBreakpointInGlobalConstructor.py @@ -0,0 +1,46 @@ +""" +Test that we can hit breakpoints in global constructors +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestBreakpointInGlobalConstructors(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @expectedFailureNetBSD + def test(self): + self.build() + self.line_foo = line_number('foo.cpp', '// !BR_foo') + self.line_main = line_number('main.cpp', '// !BR_main') + + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + env= self.registerSharedLibrariesWithTarget(target, ["foo"]) + + bp_main = lldbutil.run_break_set_by_file_and_line( + self, 'main.cpp', self.line_main) + + bp_foo = lldbutil.run_break_set_by_file_and_line( + self, 'foo.cpp', self.line_foo, num_expected_locations=-2) + + process = target.LaunchSimple( + None, env, self.get_process_working_directory()) + + self.assertIsNotNone( + lldbutil.get_one_thread_stopped_at_breakpoint_id( + self.process(), bp_foo)) + + self.runCmd("continue") + + self.assertIsNotNone( + lldbutil.get_one_thread_stopped_at_breakpoint_id( + self.process(), bp_main)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/foo.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/foo.cpp new file mode 100644 index 00000000000..f959a295467 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/foo.cpp @@ -0,0 +1,7 @@ +#include "foo.h" + +Foo::Foo() : x(42) { + bool some_code = x == 42; // !BR_foo +} + +Foo FooObj; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/foo.h new file mode 100644 index 00000000000..3bc63fed755 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/foo.h @@ -0,0 +1,11 @@ +#ifndef FOO_H +#define FOO_H + +struct LLDB_TEST_API Foo { + Foo(); + int x; +}; + +extern LLDB_TEST_API Foo FooObj; + +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/main.cpp new file mode 100644 index 00000000000..d1c8038dfad --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/global_constructor/main.cpp @@ -0,0 +1,14 @@ +#include "foo.h" + +struct Main { + Main(); + int x; +}; + +Main::Main() : x(47) { + bool some_code = x == 47; // !BR_main +} + +Main MainObj; + +int main() { return MainObj.x + FooObj.x; } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/Makefile new file mode 100644 index 00000000000..de4ec12b13c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/Makefile @@ -0,0 +1,4 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/TestHWBreakMultiThread.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/TestHWBreakMultiThread.py new file mode 100644 index 00000000000..56112b24eb5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/TestHWBreakMultiThread.py @@ -0,0 +1,104 @@ +""" +Test hardware breakpoints for multiple threads. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +# Hardware breakpoints are supported only by platforms mentioned in oslist. +@skipUnlessPlatform(oslist=['linux']) +class HardwareBreakpointMultiThreadTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + # LLDB supports hardware breakpoints for arm and aarch64 architectures. + @skipIf(archs=no_match(['arm', 'aarch64'])) + def test_hw_break_set_delete_multi_thread(self): + self.build() + self.setTearDownCleanup() + self.break_multi_thread('delete') + + # LLDB supports hardware breakpoints for arm and aarch64 architectures. + @skipIf(archs=no_match(['arm', 'aarch64'])) + def test_hw_break_set_disable_multi_thread(self): + self.build() + self.setTearDownCleanup() + self.break_multi_thread('disable') + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.cpp' + # Find the line number to break inside main(). + self.first_stop = line_number( + self.source, 'Starting thread creation with hardware breakpoint set') + + def break_multi_thread(self, removal_type): + """Test that lldb hardware breakpoints work for multiple threads.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + + # Stop in main before creating any threads. + lldbutil.run_break_set_by_file_and_line( + self, None, self.first_stop, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # We should be stopped again due to the breakpoint. + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Now set a hardware breakpoint in thread function. + self.expect("breakpoint set -b hw_break_function --hardware", + substrs=[ + 'Breakpoint', + 'hw_break_function', + 'address = 0x']) + + # We should stop in hw_break_function function for 4 threads. + count = 0 + + while count < 2 : + + self.runCmd("process continue") + + # We should be stopped in hw_break_function + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=[ + 'stop reason = breakpoint', + 'hw_break_function']) + + # Continue the loop and test that we are stopped 4 times. + count += 1 + + if removal_type == 'delete': + self.runCmd("settings set auto-confirm true") + + # Now 'breakpoint delete' should just work fine without confirmation + # prompt from the command interpreter. + self.expect("breakpoint delete", + startstr="All breakpoints removed") + + # Restore the original setting of auto-confirm. + self.runCmd("settings clear auto-confirm") + + elif removal_type == 'disable': + self.expect("breakpoint disable", + startstr="All breakpoints disabled.") + + # Continue. Program should exit without stopping anywhere. + self.runCmd("process continue") + + # Process should have stopped and exited with status = 0 + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* exited with status = 0']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/main.cpp new file mode 100644 index 00000000000..94a12c6241d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/hardware_breakpoints/hardware_breakpoint_on_multiple_threads/main.cpp @@ -0,0 +1,50 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <chrono> +#include <cstdio> +#include <mutex> +#include <random> +#include <thread> + +#define NUM_OF_THREADS 4 + +std::mutex hw_break_mutex; + +void +hw_break_function (uint32_t thread_index) { + printf ("%s called by Thread #%u...\n", __FUNCTION__, thread_index); +} + + +void +thread_func (uint32_t thread_index) { + printf ("%s (thread index = %u) starting...\n", __FUNCTION__, thread_index); + + hw_break_mutex.lock(); + + hw_break_function(thread_index); // Call hw_break_function + + hw_break_mutex.unlock(); +} + + +int main (int argc, char const *argv[]) +{ + std::thread threads[NUM_OF_THREADS]; + + printf ("Starting thread creation with hardware breakpoint set...\n"); + + for (auto &thread : threads) + thread = std::thread{thread_func, std::distance(threads, &thread)}; + + for (auto &thread : threads) + thread.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/Makefile new file mode 100644 index 00000000000..551d02feac8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := int.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py new file mode 100644 index 00000000000..76fefda8a9f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py @@ -0,0 +1,66 @@ +""" +Test that inlined breakpoints (breakpoint set on a file/line included from +another source file) works correctly. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class InlinedBreakpointsTestCase(TestBase): + """Bug fixed: rdar://problem/8464339""" + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """Test 'b basic_types.cpp:176' does break (where int.cpp includes basic_type.cpp).""" + self.build() + self.inlined_breakpoints() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside basic_type.cpp. + self.line = line_number( + 'basic_type.cpp', + '// Set break point at this line.') + + def inlined_breakpoints(self): + """Test 'b basic_types.cpp:176' does break (where int.cpp includes basic_type.cpp).""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # With the inline-breakpoint-strategy, our file+line breakpoint should + # not resolve to a location. + self.runCmd('settings set target.inline-breakpoint-strategy headers') + + # Set a breakpoint and fail because it is in an inlined source + # implemenation file + lldbutil.run_break_set_by_file_and_line( + self, "basic_type.cpp", self.line, num_expected_locations=0) + + # Now enable breakpoints in implementation files and see the breakpoint + # set succeed + self.runCmd('settings set target.inline-breakpoint-strategy always') + # And add hooks to restore the settings during tearDown(). + self.addTearDownHook(lambda: self.runCmd( + "settings set target.inline-breakpoint-strategy always")) + + lldbutil.run_break_set_by_file_and_line( + self, + "basic_type.cpp", + self.line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + # And it should break at basic_type.cpp:176. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint', + 'basic_type.cpp:%d' % self.line]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/basic_type.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/basic_type.cpp new file mode 100644 index 00000000000..75d2c3690c8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/basic_type.cpp @@ -0,0 +1,178 @@ +// This file must have the following defined before it is included: +// T defined to the type to test (int, float, etc) +// T_CSTR a C string representation of the type T ("int", "float") +// T_VALUE_1 defined to a valid initializer value for TEST_TYPE (7 for int, 2.0 for float) +// T_VALUE_2, T_VALUE_3, T_VALUE_4 defined to a valid initializer value for TEST_TYPE that is different from TEST_VALUE_1 +// T_PRINTF_FORMAT defined if T can be printed with printf +// +// An example for integers is below +#if 0 + +#define T int +#define T_CSTR "int" +#define T_VALUE_1 11001110 +#define T_VALUE_2 22002220 +#define T_VALUE_3 33003330 +#define T_VALUE_4 44044440 +#define T_PRINTF_FORMAT "%i" + +#include "basic_type.cpp" + +#endif + +#include <cstdint> +#include <cstdio> + +class a_class +{ +public: + a_class (const T& a, const T& b) : + m_a (a), + m_b (b) + { + } + + ~a_class () + { + } + + const T& + get_a() + { + return m_a; + } + + void + set_a (const T& a) + { + m_a = a; + } + + const T& + get_b() + { + return m_b; + } + + void + set_b (const T& b) + { + m_b = b; + } + +protected: + T m_a; + T m_b; +}; + +typedef struct a_struct_tag { + T a; + T b; +} a_struct_t; + + +typedef union a_union_zero_tag { + T a; + double a_double; +} a_union_zero_t; + +typedef struct a_union_nonzero_tag { + double a_double; + a_union_zero_t u; +} a_union_nonzero_t; + + +void Puts(char const *msg) +{ + std::puts(msg); +} + +int +main (int argc, char const *argv[]) +{ + T a = T_VALUE_1; + T* a_ptr = &a; + T& a_ref = a; + T a_array_bounded[2] = { T_VALUE_1, T_VALUE_2 }; + T a_array_unbounded[] = { T_VALUE_1, T_VALUE_2 }; + + a_class a_class_instance (T_VALUE_1, T_VALUE_2); + a_class *a_class_ptr = &a_class_instance; + a_class &a_class_ref = a_class_instance; + + a_struct_t a_struct = { T_VALUE_1, T_VALUE_2 }; + a_struct_t *a_struct_ptr = &a_struct; + a_struct_t &a_struct_ref = a_struct; + + // Create a union with type T at offset zero + a_union_zero_t a_union_zero; + a_union_zero.a = T_VALUE_1; + a_union_zero_t *a_union_zero_ptr = &a_union_zero; + a_union_zero_t &a_union_zero_ref = a_union_zero; + + // Create a union with type T at a non-zero offset + a_union_nonzero_t a_union_nonzero; + a_union_nonzero.u.a = T_VALUE_1; + a_union_nonzero_t *a_union_nonzero_ptr = &a_union_nonzero; + a_union_nonzero_t &a_union_nonzero_ref = a_union_nonzero; + + a_struct_t a_struct_array_bounded[2] = {{ T_VALUE_1, T_VALUE_2 }, { T_VALUE_3, T_VALUE_4 }}; + a_struct_t a_struct_array_unbounded[] = {{ T_VALUE_1, T_VALUE_2 }, { T_VALUE_3, T_VALUE_4 }}; + a_union_zero_t a_union_zero_array_bounded[2]; + a_union_zero_array_bounded[0].a = T_VALUE_1; + a_union_zero_array_bounded[1].a = T_VALUE_2; + a_union_zero_t a_union_zero_array_unbounded[] = {{ T_VALUE_1 }, { T_VALUE_2 }}; + +#ifdef T_PRINTF_FORMAT + std::printf ("%s: a = '" T_PRINTF_FORMAT "'\n", T_CSTR, a); + std::printf ("%s*: %p => *a_ptr = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_ptr, *a_ptr); + std::printf ("%s&: @%p => a_ref = '" T_PRINTF_FORMAT "'\n", T_CSTR, &a_ref, a_ref); + + std::printf ("%s[2]: a_array_bounded[0] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_bounded[0]); + std::printf ("%s[2]: a_array_bounded[1] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_bounded[1]); + + std::printf ("%s[]: a_array_unbounded[0] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_unbounded[0]); + std::printf ("%s[]: a_array_unbounded[1] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_unbounded[1]); + + std::printf ("(a_class) a_class_instance.m_a = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_a()); + std::printf ("(a_class) a_class_instance.m_b = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_b()); + std::printf ("(a_class*) a_class_ptr = %p, a_class_ptr->m_a = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_a()); + std::printf ("(a_class*) a_class_ptr = %p, a_class_ptr->m_b = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_b()); + std::printf ("(a_class&) a_class_ref = %p, a_class_ref.m_a = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_a()); + std::printf ("(a_class&) a_class_ref = %p, a_class_ref.m_b = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_b()); + + std::printf ("(a_struct_t) a_struct.a = '" T_PRINTF_FORMAT "'\n", a_struct.a); + std::printf ("(a_struct_t) a_struct.b = '" T_PRINTF_FORMAT "'\n", a_struct.b); + std::printf ("(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->a = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->a); + std::printf ("(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->b = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->b); + std::printf ("(a_struct_t&) a_struct_ref = %p, a_struct_ref.a = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.a); + std::printf ("(a_struct_t&) a_struct_ref = %p, a_struct_ref.b = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.b); + + std::printf ("(a_union_zero_t) a_union_zero.a = '" T_PRINTF_FORMAT "'\n", a_union_zero.a); + std::printf ("(a_union_zero_t*) a_union_zero_ptr = %p, a_union_zero_ptr->a = '" T_PRINTF_FORMAT "'\n", a_union_zero_ptr, a_union_zero_ptr->a); + std::printf ("(a_union_zero_t&) a_union_zero_ref = %p, a_union_zero_ref.a = '" T_PRINTF_FORMAT "'\n", &a_union_zero_ref, a_union_zero_ref.a); + + std::printf ("(a_union_nonzero_t) a_union_nonzero.u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero.u.a); + std::printf ("(a_union_nonzero_t*) a_union_nonzero_ptr = %p, a_union_nonzero_ptr->u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero_ptr, a_union_nonzero_ptr->u.a); + std::printf ("(a_union_nonzero_t&) a_union_nonzero_ref = %p, a_union_nonzero_ref.u.a = '" T_PRINTF_FORMAT "'\n", &a_union_nonzero_ref, a_union_nonzero_ref.u.a); + + std::printf ("(a_struct_t[2]) a_struct_array_bounded[0].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[0].a); + std::printf ("(a_struct_t[2]) a_struct_array_bounded[0].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[0].b); + std::printf ("(a_struct_t[2]) a_struct_array_bounded[1].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[1].a); + std::printf ("(a_struct_t[2]) a_struct_array_bounded[1].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[1].b); + + std::printf ("(a_struct_t[]) a_struct_array_unbounded[0].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[0].a); + std::printf ("(a_struct_t[]) a_struct_array_unbounded[0].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[0].b); + std::printf ("(a_struct_t[]) a_struct_array_unbounded[1].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[1].a); + std::printf ("(a_struct_t[]) a_struct_array_unbounded[1].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[1].b); + + std::printf ("(a_union_zero_t[2]) a_union_zero_array_bounded[0].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_bounded[0].a); + std::printf ("(a_union_zero_t[2]) a_union_zero_array_bounded[1].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_bounded[1].a); + + std::printf ("(a_union_zero_t[]) a_union_zero_array_unbounded[0].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_unbounded[0].a); + std::printf ("(a_union_zero_t[]) a_union_zero_array_unbounded[1].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_unbounded[1].a); + +#endif + Puts("About to exit, break here to check values..."); // Set break point at this line. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/int.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/int.cpp new file mode 100644 index 00000000000..922398b1c6e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/int.cpp @@ -0,0 +1,9 @@ +#define T int +#define T_CSTR "int" +#define T_VALUE_1 11001110 +#define T_VALUE_2 22002220 +#define T_VALUE_3 33003330 +#define T_VALUE_4 44004440 +#define T_PRINTF_FORMAT "%i" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/Makefile new file mode 100644 index 00000000000..4b3098cf7da --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/Makefile @@ -0,0 +1,5 @@ +DYLIB_NAME := foo +DYLIB_CXX_SOURCES := foo.cpp +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/TestMoveNearest.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/TestMoveNearest.py new file mode 100644 index 00000000000..b8281e9c85b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/TestMoveNearest.py @@ -0,0 +1,69 @@ +from __future__ import print_function + + +import unittest2 +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class TestMoveNearest(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line1 = line_number('foo.h', '// !BR1') + self.line2 = line_number('foo.h', '// !BR2') + self.line_between = line_number('main.cpp', "// BR_Between") + print("BR_Between found at", self.line_between) + self.line_main = line_number('main.cpp', '// !BR_main') + + def test(self): + """Test target.move-to-nearest logic""" + + self.build() + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + lldbutil.run_break_set_by_symbol(self, 'main', sym_exact=True) + environment = self.registerSharedLibrariesWithTarget(target, ["foo"]) + process = target.LaunchSimple(None, environment, self.get_process_working_directory()) + self.assertEquals(process.GetState(), lldb.eStateStopped) + + # Regardless of the -m value the breakpoint should have exactly one + # location on the foo functions + self.runCmd("settings set target.move-to-nearest-code true") + lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line1, + loc_exact=True, extra_options="-m 1") + lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line2, + loc_exact=True, extra_options="-m 1") + + self.runCmd("settings set target.move-to-nearest-code false") + lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line1, + loc_exact=True, extra_options="-m 0") + lldbutil.run_break_set_by_file_and_line(self, 'foo.h', self.line2, + loc_exact=True, extra_options="-m 0") + + + # Make sure we set a breakpoint in main with -m 1 for various lines in + # the function declaration + # "int" + lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', + self.line_main-1, extra_options="-m 1") + # "main()" + lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', + self.line_main, extra_options="-m 1") + # "{" + lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', + self.line_main+1, extra_options="-m 1") + # "return .." + lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', + self.line_main+2, extra_options="-m 1") + + # Make sure we don't put move the breakpoint if it is set between two functions: + lldbutil.run_break_set_by_file_and_line(self, 'main.cpp', + self.line_between, extra_options="-m 1", num_expected_locations=0) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/foo.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/foo.cpp new file mode 100644 index 00000000000..8dad0a23f36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/foo.cpp @@ -0,0 +1,3 @@ +#include "foo.h" + +int call_foo1() { return foo1(); } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/foo.h new file mode 100644 index 00000000000..9f0e56dd22e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/foo.h @@ -0,0 +1,5 @@ +inline int foo1() { return 1; } // !BR1 + +inline int foo2() { return 2; } // !BR2 + +LLDB_TEST_API extern int call_foo1(); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/main.cpp new file mode 100644 index 00000000000..76a22a5420f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/move_nearest/main.cpp @@ -0,0 +1,9 @@ +#include "foo.h" + +int call_foo2() { return foo2(); } +// BR_Between +int +main() // !BR_main +{ + return call_foo1() + call_foo2(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/Makefile new file mode 100644 index 00000000000..37dd8f40a9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py new file mode 100644 index 00000000000..2091987fd2f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py @@ -0,0 +1,129 @@ +""" +Test that objective-c constant strings are generated correctly by the expression +parser. +""" + + + +import shutil +import subprocess +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class TestObjCBreakpoints(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_break(self): + """Test setting Objective-C specific breakpoints (DWARF in .o files).""" + self.build() + self.setTearDownCleanup() + self.check_objc_breakpoints(False) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.main_source = "main.m" + self.line = line_number(self.main_source, '// Set breakpoint here') + + def check_category_breakpoints(self): + name_bp = self.target.BreakpointCreateByName("myCategoryFunction") + selector_bp = self.target.BreakpointCreateByName( + "myCategoryFunction", + lldb.eFunctionNameTypeSelector, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + name_bp.GetNumLocations() == selector_bp.GetNumLocations(), + 'Make sure setting a breakpoint by name "myCategoryFunction" sets a breakpoint even though it is in a category') + for bp_loc in selector_bp: + function_name = bp_loc.GetAddress().GetSymbol().GetName() + self.assertTrue( + " myCategoryFunction]" in function_name, + 'Make sure all function names have " myCategoryFunction]" in their names') + + category_bp = self.target.BreakpointCreateByName( + "-[MyClass(MyCategory) myCategoryFunction]") + stripped_bp = self.target.BreakpointCreateByName( + "-[MyClass myCategoryFunction]") + stripped2_bp = self.target.BreakpointCreateByName( + "[MyClass myCategoryFunction]") + self.assertTrue( + category_bp.GetNumLocations() == 1, + "Make sure we can set a breakpoint using a full objective C function name with the category included (-[MyClass(MyCategory) myCategoryFunction])") + self.assertTrue( + stripped_bp.GetNumLocations() == 1, + "Make sure we can set a breakpoint using a full objective C function name without the category included (-[MyClass myCategoryFunction])") + self.assertTrue( + stripped2_bp.GetNumLocations() == 1, + "Make sure we can set a breakpoint using a full objective C function name without the category included ([MyClass myCategoryFunction])") + + def check_objc_breakpoints(self, have_dsym): + """Test constant string generation amd comparison by the expression parser.""" + + # Set debugger into synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + #---------------------------------------------------------------------- + # Set breakpoints on all selectors whose name is "count". This should + # catch breakpoints that are both C functions _and_ anything whose + # selector is "count" because just looking at "count" we can't tell + # definitively if the name is a selector or a C function + #---------------------------------------------------------------------- + name_bp = self.target.BreakpointCreateByName("count") + selector_bp = self.target.BreakpointCreateByName( + "count", + lldb.eFunctionNameTypeSelector, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + name_bp.GetNumLocations() >= selector_bp.GetNumLocations(), + 'Make sure we get at least the same amount of breakpoints if not more when setting by name "count"') + self.assertTrue( + selector_bp.GetNumLocations() > 50, + 'Make sure we find a lot of "count" selectors') # There are 93 on the latest MacOSX + for bp_loc in selector_bp: + function_name = bp_loc.GetAddress().GetSymbol().GetName() + self.assertTrue( + " count]" in function_name, + 'Make sure all function names have " count]" in their names') + + #---------------------------------------------------------------------- + # Set breakpoints on all selectors whose name is "isEqual:". This should + # catch breakpoints that are only ObjC selectors because no C function + # can end with a : + #---------------------------------------------------------------------- + name_bp = self.target.BreakpointCreateByName("isEqual:") + selector_bp = self.target.BreakpointCreateByName( + "isEqual:", + lldb.eFunctionNameTypeSelector, + lldb.SBFileSpecList(), + lldb.SBFileSpecList()) + self.assertTrue( + name_bp.GetNumLocations() == selector_bp.GetNumLocations(), + 'Make sure setting a breakpoint by name "isEqual:" only sets selector breakpoints') + for bp_loc in selector_bp: + function_name = bp_loc.GetAddress().GetSymbol().GetName() + self.assertTrue( + " isEqual:]" in function_name, + 'Make sure all function names have " isEqual:]" in their names') + + self.check_category_breakpoints() + + if have_dsym: + shutil.rmtree(exe + ".dSYM") + self.assertTrue(subprocess.call( + ['/usr/bin/strip', '-Sx', exe]) == 0, 'stripping dylib succeeded') + + # Check breakpoints again, this time using the symbol table only + self.check_category_breakpoints() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/main.m new file mode 100644 index 00000000000..53567491219 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/main.m @@ -0,0 +1,98 @@ +#import <Foundation/Foundation.h> +#include <unistd.h> + +@interface MyClass : NSObject +@end + +@implementation MyClass : NSObject +@end + +@implementation MyClass (MyCategory) + + +- (void) myCategoryFunction { + NSLog (@"myCategoryFunction"); +} + +@end + + + +int +Test_Selector () +{ + SEL sel = @selector(length); + printf("sel = %p\n", sel); + // Expressions to test here for selector: + // expression (char *)sel_getName(sel) + // The expression above should return "sel" as it should be just + // a uniqued C string pointer. We were seeing the result pointer being + // truncated with recent LLDBs. + return 0; // Break here for selector: tests +} + +int +Test_NSString (const char *program) +{ + NSString *str = [NSString stringWithFormat:@"Hello from '%s'", program]; + NSLog(@"NSString instance: %@", str); + printf("str = '%s'\n", [str cStringUsingEncoding: [NSString defaultCStringEncoding]]); + printf("[str length] = %zu\n", (size_t)[str length]); + printf("[str description] = %s\n", [[str description] UTF8String]); + id str_id = str; + // Expressions to test here for NSString: + // expression (char *)sel_getName(sel) + // expression [str length] + // expression [str_id length] + // expression [str description] + // expression [str_id description] + // expression str.length + // expression str.description + // expression str = @"new" + // expression str = [NSString stringWithFormat: @"%cew", 'N'] + return 0; // Break here for NSString tests +} + +NSString *my_global_str = NULL; + +int +Test_NSArray () +{ + NSMutableArray *nil_mutable_array = nil; + NSArray *array1 = [NSArray arrayWithObjects: @"array1 object1", @"array1 object2", @"array1 object3", nil]; + NSArray *array2 = [NSArray arrayWithObjects: array1, @"array2 object2", @"array2 object3", nil]; + // Expressions to test here for NSArray: + // expression [nil_mutable_array count] + // expression [array1 count] + // expression array1.count + // expression [array2 count] + // expression array2.count + id obj; + // After each object at index call, use expression and validate object + obj = [array1 objectAtIndex: 0]; // Break here for NSArray tests + obj = [array1 objectAtIndex: 1]; + obj = [array1 objectAtIndex: 2]; + + obj = [array2 objectAtIndex: 0]; + obj = [array2 objectAtIndex: 1]; + obj = [array2 objectAtIndex: 2]; + NSUInteger count = [nil_mutable_array count]; + return 0; +} + + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + Test_Selector(); // Set breakpoint here + Test_NSArray (); + Test_NSString (argv[0]); + MyClass *my_class = [[MyClass alloc] init]; + [my_class myCategoryFunction]; + printf("sizeof(id) = %zu\n", sizeof(id)); + printf("sizeof(Class) = %zu\n", sizeof(Class)); + printf("sizeof(SEL) = %zu\n", sizeof(SEL)); + + [pool release]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/require_hw_breakpoints/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/require_hw_breakpoints/Makefile new file mode 100644 index 00000000000..9645fd9cc8d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/require_hw_breakpoints/Makefile @@ -0,0 +1,7 @@ +C_SOURCES := main.c + +ifneq (,$(findstring icc,$(CC))) + CFLAGS_EXTRAS := -debug inline-debug-info +endif + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/require_hw_breakpoints/TestRequireHWBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/require_hw_breakpoints/TestRequireHWBreakpoints.py new file mode 100644 index 00000000000..0bf82c4a310 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/require_hw_breakpoints/TestRequireHWBreakpoints.py @@ -0,0 +1,110 @@ +""" +Test require hardware breakpoints. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointLocationsTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + def test_breakpoint(self): + """Test regular breakpoints when hardware breakpoints are required.""" + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + + self.runCmd("settings set target.require-hardware-breakpoint true") + + breakpoint = target.BreakpointCreateByLocation("main.c", 1) + self.assertTrue(breakpoint.IsHardware()) + + @skipIfWindows + @expectedFailureAll(archs="aarch64", oslist="linux", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=44055") + def test_step_range(self): + """Test stepping when hardware breakpoints are required.""" + self.build() + + _, _, thread, _ = lldbutil.run_to_line_breakpoint( + self, lldb.SBFileSpec("main.c"), 1) + + self.runCmd("settings set target.require-hardware-breakpoint true") + + # Ensure we fail in the interpreter. + self.expect("thread step-in") + self.expect("thread step-in", error=True) + + # Ensure we fail when stepping through the API. + error = lldb.SBError() + thread.StepInto('', 4, error) + self.assertTrue(error.Fail()) + self.assertTrue("Could not create hardware breakpoint for thread plan" + in error.GetCString()) + + @skipIfWindows + @expectedFailureAll(archs="aarch64", oslist="linux", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=44055") + def test_step_out(self): + """Test stepping out when hardware breakpoints are required.""" + self.build() + + _, _, thread, _ = lldbutil.run_to_line_breakpoint( + self, lldb.SBFileSpec("main.c"), 1) + + self.runCmd("settings set target.require-hardware-breakpoint true") + + # Ensure this fails in the command interpreter. + self.expect("thread step-out", error=True) + + # Ensure we fail when stepping through the API. + error = lldb.SBError() + thread.StepOut(error) + self.assertTrue(error.Fail()) + self.assertTrue("Could not create hardware breakpoint for thread plan" + in error.GetCString()) + + @skipIfWindows + @expectedFailureAll(archs="aarch64", oslist="linux", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=44055") + def test_step_over(self): + """Test stepping over when hardware breakpoints are required.""" + self.build() + + _, _, thread, _ = lldbutil.run_to_line_breakpoint( + self, lldb.SBFileSpec("main.c"), 7) + + self.runCmd("settings set target.require-hardware-breakpoint true") + + # Step over doesn't fail immediately but fails later on. + self.expect( + "thread step-over", + error=True, + substrs=[ + 'error: Could not create hardware breakpoint for thread plan.' + ]) + + @skipIfWindows + @expectedFailureAll(archs="aarch64", oslist="linux", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=44055") + def test_step_until(self): + """Test stepping until when hardware breakpoints are required.""" + self.build() + + _, _, thread, _ = lldbutil.run_to_line_breakpoint( + self, lldb.SBFileSpec("main.c"), 7) + + self.runCmd("settings set target.require-hardware-breakpoint true") + + self.expect("thread until 5", error=True) + + # Ensure we fail when stepping through the API. + error = thread.StepOverUntil(lldb.SBFrame(), lldb.SBFileSpec(), 5) + self.assertTrue(error.Fail()) + self.assertTrue("Could not create hardware breakpoint for thread plan" + in error.GetCString()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/require_hw_breakpoints/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/require_hw_breakpoints/main.c new file mode 100644 index 00000000000..7d49a57d4c7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/require_hw_breakpoints/main.c @@ -0,0 +1,9 @@ +int break_on_me() { + int i = 10; + i++; + return i; +} + +int main() { + return break_on_me(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/Makefile new file mode 100644 index 00000000000..695335e068c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/TestScriptedResolver.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/TestScriptedResolver.py new file mode 100644 index 00000000000..895f4fa1e37 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/TestScriptedResolver.py @@ -0,0 +1,224 @@ +""" +Test setting breakpoints using a scripted resolver +""" + +import os +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class TestScriptedResolver(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528") + def test_scripted_resolver(self): + """Use a scripted resolver to set a by symbol name breakpoint""" + self.build() + self.do_test() + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528") + def test_search_depths(self): + """ Make sure we are called at the right depths depending on what we return + from __get_depth__""" + self.build() + self.do_test_depths() + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528") + def test_command_line(self): + """ Test setting a resolver breakpoint from the command line """ + self.build() + self.do_test_cli() + + def test_bad_command_lines(self): + """Make sure we get appropriate errors when we give invalid key/value + options""" + self.build() + self.do_test_bad_options() + + def make_target_and_import(self): + target = lldbutil.run_to_breakpoint_make_target(self) + interp = self.dbg.GetCommandInterpreter() + error = lldb.SBError() + + script_name = os.path.join(self.getSourceDir(), "resolver.py") + source_name = os.path.join(self.getSourceDir(), "main.c") + + command = "command script import " + script_name + result = lldb.SBCommandReturnObject() + interp.HandleCommand(command, result) + self.assertTrue(result.Succeeded(), "com scr imp failed: %s"%(result.GetError())) + return target + + def make_extra_args(self): + json_string = '{"symbol":"break_on_me", "test1": "value1"}' + json_stream = lldb.SBStream() + json_stream.Print(json_string) + extra_args = lldb.SBStructuredData() + error = extra_args.SetFromJSON(json_stream) + self.assertTrue(error.Success(), "Error making SBStructuredData: %s"%(error.GetCString())) + return extra_args + + def do_test(self): + """This reads in a python file and sets a breakpoint using it.""" + + target = self.make_target_and_import() + extra_args = self.make_extra_args() + + file_list = lldb.SBFileSpecList() + module_list = lldb.SBFileSpecList() + + # Make breakpoints with this resolver using different filters, first ones that will take: + right = [] + # one with no file or module spec - this one should fire: + right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + + # one with the right source file and no module - should also fire: + file_list.Append(lldb.SBFileSpec("main.c")) + right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + # Make sure the help text shows up in the "break list" output: + self.expect("break list", substrs=["I am a python breakpoint resolver"], msg="Help is listed in break list") + + # one with the right source file and right module - should also fire: + module_list.Append(lldb.SBFileSpec("a.out")) + right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + + # And one with no source file but the right module: + file_list.Clear() + right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + + # Make sure these all got locations: + for i in range (0, len(right)): + self.assertTrue(right[i].GetNumLocations() >= 1, "Breakpoint %d has no locations."%(i)) + + # Now some ones that won't take: + + module_list.Clear() + file_list.Clear() + wrong = [] + + # one with the wrong module - should not fire: + module_list.Append(lldb.SBFileSpec("noSuchModule")) + wrong.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + + # one with the wrong file - also should not fire: + file_list.Clear() + module_list.Clear() + file_list.Append(lldb.SBFileSpec("noFileOfThisName.xxx")) + wrong.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)) + + # Now make sure the CU level iteration obeys the file filters: + file_list.Clear() + module_list.Clear() + file_list.Append(lldb.SBFileSpec("no_such_file.xxx")) + wrong.append(target.BreakpointCreateFromScript("resolver.ResolverCUDepth", extra_args, module_list, file_list)) + + # And the Module filters: + file_list.Clear() + module_list.Clear() + module_list.Append(lldb.SBFileSpec("NoSuchModule.dylib")) + wrong.append(target.BreakpointCreateFromScript("resolver.ResolverCUDepth", extra_args, module_list, file_list)) + + # Now make sure the Function level iteration obeys the file filters: + file_list.Clear() + module_list.Clear() + file_list.Append(lldb.SBFileSpec("no_such_file.xxx")) + wrong.append(target.BreakpointCreateFromScript("resolver.ResolverFuncDepth", extra_args, module_list, file_list)) + + # And the Module filters: + file_list.Clear() + module_list.Clear() + module_list.Append(lldb.SBFileSpec("NoSuchModule.dylib")) + wrong.append(target.BreakpointCreateFromScript("resolver.ResolverFuncDepth", extra_args, module_list, file_list)) + + # Make sure these didn't get locations: + for i in range(0, len(wrong)): + self.assertEqual(wrong[i].GetNumLocations(), 0, "Breakpoint %d has locations."%(i)) + + # Now run to main and ensure we hit the breakpoints we should have: + + lldbutil.run_to_breakpoint_do_run(self, target, right[0]) + + # Test the hit counts: + for i in range(0, len(right)): + self.assertEqual(right[i].GetHitCount(), 1, "Breakpoint %d has the wrong hit count"%(i)) + + for i in range(0, len(wrong)): + self.assertEqual(wrong[i].GetHitCount(), 0, "Breakpoint %d has the wrong hit count"%(i)) + + def do_test_depths(self): + """This test uses a class variable in resolver.Resolver which gets set to 1 if we saw + compile unit and 2 if we only saw modules. If the search depth is module, you get passed just + the modules with no comp_unit. If the depth is comp_unit you get comp_units. So we can use + this to test that our callback gets called at the right depth.""" + + target = self.make_target_and_import() + extra_args = self.make_extra_args() + + file_list = lldb.SBFileSpecList() + module_list = lldb.SBFileSpecList() + module_list.Append(lldb.SBFileSpec("a.out")) + + # Make a breakpoint that has no __get_depth__, check that that is converted to eSearchDepthModule: + bkpt = target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list) + self.assertTrue(bkpt.GetNumLocations() > 0, "Resolver got no locations.") + self.expect("script print(resolver.Resolver.got_files)", substrs=["2"], msg="Was only passed modules") + + # Make a breakpoint that asks for modules, check that we didn't get any files: + bkpt = target.BreakpointCreateFromScript("resolver.ResolverModuleDepth", extra_args, module_list, file_list) + self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverModuleDepth got no locations.") + self.expect("script print(resolver.Resolver.got_files)", substrs=["2"], msg="Was only passed modules") + + # Make a breakpoint that asks for compile units, check that we didn't get any files: + bkpt = target.BreakpointCreateFromScript("resolver.ResolverCUDepth", extra_args, module_list, file_list) + self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverCUDepth got no locations.") + self.expect("script print(resolver.Resolver.got_files)", substrs=["1"], msg="Was passed compile units") + + # Make a breakpoint that returns a bad value - we should convert that to "modules" so check that: + bkpt = target.BreakpointCreateFromScript("resolver.ResolverBadDepth", extra_args, module_list, file_list) + self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverBadDepth got no locations.") + self.expect("script print(resolver.Resolver.got_files)", substrs=["2"], msg="Was only passed modules") + + # Make a breakpoint that searches at function depth: + bkpt = target.BreakpointCreateFromScript("resolver.ResolverFuncDepth", extra_args, module_list, file_list) + self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverFuncDepth got no locations.") + self.expect("script print(resolver.Resolver.got_files)", substrs=["3"], msg="Was only passed modules") + self.expect("script print(resolver.Resolver.func_list)", substrs=["break_on_me", "main", "test_func"], msg="Saw all the functions") + + def do_test_cli(self): + target = self.make_target_and_import() + + lldbutil.run_break_set_by_script(self, "resolver.Resolver", extra_options="-k symbol -v break_on_me") + + # Make sure setting a resolver breakpoint doesn't pollute further breakpoint setting + # by checking the description of a regular file & line breakpoint to make sure it + # doesn't mention the Python Resolver function: + bkpt_no = lldbutil.run_break_set_by_file_and_line(self, "main.c", 12) + bkpt = target.FindBreakpointByID(bkpt_no) + strm = lldb.SBStream() + bkpt.GetDescription(strm, False) + used_resolver = "I am a python breakpoint resolver" in strm.GetData() + self.assertFalse(used_resolver, "Found the resolver description in the file & line breakpoint description.") + + # Also make sure the breakpoint was where we expected: + bp_loc = bkpt.GetLocationAtIndex(0) + bp_sc = bp_loc.GetAddress().GetSymbolContext(lldb.eSymbolContextEverything) + bp_se = bp_sc.GetLineEntry() + self.assertEqual(bp_se.GetLine(), 12, "Got the right line number") + self.assertEqual(bp_se.GetFileSpec().GetFilename(), "main.c", "Got the right filename") + + def do_test_bad_options(self): + target = self.make_target_and_import() + + self.expect("break set -P resolver.Resolver -k a_key", error = True, msg="Missing value at end", + substrs=['Key: "a_key" missing value']) + self.expect("break set -P resolver.Resolver -v a_value", error = True, msg="Missing key at end", + substrs=['Value: "a_value" missing matching key']) + self.expect("break set -P resolver.Resolver -v a_value -k a_key -v another_value", error = True, msg="Missing key among args", + substrs=['Value: "a_value" missing matching key']) + self.expect("break set -P resolver.Resolver -k a_key -k a_key -v another_value", error = True, msg="Missing value among args", + substrs=['Key: "a_key" missing value']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/main.c new file mode 100644 index 00000000000..b91ccfc1b43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/main.c @@ -0,0 +1,21 @@ +#include <stdio.h> + +int +test_func() +{ + return printf("I am a test function."); +} + +void +break_on_me() +{ + printf("I was called.\n"); +} + +int +main() +{ + break_on_me(); + test_func(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/resolver.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/resolver.py new file mode 100644 index 00000000000..f3af7c09f97 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/scripted_bkpt/resolver.py @@ -0,0 +1,57 @@ +import lldb + +class Resolver: + got_files = 0 + func_list = [] + + def __init__(self, bkpt, extra_args, dict): + self.bkpt = bkpt + self.extra_args = extra_args + + Resolver.func_list = [] + Resolver.got_files = 0 + + def __callback__(self, sym_ctx): + sym_name = "not_a_real_function_name" + sym_item = self.extra_args.GetValueForKey("symbol") + if sym_item.IsValid(): + sym_name = sym_item.GetStringValue(1000) + else: + print("Didn't have a value for key 'symbol'") + + if sym_ctx.compile_unit.IsValid(): + Resolver.got_files = 1 + else: + Resolver.got_files = 2 + + if sym_ctx.function.IsValid(): + Resolver.got_files = 3 + func_name = sym_ctx.function.GetName() + Resolver.func_list.append(func_name) + if sym_name == func_name: + self.bkpt.AddLocation(sym_ctx.function.GetStartAddress()) + return + + if sym_ctx.module.IsValid(): + sym = sym_ctx.module.FindSymbol(sym_name, lldb.eSymbolTypeCode) + if sym.IsValid(): + self.bkpt.AddLocation(sym.GetStartAddress()) + + def get_short_help(self): + return "I am a python breakpoint resolver" + +class ResolverModuleDepth(Resolver): + def __get_depth__ (self): + return lldb.eSearchDepthModule + +class ResolverCUDepth(Resolver): + def __get_depth__ (self): + return lldb.eSearchDepthCompUnit + +class ResolverFuncDepth(Resolver): + def __get_depth__ (self): + return lldb.eSearchDepthFunction + +class ResolverBadDepth(Resolver): + def __get_depth__ (self): + return lldb.kLastSearchDepthKind + 1 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/TestBreakpointSerialization.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/TestBreakpointSerialization.py new file mode 100644 index 00000000000..4c6f32b0896 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/TestBreakpointSerialization.py @@ -0,0 +1,375 @@ +""" +Test breakpoint serialization. +""" + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointSerialization(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + def test_resolvers(self): + """Use Python APIs to test that we serialize resolvers.""" + self.build() + self.setup_targets_and_cleanup() + self.do_check_resolvers() + + def test_filters(self): + """Use Python APIs to test that we serialize search filters correctly.""" + self.build() + self.setup_targets_and_cleanup() + self.do_check_filters() + + def test_options(self): + """Use Python APIs to test that we serialize breakpoint options correctly.""" + self.build() + self.setup_targets_and_cleanup() + self.do_check_options() + + def test_appending(self): + """Use Python APIs to test that we serialize breakpoint options correctly.""" + self.build() + self.setup_targets_and_cleanup() + self.do_check_appending() + + def test_name_filters(self): + """Use python APIs to test that reading in by name works correctly.""" + self.build() + self.setup_targets_and_cleanup() + self.do_check_names() + + def test_scripted_extra_args(self): + self.build() + self.setup_targets_and_cleanup() + self.do_check_extra_args() + + def setup_targets_and_cleanup(self): + def cleanup (): + self.RemoveTempFile(self.bkpts_file_path) + + if self.orig_target.IsValid(): + self.dbg.DeleteTarget(self.orig_target) + self.dbg.DeleteTarget(self.copy_target) + + self.addTearDownHook(cleanup) + self.RemoveTempFile(self.bkpts_file_path) + + exe = self.getBuildArtifact("a.out") + + # Create the targets we are making breakpoints in and copying them to: + self.orig_target = self.dbg.CreateTarget(exe) + self.assertTrue(self.orig_target, VALID_TARGET) + + self.copy_target = self.dbg.CreateTarget(exe) + self.assertTrue(self.copy_target, VALID_TARGET) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.bkpts_file_path = self.getBuildArtifact("breakpoints.json") + self.bkpts_file_spec = lldb.SBFileSpec(self.bkpts_file_path) + + def check_equivalence(self, source_bps, do_write = True): + + error = lldb.SBError() + + if (do_write): + error = self.orig_target.BreakpointsWriteToFile(self.bkpts_file_spec, source_bps) + self.assertTrue(error.Success(), "Failed writing breakpoints to file: %s."%(error.GetCString())) + + copy_bps = lldb.SBBreakpointList(self.copy_target) + error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, copy_bps) + self.assertTrue(error.Success(), "Failed reading breakpoints from file: %s"%(error.GetCString())) + + num_source_bps = source_bps.GetSize() + num_copy_bps = copy_bps.GetSize() + self.assertTrue(num_source_bps == num_copy_bps, "Didn't get same number of input and output breakpoints - orig: %d copy: %d"%(num_source_bps, num_copy_bps)) + + for i in range(0, num_source_bps): + source_bp = source_bps.GetBreakpointAtIndex(i) + source_desc = lldb.SBStream() + source_bp.GetDescription(source_desc, False) + source_text = source_desc.GetData() + + # I am assuming here that the breakpoints will get written out in breakpoint ID order, and + # read back in ditto. That is true right now, and I can't see any reason to do it differently + # but if we do we can go to writing the breakpoints one by one, or sniffing the descriptions to + # see which one is which. + copy_id = source_bp.GetID() + copy_bp = copy_bps.FindBreakpointByID(copy_id) + self.assertTrue(copy_bp.IsValid(), "Could not find copy breakpoint %d."%(copy_id)) + + copy_desc = lldb.SBStream() + copy_bp.GetDescription(copy_desc, False) + copy_text = copy_desc.GetData() + + # These two should be identical. + # print ("Source text for %d is %s."%(i, source_text)) + self.assertTrue (source_text == copy_text, "Source and dest breakpoints are not identical: \nsource: %s\ndest: %s"%(source_text, copy_text)) + + def do_check_resolvers(self): + """Use Python APIs to check serialization of breakpoint resolvers""" + + empty_module_list = lldb.SBFileSpecList() + empty_cu_list = lldb.SBFileSpecList() + blubby_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "blubby.c")) + + # It isn't actually important for these purposes that these breakpoint + # actually have locations. + source_bps = lldb.SBBreakpointList(self.orig_target) + source_bps.Append(self.orig_target.BreakpointCreateByLocation("blubby.c", 666)) + # Make sure we do one breakpoint right: + self.check_equivalence(source_bps) + source_bps.Clear() + + source_bps.Append(self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list)) + source_bps.Append(self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeFull, empty_module_list,empty_cu_list)) + source_bps.Append(self.orig_target.BreakpointCreateBySourceRegex("dont really care", blubby_file_spec)) + + # And some number greater than one: + self.check_equivalence(source_bps) + + def do_check_filters(self): + """Use Python APIs to check serialization of breakpoint filters.""" + module_list = lldb.SBFileSpecList() + module_list.Append(lldb.SBFileSpec("SomeBinary")) + module_list.Append(lldb.SBFileSpec("SomeOtherBinary")) + + cu_list = lldb.SBFileSpecList() + cu_list.Append(lldb.SBFileSpec("SomeCU.c")) + cu_list.Append(lldb.SBFileSpec("AnotherCU.c")) + cu_list.Append(lldb.SBFileSpec("ThirdCU.c")) + + blubby_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "blubby.c")) + + # It isn't actually important for these purposes that these breakpoint + # actually have locations. + source_bps = lldb.SBBreakpointList(self.orig_target) + bkpt = self.orig_target.BreakpointCreateByLocation(blubby_file_spec, 666, 0, module_list) + source_bps.Append(bkpt) + + # Make sure we do one right: + self.check_equivalence(source_bps) + source_bps.Clear() + + bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, module_list, cu_list) + source_bps.Append(bkpt) + bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeFull, module_list, cu_list) + source_bps.Append(bkpt) + bkpt = self.orig_target.BreakpointCreateBySourceRegex("dont really care", blubby_file_spec) + source_bps.Append(bkpt) + + # And some number greater than one: + self.check_equivalence(source_bps) + + def do_check_options(self): + """Use Python APIs to check serialization of breakpoint options.""" + + empty_module_list = lldb.SBFileSpecList() + empty_cu_list = lldb.SBFileSpecList() + blubby_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "blubby.c")) + + # It isn't actually important for these purposes that these breakpoint + # actually have locations. + source_bps = lldb.SBBreakpointList(self.orig_target) + + bkpt = self.orig_target.BreakpointCreateByLocation( + lldb.SBFileSpec("blubby.c"), 666, 333, 0, lldb.SBFileSpecList()) + bkpt.SetEnabled(False) + bkpt.SetOneShot(True) + bkpt.SetThreadID(10) + source_bps.Append(bkpt) + + # Make sure we get one right: + self.check_equivalence(source_bps) + source_bps.Clear() + + bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list) + bkpt.SetIgnoreCount(10) + bkpt.SetThreadName("grubby") + source_bps.Append(bkpt) + + bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list) + bkpt.SetCondition("gonna remove this") + bkpt.SetCondition("") + source_bps.Append(bkpt) + + bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeFull, empty_module_list,empty_cu_list) + bkpt.SetCondition("something != something_else") + bkpt.SetQueueName("grubby") + bkpt.AddName("FirstName") + bkpt.AddName("SecondName") + bkpt.SetScriptCallbackBody('\tprint("I am a function that prints.")\n\tprint("I don\'t do anything else")\n') + source_bps.Append(bkpt) + + bkpt = self.orig_target.BreakpointCreateBySourceRegex("dont really care", blubby_file_spec) + cmd_list = lldb.SBStringList() + cmd_list.AppendString("frame var") + cmd_list.AppendString("thread backtrace") + + bkpt.SetCommandLineCommands(cmd_list) + source_bps.Append(bkpt) + + self.check_equivalence(source_bps) + + def do_check_appending(self): + """Use Python APIs to check appending to already serialized options.""" + + empty_module_list = lldb.SBFileSpecList() + empty_cu_list = lldb.SBFileSpecList() + blubby_file_spec = lldb.SBFileSpec(os.path.join(self.getSourceDir(), "blubby.c")) + + # It isn't actually important for these purposes that these breakpoint + # actually have locations. + + all_bps = lldb.SBBreakpointList(self.orig_target) + source_bps = lldb.SBBreakpointList(self.orig_target) + + bkpt = self.orig_target.BreakpointCreateByLocation( + lldb.SBFileSpec("blubby.c"), 666, 333, 0, lldb.SBFileSpecList()) + bkpt.SetEnabled(False) + bkpt.SetOneShot(True) + bkpt.SetThreadID(10) + source_bps.Append(bkpt) + all_bps.Append(bkpt) + + error = lldb.SBError() + error = self.orig_target.BreakpointsWriteToFile(self.bkpts_file_spec, source_bps) + self.assertTrue(error.Success(), "Failed writing breakpoints to file: %s."%(error.GetCString())) + + source_bps.Clear() + + bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeAuto, empty_module_list, empty_cu_list) + bkpt.SetIgnoreCount(10) + bkpt.SetThreadName("grubby") + source_bps.Append(bkpt) + all_bps.Append(bkpt) + + bkpt = self.orig_target.BreakpointCreateByName("blubby", lldb.eFunctionNameTypeFull, empty_module_list,empty_cu_list) + bkpt.SetCondition("something != something_else") + bkpt.SetQueueName("grubby") + bkpt.AddName("FirstName") + bkpt.AddName("SecondName") + + source_bps.Append(bkpt) + all_bps.Append(bkpt) + + error = self.orig_target.BreakpointsWriteToFile(self.bkpts_file_spec, source_bps, True) + self.assertTrue(error.Success(), "Failed appending breakpoints to file: %s."%(error.GetCString())) + + self.check_equivalence(all_bps) + + def do_check_names(self): + bkpt = self.orig_target.BreakpointCreateByLocation( + lldb.SBFileSpec("blubby.c"), 666, 333, 0, lldb.SBFileSpecList()) + good_bkpt_name = "GoodBreakpoint" + write_bps = lldb.SBBreakpointList(self.orig_target) + bkpt.AddName(good_bkpt_name) + write_bps.Append(bkpt) + + error = lldb.SBError() + error = self.orig_target.BreakpointsWriteToFile(self.bkpts_file_spec, write_bps) + self.assertTrue(error.Success(), "Failed writing breakpoints to file: %s."%(error.GetCString())) + + copy_bps = lldb.SBBreakpointList(self.copy_target) + names_list = lldb.SBStringList() + names_list.AppendString("NoSuchName") + + error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, names_list, copy_bps) + self.assertTrue(error.Success(), "Failed reading breakpoints from file: %s"%(error.GetCString())) + self.assertTrue(copy_bps.GetSize() == 0, "Found breakpoints with a nonexistent name.") + + names_list.AppendString(good_bkpt_name) + error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, names_list, copy_bps) + self.assertTrue(error.Success(), "Failed reading breakpoints from file: %s"%(error.GetCString())) + self.assertTrue(copy_bps.GetSize() == 1, "Found the matching breakpoint.") + + def do_check_extra_args(self): + + import side_effect + interp = self.dbg.GetCommandInterpreter() + error = lldb.SBError() + + script_name = os.path.join(self.getSourceDir(), "resolver.py") + + command = "command script import " + script_name + result = lldb.SBCommandReturnObject() + interp.HandleCommand(command, result) + self.assertTrue(result.Succeeded(), "com scr imp failed: %s"%(result.GetError())) + + # First make sure a scripted breakpoint with no args works: + bkpt = self.orig_target.BreakpointCreateFromScript("resolver.Resolver", lldb.SBStructuredData(), + lldb.SBFileSpecList(), lldb.SBFileSpecList()) + self.assertTrue(bkpt.IsValid(), "Bkpt is valid") + write_bps = lldb.SBBreakpointList(self.orig_target) + + error = self.orig_target.BreakpointsWriteToFile(self.bkpts_file_spec, write_bps) + self.assertTrue(error.Success(), "Failed writing breakpoints: %s"%(error.GetCString())) + + side_effect.g_extra_args = None + copy_bps = lldb.SBBreakpointList(self.copy_target) + error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, copy_bps) + self.assertTrue(error.Success(), "Failed reading breakpoints: %s"%(error.GetCString())) + + self.assertEqual(copy_bps.GetSize(), 1, "Got one breakpoint from file.") + no_keys = lldb.SBStringList() + side_effect.g_extra_args.GetKeys(no_keys) + self.assertEqual(no_keys.GetSize(), 0, "Should have no keys") + + self.orig_target.DeleteAllBreakpoints() + self.copy_target.DeleteAllBreakpoints() + + # Now try one with extra args: + + extra_args = lldb.SBStructuredData() + stream = lldb.SBStream() + stream.Print('{"first_arg" : "first_value", "second_arg" : "second_value"}') + extra_args.SetFromJSON(stream) + self.assertTrue(extra_args.IsValid(), "SBStructuredData is valid.") + + bkpt = self.orig_target.BreakpointCreateFromScript("resolver.Resolver", + extra_args, lldb.SBFileSpecList(), lldb.SBFileSpecList()) + self.assertTrue(bkpt.IsValid(), "Bkpt is valid") + write_bps = lldb.SBBreakpointList(self.orig_target) + + error = self.orig_target.BreakpointsWriteToFile(self.bkpts_file_spec, write_bps) + self.assertTrue(error.Success(), "Failed writing breakpoints: %s"%(error.GetCString())) + + orig_extra_args = side_effect.g_extra_args + self.assertTrue(orig_extra_args.IsValid(), "Extra args originally valid") + + orig_keys = lldb.SBStringList() + orig_extra_args.GetKeys(orig_keys) + self.assertEqual(2, orig_keys.GetSize(), "Should have two keys") + + side_effect.g_extra_args = None + + copy_bps = lldb.SBBreakpointList(self.copy_target) + error = self.copy_target.BreakpointsCreateFromFile(self.bkpts_file_spec, copy_bps) + self.assertTrue(error.Success(), "Failed reading breakpoints: %s"%(error.GetCString())) + + self.assertEqual(copy_bps.GetSize(), 1, "Got one breakpoint from file.") + + copy_extra_args = side_effect.g_extra_args + copy_keys = lldb.SBStringList() + copy_extra_args.GetKeys(copy_keys) + self.assertEqual(2, copy_keys.GetSize(), "Copy should have two keys") + + for idx in range(0, orig_keys.GetSize()): + key = orig_keys.GetStringAtIndex(idx) + copy_value = copy_extra_args.GetValueForKey(key).GetStringValue(100) + + if key == "first_arg": + self.assertEqual(copy_value, "first_value") + elif key == "second_arg": + self.assertEqual(copy_value, "second_value") + else: + self.Fail("Unknown key: %s"%(key)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/main.c new file mode 100644 index 00000000000..b1ed4465c1d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/main.c @@ -0,0 +1,53 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to demonstrate the capability of the lldb command +// "breakpoint modify -i <count> breakpt-id" to set the number of times a +// breakpoint is skipped before stopping. Ignore count can also be set upon +// breakpoint creation by 'breakpoint set ... -i <count>'. + +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); // a(3) -> c(3) Find the call site of c(3). + + 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) Find the call site of b(2). + printf("b(2) returns %d\n", B2); + + int A3 = a(3); // a(3) -> c(3) Find the call site of a(3). + printf("a(3) returns %d\n", A3); + + int C1 = c(5); // Find the call site of c in main. + printf ("c(5) returns %d\n", C1); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/resolver.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/resolver.py new file mode 100644 index 00000000000..c3a5af596d2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/resolver.py @@ -0,0 +1,17 @@ +import lldb +import side_effect + +class Resolver: + """This resolver class is just so I can read out the extra_args.""" + + def __init__(self, bkpt, extra_args, dict): + self.bkpt = bkpt + side_effect.g_extra_args = extra_args + + def __callback__(self, sym_ctx): + """Doesn't actually do anything.""" + return + + def get_short_help(self): + return "I am a python breakpoint resolver that does nothing" + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/side_effect.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/side_effect.py new file mode 100644 index 00000000000..868901cfce8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/serialize/side_effect.py @@ -0,0 +1 @@ +g_extra_args = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/Makefile new file mode 100644 index 00000000000..af0cd3066df --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c a.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py new file mode 100644 index 00000000000..0409c78c1b8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/TestSourceRegexBreakpoints.py @@ -0,0 +1,103 @@ +""" +Test lldb breakpoint setting by source regular expression. +This test just tests the source file & function restrictions. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestSourceRegexBreakpoints(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_location(self): + self.build() + self.source_regex_locations() + + def test_restrictions(self): + self.build() + self.source_regex_restrictions() + + def source_regex_locations(self): + """ Test that restricting source expressions to files & to functions. """ + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # First look just in main: + target_files = lldb.SBFileSpecList() + target_files.Append(lldb.SBFileSpec("a.c")) + + func_names = lldb.SBStringList() + func_names.AppendString("a_func") + + source_regex = "Set . breakpoint here" + main_break = target.BreakpointCreateBySourceRegex( + source_regex, lldb.SBFileSpecList(), target_files, func_names) + num_locations = main_break.GetNumLocations() + self.assertTrue( + num_locations == 1, + "a.c in a_func should give one breakpoint, got %d." % + (num_locations)) + + loc = main_break.GetLocationAtIndex(0) + self.assertTrue(loc.IsValid(), "Got a valid location.") + address = loc.GetAddress() + self.assertTrue( + address.IsValid(), + "Got a valid address from the location.") + + a_func_line = line_number("a.c", "Set A breakpoint here") + line_entry = address.GetLineEntry() + self.assertTrue(line_entry.IsValid(), "Got a valid line entry.") + self.assertTrue(line_entry.line == a_func_line, + "Our line number matches the one lldbtest found.") + + def source_regex_restrictions(self): + """ Test that restricting source expressions to files & to functions. """ + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # First look just in main: + target_files = lldb.SBFileSpecList() + target_files.Append(lldb.SBFileSpec("main.c")) + source_regex = "Set . breakpoint here" + main_break = target.BreakpointCreateBySourceRegex( + source_regex, lldb.SBFileSpecList(), target_files, lldb.SBStringList()) + + num_locations = main_break.GetNumLocations() + self.assertTrue( + num_locations == 2, + "main.c should have 2 matches, got %d." % + (num_locations)) + + # Now look in both files: + target_files.Append(lldb.SBFileSpec("a.c")) + + main_break = target.BreakpointCreateBySourceRegex( + source_regex, lldb.SBFileSpecList(), target_files, lldb.SBStringList()) + + num_locations = main_break.GetNumLocations() + self.assertTrue( + num_locations == 4, + "main.c and a.c should have 4 matches, got %d." % + (num_locations)) + + # Now restrict it to functions: + func_names = lldb.SBStringList() + func_names.AppendString("main_func") + main_break = target.BreakpointCreateBySourceRegex( + source_regex, lldb.SBFileSpecList(), target_files, func_names) + + num_locations = main_break.GetNumLocations() + self.assertTrue( + num_locations == 2, + "main_func in main.c and a.c should have 2 matches, got %d." % + (num_locations)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/a.c new file mode 100644 index 00000000000..056583f1c42 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/a.c @@ -0,0 +1,16 @@ +#include <stdio.h> + +#include "a.h" + +static int +main_func(int input) +{ + return printf("Set B breakpoint here: %d", input); +} + +int +a_func(int input) +{ + input += 1; // Set A breakpoint here; + return main_func(input); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/a.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/a.h new file mode 100644 index 00000000000..f578ac0304c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/a.h @@ -0,0 +1 @@ +int a_func(int); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/main.c new file mode 100644 index 00000000000..9c8625e877f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/source_regexp/main.c @@ -0,0 +1,17 @@ +#include <stdio.h> +#include "a.h" + +int +main_func(int input) +{ + return printf("Set B breakpoint here: %d.\n", input); +} + +int +main() +{ + a_func(10); + main_func(10); + printf("Set a breakpoint here:\n"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/step_over_breakpoint/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/step_over_breakpoint/Makefile new file mode 100644 index 00000000000..2c00681fa22 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/step_over_breakpoint/Makefile @@ -0,0 +1,8 @@ +CXX_SOURCES := main.cpp + +ifneq (,$(findstring icc,$(CC))) + CXXFLAGS_EXTRAS := -debug inline-debug-info +endif + + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/step_over_breakpoint/TestStepOverBreakpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/step_over_breakpoint/TestStepOverBreakpoint.py new file mode 100644 index 00000000000..ea94fd3ec1f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/step_over_breakpoint/TestStepOverBreakpoint.py @@ -0,0 +1,118 @@ +""" +Test that breakpoints do not affect stepping. +Check for correct StopReason when stepping to the line with breakpoint +which chould be eStopReasonBreakpoint in general, +and eStopReasonPlanComplete when breakpoint's condition fails. +""" + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class StepOverBreakpointsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + + self.build() + exe = self.getBuildArtifact("a.out") + src = lldb.SBFileSpec("main.cpp") + + # Create a target by the debugger. + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + # Setup four breakpoints, two of them with false condition + self.line1 = line_number('main.cpp', "breakpoint_1") + self.line4 = line_number('main.cpp', "breakpoint_4") + + self.breakpoint1 = self.target.BreakpointCreateByLocation(src, self.line1) + self.assertTrue( + self.breakpoint1 and self.breakpoint1.GetNumLocations() == 1, + VALID_BREAKPOINT) + + self.breakpoint2 = self.target.BreakpointCreateBySourceRegex("breakpoint_2", src) + self.breakpoint2.GetLocationAtIndex(0).SetCondition('false') + + self.breakpoint3 = self.target.BreakpointCreateBySourceRegex("breakpoint_3", src) + self.breakpoint3.GetLocationAtIndex(0).SetCondition('false') + + self.breakpoint4 = self.target.BreakpointCreateByLocation(src, self.line4) + + # Start debugging + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertIsNotNone(self.process, PROCESS_IS_VALID) + self.thread = lldbutil.get_one_thread_stopped_at_breakpoint(self.process, self.breakpoint1) + self.assertIsNotNone(self.thread, "Didn't stop at breakpoint 1.") + + def test_step_instruction(self): + # Count instructions between breakpoint_1 and breakpoint_4 + contextList = self.target.FindFunctions('main', lldb.eFunctionNameTypeAuto) + self.assertEquals(contextList.GetSize(), 1) + symbolContext = contextList.GetContextAtIndex(0) + function = symbolContext.GetFunction() + self.assertTrue(function) + instructions = function.GetInstructions(self.target) + addr_1 = self.breakpoint1.GetLocationAtIndex(0).GetAddress() + addr_4 = self.breakpoint4.GetLocationAtIndex(0).GetAddress() + + # if third argument is true then the count will be the number of + # instructions on which a breakpoint can be set. + # start = addr_1, end = addr_4, canSetBreakpoint = True + steps_expected = instructions.GetInstructionsCount(addr_1, addr_4, True) + step_count = 0 + # Step from breakpoint_1 to breakpoint_4 + while True: + self.thread.StepInstruction(True) + step_count = step_count + 1 + self.assertEquals(self.process.GetState(), lldb.eStateStopped) + self.assertTrue(self.thread.GetStopReason() == lldb.eStopReasonPlanComplete or + self.thread.GetStopReason() == lldb.eStopReasonBreakpoint) + if (self.thread.GetStopReason() == lldb.eStopReasonBreakpoint) : + # we should not stop on breakpoint_2 and _3 because they have false condition + self.assertEquals(self.thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.line4) + # breakpoint_2 and _3 should not affect step count + self.assertTrue(step_count >= steps_expected) + break + + # Run the process until termination + self.process.Continue() + self.assertEquals(self.process.GetState(), lldb.eStateExited) + + @skipIf(bugnumber="llvm.org/pr31972", hostoslist=["windows"]) + def test_step_over(self): + #lldb.DBG.EnableLog("lldb", ["step","breakpoint"]) + + self.thread.StepOver() + # We should be stopped at the breakpoint_2 line with stop plan complete reason + self.assertEquals(self.process.GetState(), lldb.eStateStopped) + self.assertEquals(self.thread.GetStopReason(), lldb.eStopReasonPlanComplete) + + self.thread.StepOver() + # We should be stopped at the breakpoint_3 line with stop plan complete reason + self.assertEquals(self.process.GetState(), lldb.eStateStopped) + self.assertEquals(self.thread.GetStopReason(), lldb.eStopReasonPlanComplete) + + self.thread.StepOver() + # We should be stopped at the breakpoint_4 + self.assertEquals(self.process.GetState(), lldb.eStateStopped) + self.assertEquals(self.thread.GetStopReason(), lldb.eStopReasonBreakpoint) + thread1 = lldbutil.get_one_thread_stopped_at_breakpoint(self.process, self.breakpoint4) + self.assertEquals(self.thread, thread1, "Didn't stop at breakpoint 4.") + + # Check that stepping does not affect breakpoint's hit count + self.assertEquals(self.breakpoint1.GetHitCount(), 1) + self.assertEquals(self.breakpoint2.GetHitCount(), 0) + self.assertEquals(self.breakpoint3.GetHitCount(), 0) + self.assertEquals(self.breakpoint4.GetHitCount(), 1) + + # Run the process until termination + self.process.Continue() + self.assertEquals(self.process.GetState(), lldb.eStateExited) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/step_over_breakpoint/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/step_over_breakpoint/main.cpp new file mode 100644 index 00000000000..8cfd34b73b5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/breakpoint/step_over_breakpoint/main.cpp @@ -0,0 +1,12 @@ + +int func() { return 1; } + +int +main(int argc, char const *argv[]) +{ + int a = 0; // breakpoint_1 + int b = func(); // breakpoint_2 + a = b + func(); // breakpoint_3 + return 0; // breakpoint_4 +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/.categories new file mode 100644 index 00000000000..3a3f4df6416 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/.categories @@ -0,0 +1 @@ +cmdline diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py new file mode 100644 index 00000000000..26c70c1e7fc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py @@ -0,0 +1,431 @@ +""" +Test the lldb command line completion mechanism. +""" + + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbplatform +from lldbsuite.test import lldbutil + + +class CommandLineCompletionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @classmethod + def classCleanup(cls): + """Cleanup the test byproducts.""" + try: + os.remove("child_send.txt") + os.remove("child_read.txt") + except: + pass + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_at(self): + """Test that 'at' completes to 'attach '.""" + self.complete_from_to('at', 'attach ') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_de(self): + """Test that 'de' completes to 'detach '.""" + self.complete_from_to('de', 'detach ') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_frame_variable(self): + self.build() + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + '// Break here', self.main_source_spec) + self.assertEquals(process.GetState(), lldb.eStateStopped) + # FIXME: This pulls in the debug information to make the completions work, + # but the completions should also work without. + self.runCmd("frame variable fooo") + + self.complete_from_to('frame variable fo', + 'frame variable fooo') + self.complete_from_to('frame variable fooo.', + 'frame variable fooo.') + self.complete_from_to('frame variable fooo.dd', + 'frame variable fooo.dd') + + self.complete_from_to('frame variable ptr_fooo->', + 'frame variable ptr_fooo->') + self.complete_from_to('frame variable ptr_fooo->dd', + 'frame variable ptr_fooo->dd') + + self.complete_from_to('frame variable cont', + 'frame variable container') + self.complete_from_to('frame variable container.', + 'frame variable container.MemberVar') + self.complete_from_to('frame variable container.Mem', + 'frame variable container.MemberVar') + + self.complete_from_to('frame variable ptr_cont', + 'frame variable ptr_container') + self.complete_from_to('frame variable ptr_container->', + 'frame variable ptr_container->MemberVar') + self.complete_from_to('frame variable ptr_container->Mem', + 'frame variable ptr_container->MemberVar') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_process_attach_dash_dash_con(self): + """Test that 'process attach --con' completes to 'process attach --continue '.""" + self.complete_from_to( + 'process attach --con', + 'process attach --continue ') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_process_launch_arch(self): + self.complete_from_to('process launch --arch ', + ['mips', + 'arm64']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_ambiguous_long_opt(self): + self.completions_match('breakpoint modify --th', + ['--thread-id', + '--thread-index', + '--thread-name']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_plugin_load(self): + self.complete_from_to('plugin load ', []) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_log_enable(self): + self.complete_from_to('log enable ll', ['lldb']) + self.complete_from_to('log enable dw', ['dwarf']) + self.complete_from_to('log enable lldb al', ['all']) + self.complete_from_to('log enable lldb sym', ['symbol']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_log_enable(self): + self.complete_from_to('log disable ll', ['lldb']) + self.complete_from_to('log disable dw', ['dwarf']) + self.complete_from_to('log disable lldb al', ['all']) + self.complete_from_to('log disable lldb sym', ['symbol']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_log_list(self): + self.complete_from_to('log list ll', ['lldb']) + self.complete_from_to('log list dw', ['dwarf']) + self.complete_from_to('log list ll', ['lldb']) + self.complete_from_to('log list lldb dwa', ['dwarf']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_quoted_command(self): + self.complete_from_to('"set', + ['"settings" ']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_quoted_arg_with_quoted_command(self): + self.complete_from_to('"settings" "repl', + ['"replace" ']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_quoted_arg_without_quoted_command(self): + self.complete_from_to('settings "repl', + ['"replace" ']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_single_quote_command(self): + self.complete_from_to("'set", + ["'settings' "]) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_terminated_quote_command(self): + # This should not crash, but we don't get any + # reasonable completions from this. + self.complete_from_to("'settings'", []) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_process_launch_arch_arm(self): + self.complete_from_to('process launch --arch arm', + ['arm64']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_target_symbols_add_shlib(self): + # Doesn't seem to work, but at least it shouldn't crash. + self.complete_from_to('target symbols add --shlib ', []) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_log_file(self): + # Complete in our source directory which contains a 'main.cpp' file. + src_dir = os.path.dirname(os.path.realpath(__file__)) + '/' + self.complete_from_to('log enable lldb expr -f ' + src_dir, + ['main.cpp']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_log_dir(self): + # Complete our source directory. + src_dir = os.path.dirname(os.path.realpath(__file__)) + self.complete_from_to('log enable lldb expr -f ' + src_dir, + [src_dir + os.sep], turn_off_re_match=True) + + # <rdar://problem/11052829> + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_infinite_loop_while_completing(self): + """Test that 'process print hello\' completes to itself and does not infinite loop.""" + self.complete_from_to('process print hello\\', 'process print hello\\', + turn_off_re_match=True) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_watchpoint_co(self): + """Test that 'watchpoint co' completes to 'watchpoint command '.""" + self.complete_from_to('watchpoint co', 'watchpoint command ') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_watchpoint_command_space(self): + """Test that 'watchpoint command ' completes to ['add', 'delete', 'list'].""" + self.complete_from_to( + 'watchpoint command ', [ + 'add', 'delete', 'list']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_watchpoint_command_a(self): + """Test that 'watchpoint command a' completes to 'watchpoint command add '.""" + self.complete_from_to( + 'watchpoint command a', + 'watchpoint command add ') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_watchpoint_set_ex(self): + """Test that 'watchpoint set ex' completes to 'watchpoint set expression '.""" + self.complete_from_to( + 'watchpoint set ex', + 'watchpoint set expression ') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_watchpoint_set_var(self): + """Test that 'watchpoint set var' completes to 'watchpoint set variable '.""" + self.complete_from_to('watchpoint set var', 'watchpoint set variable ') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_help_fi(self): + """Test that 'help fi' completes to ['file', 'finish'].""" + self.complete_from_to( + 'help fi', [ + 'file', 'finish']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_help_watchpoint_s(self): + """Test that 'help watchpoint s' completes to 'help watchpoint set '.""" + self.complete_from_to('help watchpoint s', 'help watchpoint set ') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_append_target_er(self): + """Test that 'settings append target.er' completes to 'settings append target.error-path'.""" + self.complete_from_to( + 'settings append target.er', + 'settings append target.error-path') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_insert_after_target_en(self): + """Test that 'settings insert-after target.env' completes to 'settings insert-after target.env-vars'.""" + self.complete_from_to( + 'settings insert-after target.env', + 'settings insert-after target.env-vars') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_insert_before_target_en(self): + """Test that 'settings insert-before target.env' completes to 'settings insert-before target.env-vars'.""" + self.complete_from_to( + 'settings insert-before target.env', + 'settings insert-before target.env-vars') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_replace_target_ru(self): + """Test that 'settings replace target.ru' completes to 'settings replace target.run-args'.""" + self.complete_from_to( + 'settings replace target.ru', + 'settings replace target.run-args') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_show_term(self): + self.complete_from_to( + 'settings show term-', + 'settings show term-width') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_list_term(self): + self.complete_from_to( + 'settings list term-', + 'settings list term-width') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_remove_term(self): + self.complete_from_to( + 'settings remove term-', + 'settings remove term-width') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_s(self): + """Test that 'settings s' completes to ['set', 'show'].""" + self.complete_from_to( + 'settings s', [ + 'set', 'show']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_set_th(self): + """Test that 'settings set thread-f' completes to 'settings set thread-format'.""" + self.complete_from_to('settings set thread-f', 'settings set thread-format') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_s_dash(self): + """Test that 'settings set --g' completes to 'settings set --global'.""" + self.complete_from_to('settings set --g', 'settings set --global') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_clear_th(self): + """Test that 'settings clear thread-f' completes to 'settings clear thread-format'.""" + self.complete_from_to( + 'settings clear thread-f', + 'settings clear thread-format') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_set_ta(self): + """Test that 'settings set ta' completes to 'settings set target.'.""" + self.complete_from_to( + 'settings set target.ma', + 'settings set target.max-') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_set_target_exec(self): + """Test that 'settings set target.exec' completes to 'settings set target.exec-search-paths '.""" + self.complete_from_to( + 'settings set target.exec', + 'settings set target.exec-search-paths') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_set_target_pr(self): + """Test that 'settings set target.pr' completes to [ + 'target.prefer-dynamic-value', 'target.process.'].""" + self.complete_from_to('settings set target.pr', + ['target.prefer-dynamic-value', + 'target.process.']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_set_target_process(self): + """Test that 'settings set target.process' completes to 'settings set target.process.'.""" + self.complete_from_to( + 'settings set target.process', + 'settings set target.process.') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_set_target_process_dot(self): + """Test that 'settings set target.process.t' completes to 'settings set target.process.thread.'.""" + self.complete_from_to( + 'settings set target.process.t', + 'settings set target.process.thread.') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_settings_set_target_process_thread_dot(self): + """Test that 'settings set target.process.thread.' completes to [ + 'target.process.thread.step-avoid-regexp', 'target.process.thread.trace-thread'].""" + self.complete_from_to('settings set target.process.thread.', + ['target.process.thread.step-avoid-regexp', + 'target.process.thread.trace-thread']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_target_space(self): + """Test that 'target ' completes to ['create', 'delete', 'list', + 'modules', 'select', 'stop-hook', 'variable'].""" + self.complete_from_to('target ', + ['create', + 'delete', + 'list', + 'modules', + 'select', + 'stop-hook', + 'variable']) + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_target_create_dash_co(self): + """Test that 'target create --co' completes to 'target variable --core '.""" + self.complete_from_to('target create --co', 'target create --core ') + + @skipIfFreeBSD # timing out on the FreeBSD buildbot + def test_target_va(self): + """Test that 'target va' completes to 'target variable '.""" + self.complete_from_to('target va', 'target variable ') + + def test_command_argument_completion(self): + """Test completion of command arguments""" + self.complete_from_to("watchpoint set variable -", ["-w", "-s"]) + self.complete_from_to('watchpoint set variable -w', 'watchpoint set variable -w ') + self.complete_from_to("watchpoint set variable --", ["--watch", "--size"]) + self.complete_from_to("watchpoint set variable --w", "watchpoint set variable --watch") + self.complete_from_to('watchpoint set variable -w ', ['read', 'write', 'read_write']) + self.complete_from_to("watchpoint set variable --watch ", ["read", "write", "read_write"]) + self.complete_from_to("watchpoint set variable --watch w", "watchpoint set variable --watch write") + self.complete_from_to('watchpoint set variable -w read_', 'watchpoint set variable -w read_write') + # Now try the same thing with a variable name (non-option argument) to + # test that getopts arg reshuffling doesn't confuse us. + self.complete_from_to("watchpoint set variable foo -", ["-w", "-s"]) + self.complete_from_to('watchpoint set variable foo -w', 'watchpoint set variable foo -w ') + self.complete_from_to("watchpoint set variable foo --", ["--watch", "--size"]) + self.complete_from_to("watchpoint set variable foo --w", "watchpoint set variable foo --watch") + self.complete_from_to('watchpoint set variable foo -w ', ['read', 'write', 'read_write']) + self.complete_from_to("watchpoint set variable foo --watch ", ["read", "write", "read_write"]) + self.complete_from_to("watchpoint set variable foo --watch w", "watchpoint set variable foo --watch write") + self.complete_from_to('watchpoint set variable foo -w read_', 'watchpoint set variable foo -w read_write') + + def test_completion_description_commands(self): + """Test descriptions of top-level command completions""" + self.check_completion_with_desc("", [ + ["command", "Commands for managing custom LLDB commands."], + ["breakpoint", "Commands for operating on breakpoints (see 'help b' for shorthand.)"] + ]) + + self.check_completion_with_desc("pl", [ + ["platform", "Commands to manage and create platforms."], + ["plugin", "Commands for managing LLDB plugins."] + ]) + + # Just check that this doesn't crash. + self.check_completion_with_desc("comman", []) + self.check_completion_with_desc("non-existent-command", []) + + def test_completion_description_command_options(self): + """Test descriptions of command options""" + # Short options + self.check_completion_with_desc("breakpoint set -", [ + ["-h", "Set the breakpoint on exception catcH."], + ["-w", "Set the breakpoint on exception throW."] + ]) + + # Long options. + self.check_completion_with_desc("breakpoint set --", [ + ["--on-catch", "Set the breakpoint on exception catcH."], + ["--on-throw", "Set the breakpoint on exception throW."] + ]) + + # Ambiguous long options. + self.check_completion_with_desc("breakpoint set --on-", [ + ["--on-catch", "Set the breakpoint on exception catcH."], + ["--on-throw", "Set the breakpoint on exception throW."] + ]) + + # Unknown long option. + self.check_completion_with_desc("breakpoint set --Z", [ + ]) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489") + def test_symbol_name(self): + self.build() + self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.complete_from_to('breakpoint set -n Fo', + 'breakpoint set -n Foo::Bar(int,\\ int)', + turn_off_re_match=True) + # No completion for Qu because the candidate is + # (anonymous namespace)::Quux(). + self.complete_from_to('breakpoint set -n Qu', '') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/main.cpp new file mode 100644 index 00000000000..eba81dc4c54 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/completion/main.cpp @@ -0,0 +1,24 @@ +class Foo +{ +public: + int Bar(int x, int y) + { + return x + y; + } +}; + +namespace { int Quux (void) { return 0; } } + +struct Container { int MemberVar; }; + +int main() +{ + Foo fooo; + Foo *ptr_fooo = &fooo; + fooo.Bar(1, 2); + + Container container; + Container *ptr_container = &container; + int q = Quux(); + return container.MemberVar = 3; // Break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/.lldb b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/.lldb new file mode 100644 index 00000000000..4be90efee23 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/.lldb @@ -0,0 +1,3 @@ +breakpoint set -n c +command script import -r conditional_break.py +breakpoint command add 1 -F "conditional_break.stop_if_called_from_a" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py new file mode 100644 index 00000000000..cc48a639724 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py @@ -0,0 +1,138 @@ +""" +Test conditionally break on a function and inspect its variables. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +# rdar://problem/8532131 +# lldb not able to digest the clang-generated debug info correctly with respect to function name +# +# This class currently fails for clang as well as llvm-gcc. + + +class ConditionalBreakTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + def test_with_python(self): + """Exercise some thread and frame APIs to break if c() is called by a().""" + self.build() + self.do_conditional_break() + + def test_with_command(self): + """Simulate a user using lldb commands to break on c() if called from a().""" + self.build() + self.simulate_conditional_break_by_user() + + def do_conditional_break(self): + """Exercise some thread and frame APIs to break if c() is called by a().""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByName("c", exe) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.assertTrue(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 c's parent frame is a 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(). + # + # The 10 in range(10) is just an arbitrary number, which means we would + # like to try for at most 10 times. + for j in range(10): + if self.TraceOn(): + print("j is: ", j) + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, breakpoint) + self.assertIsNotNone( + thread, "Expected one thread to be stopped at the breakpoint") + + if thread.GetNumFrames() >= 2: + frame0 = thread.GetFrameAtIndex(0) + name0 = frame0.GetFunction().GetName() + frame1 = thread.GetFrameAtIndex(1) + name1 = frame1.GetFunction().GetName() + # lldbutil.print_stacktrace(thread) + self.assertTrue(name0 == "c", "Break on function c()") + if (name1 == "a"): + # 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(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.FindVariable("val") + self.assertEqual("int", val.GetTypeName()) + self.assertEqual("3", val.GetValue()) + break + + process.Continue() + + def simulate_conditional_break_by_user(self): + """Simulate a user using lldb commands to break on c() if called from a().""" + + # Sourcing .lldb in the current working directory, which sets the main + # executable, sets the breakpoint on c(), and adds the callback for the + # breakpoint such that lldb only stops when the caller of c() is a(). + # the "my" package that defines the date() function. + if self.TraceOn(): + print("About to source .lldb") + + if not self.TraceOn(): + self.HideStdout() + + # Separate out the "file " + self.getBuildArtifact("a.out") command from .lldb file, for the sake of + # remote testsuite. + self.runCmd("file " + self.getBuildArtifact("a.out")) + self.runCmd("command source .lldb") + + self.runCmd("break list") + + if self.TraceOn(): + print("About to run.") + self.runCmd("run", RUN_SUCCEEDED) + + self.runCmd("break list") + + if self.TraceOn(): + print("Done running") + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # The frame info for frame #0 points to a.out`c and its immediate caller + # (frame #1) points to a.out`a. + + self.expect("frame info", "We should stop at c()", + substrs=["a.out`c"]) + + # Select our parent frame as the current frame. + self.runCmd("frame select 1") + self.expect("frame info", "The immediate caller should be a()", + substrs=["a.out`a"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py new file mode 100644 index 00000000000..4f2746428cd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py @@ -0,0 +1,29 @@ +import lldb + + +def stop_if_called_from_a(frame, bp_loc, dict): + + thread = frame.GetThread() + process = thread.GetProcess() + target = process.GetTarget() + dbg = target.GetDebugger() + + # Perform synchronous interaction with the debugger. + old_async = dbg.GetAsync() + dbg.SetAsync(True) + + # We check the call frames in order to stop only when the immediate caller + # of the leaf function c() is a(). If it's not the right caller, we ask the + # command interpreter to continue execution. + + should_stop = True + if thread.GetNumFrames() >= 2: + + if (thread.frames[0].function.name == + 'c' and thread.frames[1].function.name == 'a'): + should_stop = True + else: + should_stop = False + + dbg.SetAsync(old_async) + return should_stop diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/main.c new file mode 100644 index 00000000000..dc528a458b3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/conditional_break/main.c @@ -0,0 +1,53 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to demonstrate the capability of the lldb command +// "breakpoint command add" to add a set of commands to a breakpoint to be +// executed when the breakpoint is hit. +// +// In particular, we want to break within c(), but only if the immediate caller +// is a(). + +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); // Find the line number where c's parent frame is a here. + + return val; +} + +int b(int val) +{ + return c(val); +} + +int c(int val) +{ + return val + 3; +} + +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; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/.categories new file mode 100644 index 00000000000..ea135483a48 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/.categories @@ -0,0 +1 @@ +darwin-log diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/basic/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/basic/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/basic/TestDarwinLogBasic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/basic/TestDarwinLogBasic.py new file mode 100644 index 00000000000..6e6607ac232 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/basic/TestDarwinLogBasic.py @@ -0,0 +1,35 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + +# System imports + +# LLDB imports +from lldbsuite.test import darwin_log +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest + + +class TestDarwinLogBasic(darwin_log.DarwinLogEventBasedTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + @decorators.add_test_categories(['pyapi']) + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(archs=["i386"], bugnumber="rdar://28655626") + @decorators.expectedFailureAll(bugnumber="rdar://30645203") + def test_SBStructuredData_gets_broadcasted(self): + """Exercise SBStructuredData API.""" + + # Run the test. + log_entries = self.do_test(None, max_entry_count=2) + + # Validate that we received our two log entries. + self.assertEqual(len(log_entries), 1, + "Expected one log entry to arrive via events.") + self.assertEqual(log_entries[0]['message'], "Hello, world", + "Log message should match expected content.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/basic/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/basic/main.c new file mode 100644 index 00000000000..c69d0ab1c35 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/basic/main.c @@ -0,0 +1,31 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/log.h> +#include <stdio.h> + +#include "../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger = os_log_create("org.llvm.lldb.test", "basic-test"); + if (!logger) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_log(logger, "Hello, world"); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/common/darwin_log_common.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/common/darwin_log_common.h new file mode 100644 index 00000000000..de923b94911 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/common/darwin_log_common.h @@ -0,0 +1,6 @@ +// The number of seconds to wait at the end of the test inferior before +// exiting. This delay is needed to ensure the logging infrastructure +// has flushed out the message. If we finished before all messages were +// flushed, then the test will never see the unflushed messages, causing +// some test logic to fail. +#define FINAL_WAIT_SECONDS 5 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/TestDarwinLogFilterMatchActivityChain.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/TestDarwinLogFilterMatchActivityChain.py new file mode 100644 index 00000000000..c1dfd15c6bd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/TestDarwinLogFilterMatchActivityChain.py @@ -0,0 +1,120 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterMatchActivityChain(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogFilterMatchActivityChain, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogFilterMatchActivityChain, self).tearDown() + + # ========================================================================== + # activity-chain filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_chain_match(self): + """Test that fall-through reject, accept full-match activity chain works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity-chain match " + "parent-activity:child-activity\""]) + + # We should only see the second log message as we only accept + # that activity. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_activity_chain_partial_match(self): + """Test that fall-through reject, doesn't accept only partial match of activity-chain.""" + self.do_test( + ["--no-match-accepts false", + # Match the second fully. + "--filter \"accept activity-chain match parent-activity:child-activity\"", + "--filter \"accept activity-chain match parent-ac\""]) # Only partially match the first. + + # We should only see the second log message as we only accept + # that activity. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_activity_chain_full_match(self): + """Test that fall-through accept, reject match activity-chain works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject activity-chain match parent-activity\""]) + + # We should only see the second log message as we rejected the first + # via activity-chain rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_chain_second_rule(self): + """Test that fall-through reject, accept activity-chain on second rule works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity-chain match non-existent\"", + "--filter \"accept activity-chain match parent-activity:child-activity\""]) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the activity-chain of the second log message. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/main.c new file mode 100644 index 00000000000..fbe5106b5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity-chain/main.c @@ -0,0 +1,42 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_activity_t parent_activity = os_activity_create("parent-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(parent_activity, ^{ + os_log(logger_sub1, "source-log-sub1-cat1"); + os_activity_t child_activity = os_activity_create("child-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(child_activity, ^{ + os_log(logger_sub2, "source-log-sub2-cat2"); + }); + }); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/TestDarwinLogFilterMatchActivity.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/TestDarwinLogFilterMatchActivity.py new file mode 100644 index 00000000000..f2587b1899a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/TestDarwinLogFilterMatchActivity.py @@ -0,0 +1,124 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterMatchActivity(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogFilterMatchActivity, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogFilterMatchActivity, self).tearDown() + + # ========================================================================== + # activity filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_match(self): + """Test that fall-through reject, accept match activity works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity match child-activity\""] + ) + + # We should only see the second log message as we only accept + # that activity. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_activity_partial_match(self): + """Test that fall-through reject, accept match activity via partial match does not accept.""" + self.do_test( + ["--no-match-accepts false", + # Fully match second message. + "--filter \"accept activity match child-activity\"", + "--filter \"accept activity match parent-\""] # Only partially match first message. + ) + + # We should only see the second log message as we only accept + # that activity. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_activity_full_match(self): + """Test that fall-through accept, reject match activity works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject activity match parent-activity\""] + ) + + # We should only see the second log message as we rejected the first + # via activity rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_second_rule(self): + """Test that fall-through reject, accept regex activity on second rule works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity match non-existent\"", + "--filter \"accept activity match child-activity\"" + ] + ) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the activity of the second log message. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/main.c new file mode 100644 index 00000000000..fbe5106b5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/activity/main.c @@ -0,0 +1,42 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_activity_t parent_activity = os_activity_create("parent-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(parent_activity, ^{ + os_log(logger_sub1, "source-log-sub1-cat1"); + os_activity_t child_activity = os_activity_create("child-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(child_activity, ^{ + os_log(logger_sub2, "source-log-sub2-cat2"); + }); + }); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/TestDarwinLogFilterMatchCategory.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/TestDarwinLogFilterMatchCategory.py new file mode 100644 index 00000000000..f65b6fc55a9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/TestDarwinLogFilterMatchCategory.py @@ -0,0 +1,124 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterMatchCategory(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogFilterMatchCategory, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogFilterMatchCategory, self).tearDown() + + # ========================================================================== + # category filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_filter_accept_category_full_match(self): + """Test that fall-through reject, accept match single category works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept category match cat2\""] + ) + + # We should only see the second log message as we only accept + # that category. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_category_partial_match(self): + """Test that fall-through reject, accept regex category via partial match works.""" + self.do_test( + ["--no-match-accepts false", + # Fully match the second message. + "--filter \"accept category match cat2\"", + "--filter \"accept category match at1\""] # Only partially match first message. Should not show up. + ) + + # We should only see the second log message as we only accept + # that category. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_category_full_match(self): + """Test that fall-through accept, reject match category works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject category match cat1\""] + ) + + # We should only see the second log message as we rejected the first + # via category rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_category_second_rule(self): + """Test that fall-through reject, accept match category on second rule works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept category match non-existent\"", + "--filter \"accept category match cat2\"" + ] + ) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the category of the second log message. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/main.c new file mode 100644 index 00000000000..fbe5106b5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/category/main.c @@ -0,0 +1,42 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_activity_t parent_activity = os_activity_create("parent-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(parent_activity, ^{ + os_log(logger_sub1, "source-log-sub1-cat1"); + os_activity_t child_activity = os_activity_create("child-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(child_activity, ^{ + os_log(logger_sub2, "source-log-sub2-cat2"); + }); + }); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/TestDarwinLogFilterMatchMessage.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/TestDarwinLogFilterMatchMessage.py new file mode 100644 index 00000000000..0d0378aee7b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/TestDarwinLogFilterMatchMessage.py @@ -0,0 +1,145 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb +import re + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterMatchMessage(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogFilterMatchMessage, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + self.strict_sources = True + + # Turn on process monitor logging while we work out issues. + self.enable_process_monitor_logging = True + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogFilterMatchMessage, self).tearDown() + + # ========================================================================== + # category filter tests + # ========================================================================== + + EXPECT_REGEXES = [ + re.compile(r"log message ([^-]+)-(\S+)"), + re.compile(r"exited with status") + ] + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(oslist=["macosx"], + bugnumber="llvm.org/pr30299") + def test_filter_accept_message_full_match(self): + """Test that fall-through reject, accept match whole message works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept message match log message sub2-cat2\""], + expect_regexes=self.EXPECT_REGEXES + ) + + # We should only see the second log message as we only accept + # that message contents. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(oslist=["macosx"], + bugnumber="llvm.org/pr30299") + def test_filter_no_accept_message_partial_match(self): + """Test that fall-through reject, match message via partial content match doesn't accept.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept message match log message sub2-cat2\"", + "--filter \"accept message match sub1-cat1\""], + expect_regexes=self.EXPECT_REGEXES + ) + + # We should only see the second log message as the partial match on + # the first message should not pass. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(oslist=["macosx"], + bugnumber="llvm.org/pr30299") + def test_filter_reject_category_full_match(self): + """Test that fall-through accept, reject match message works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject message match log message sub1-cat1\""], + expect_regexes=self.EXPECT_REGEXES + ) + + # We should only see the second log message as we rejected the first + # via message contents rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(oslist=["macosx"], + bugnumber="llvm.org/pr30299") + def test_filter_accept_category_second_rule(self): + """Test that fall-through reject, accept match category on second rule works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept message match non-existent\"", + "--filter \"accept message match log message sub2-cat2\""], + expect_regexes=self.EXPECT_REGEXES + ) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the category of the second log message. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/main.c new file mode 100644 index 00000000000..b4b26c158d3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/message/main.c @@ -0,0 +1,34 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_log(logger_sub1, "log message sub%d-cat%d", 1, 1); + os_log(logger_sub2, "log message sub%d-cat%d", 2, 2); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(1); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/TestDarwinLogFilterMatchSubsystem.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/TestDarwinLogFilterMatchSubsystem.py new file mode 100644 index 00000000000..6fd94fac0cb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/TestDarwinLogFilterMatchSubsystem.py @@ -0,0 +1,124 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterMatchSubsystem(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogFilterMatchSubsystem, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogFilterMatchSubsystem, self).tearDown() + + # ========================================================================== + # subsystem filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_filter_accept_subsystem_full_match(self): + """Test that fall-through reject, accept match single subsystem works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept subsystem match org.llvm.lldb.test.sub2\""] + ) + + # We should only see the second log message as we only accept + # that subsystem. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_subsystem_partial_match(self): + """Test that fall-through reject, doesn't accept match subsystem via partial-match.""" + self.do_test( + ["--no-match-accepts false", + # Fully match second message subsystem. + "--filter \"accept subsystem match org.llvm.lldb.test.sub2\"", + "--filter \"accept subsystem match sub1\""] # Only partially match first subsystem. + ) + + # We should only see the second log message as we only accept + # that subsystem. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_subsystem_full_match(self): + """Test that fall-through accept, reject match subsystem works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject subsystem match org.llvm.lldb.test.sub1\""] + ) + + # We should only see the second log message as we rejected the first + # via subsystem rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_subsystem_second_rule(self): + """Test that fall-through reject, accept match subsystem on second rule works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept subsystem match non-existent\"", + "--filter \"accept subsystem match org.llvm.lldb.test.sub2\"" + ] + ) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the subsystem of the second log message. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/main.c new file mode 100644 index 00000000000..fbe5106b5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/exact_match/subsystem/main.c @@ -0,0 +1,42 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_activity_t parent_activity = os_activity_create("parent-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(parent_activity, ^{ + os_log(logger_sub1, "source-log-sub1-cat1"); + os_activity_t child_activity = os_activity_create("child-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(child_activity, ^{ + os_log(logger_sub2, "source-log-sub2-cat2"); + }); + }); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/TestDarwinLogFilterRegexActivityChain.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/TestDarwinLogFilterRegexActivityChain.py new file mode 100644 index 00000000000..bec5a955f30 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/TestDarwinLogFilterRegexActivityChain.py @@ -0,0 +1,135 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterRegexActivityChain(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogFilterRegexActivityChain, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogFilterRegexActivityChain, self).tearDown() + + # ========================================================================== + # activity-chain filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_chain_full_match(self): + """Test that fall-through reject, accept full-match activity chain works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity-chain regex " + "parent-activity:child-activity\""]) + + # We should only see the second log message as we only accept + # that activity. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_chain_partial_match(self): + """Test that fall-through reject, accept activity-chain via partial match works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity-chain regex :child-activity\""]) + + # We should only see the second log message as we only accept + # that activity. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_activity_chain_full_match(self): + """Test that fall-through accept, reject activity-chain works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject activity-chain regex parent-activity:child-..tivity\""]) + + # We should only see the second log message as we rejected the first + # via activity-chain rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat1"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_activity_chain_partial_match(self): + """Test that fall-through accept, reject activity-chain by partial match works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject activity-chain regex ^p[^:]+$\""]) + + # We should only see the second log message as we rejected the first + # via activity-chain rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_chain_second_rule(self): + """Test that fall-through reject, accept activity-chain on second rule works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity-chain regex non-existent\"", + "--filter \"accept activity-chain regex child-activity\""]) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the activity-chain of the second log message. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/main.c new file mode 100644 index 00000000000..fbe5106b5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity-chain/main.c @@ -0,0 +1,42 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_activity_t parent_activity = os_activity_create("parent-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(parent_activity, ^{ + os_log(logger_sub1, "source-log-sub1-cat1"); + os_activity_t child_activity = os_activity_create("child-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(child_activity, ^{ + os_log(logger_sub2, "source-log-sub2-cat2"); + }); + }); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/TestDarwinLogFilterRegexActivity.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/TestDarwinLogFilterRegexActivity.py new file mode 100644 index 00000000000..4a4c6a21209 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/TestDarwinLogFilterRegexActivity.py @@ -0,0 +1,140 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterRegexActivity(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogFilterRegexActivity, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogFilterRegexActivity, self).tearDown() + + # ========================================================================== + # activity filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_full_match(self): + """Test that fall-through reject, accept regex full-match activity works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity regex child-activity\""] + ) + + # We should only see the second log message as we only accept + # that activity. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_partial_match(self): + """Test that fall-through reject, regex accept activity via partial match works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity regex child-.*\""] + ) + + # We should only see the second log message as we only accept + # that activity. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_activity_full_match(self): + """Test that fall-through accept, reject regex activity works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject activity regex parent-activity\""] + ) + + # We should only see the second log message as we rejected the first + # via activity rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_activity_partial_match(self): + """Test that fall-through accept, reject regex activity by partial match works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject activity regex p.+-activity\""] + ) + + # We should only see the second log message as we rejected the first + # via activity rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_activity_second_rule(self): + """Test that fall-through reject, accept regex activity on second rule works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept activity regex non-existent\"", + "--filter \"accept activity regex child-activity\"" + ] + ) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the activity of the second log message. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/main.c new file mode 100644 index 00000000000..fbe5106b5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/activity/main.c @@ -0,0 +1,42 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_activity_t parent_activity = os_activity_create("parent-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(parent_activity, ^{ + os_log(logger_sub1, "source-log-sub1-cat1"); + os_activity_t child_activity = os_activity_create("child-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(child_activity, ^{ + os_log(logger_sub2, "source-log-sub2-cat2"); + }); + }); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/TestDarwinLogFilterRegexCategory.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/TestDarwinLogFilterRegexCategory.py new file mode 100644 index 00000000000..96336093a74 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/TestDarwinLogFilterRegexCategory.py @@ -0,0 +1,140 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterRegexCategory(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogFilterRegexCategory, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogFilterRegexCategory, self).tearDown() + + # ========================================================================== + # category filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_filter_accept_category_full_match(self): + """Test that fall-through reject, accept regex single category works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept category regex cat2\""] + ) + + # We should only see the second log message as we only accept + # that category. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_category_partial_match(self): + """Test that fall-through reject, accept regex category via partial match works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept category regex .+2\""] + ) + + # We should only see the second log message as we only accept + # that category. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_category_full_match(self): + """Test that fall-through accept, reject regex category works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject category regex cat1\""] + ) + + # We should only see the second log message as we rejected the first + # via category rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_category_partial_match(self): + """Test that fall-through accept, reject regex category by partial match works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject category regex t1\""] + ) + + # We should only see the second log message as we rejected the first + # via category rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_category_second_rule(self): + """Test that fall-through reject, accept regex category on second rule works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept category regex non-existent\"", + "--filter \"accept category regex cat2\"" + ] + ) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the category of the second log message. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/main.c new file mode 100644 index 00000000000..fbe5106b5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/category/main.c @@ -0,0 +1,42 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_activity_t parent_activity = os_activity_create("parent-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(parent_activity, ^{ + os_log(logger_sub1, "source-log-sub1-cat1"); + os_activity_t child_activity = os_activity_create("child-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(child_activity, ^{ + os_log(logger_sub2, "source-log-sub2-cat2"); + }); + }); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/message/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/message/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/message/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/message/TestDarwinLogFilterRegexMessage.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/message/TestDarwinLogFilterRegexMessage.py new file mode 100644 index 00000000000..2cbdb4e3e80 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/message/TestDarwinLogFilterRegexMessage.py @@ -0,0 +1,126 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + +# System imports + + +# LLDB imports +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterRegexMessage(darwin_log.DarwinLogEventBasedTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(oslist=["macosx"], + bugnumber="llvm.org/pr30299") + def test_filter_accept_message_full_match(self): + """Test that fall-through reject, accept regex whole message works.""" + log_entries = self.do_test( + ["--no-match-accepts false", + # Note below, the four '\' characters are to get us two + # backslashes over on the gdb-remote side, which then + # becomes one as the cstr interprets it as an escape + # sequence. This needs to be rationalized. Initially I + # supported std::regex ECMAScript, which has the + # [[:digit:]] character classes and such. That was much + # more tenable. The backslashes have to travel through + # so many layers of escaping. (And note if you take + # off the Python raw string marker here, you need to put + # in 8 backslashes to go to two on the remote side.) + r'--filter "accept message regex log message sub2-cat\\\\d+"']) + + # We should have received at least one log entry. + self.assertIsNotNone(log_entries, + "Log entry list should not be None.") + self.assertEqual(len(log_entries), 1, + "Should receive one log entry.") + self.assertRegexpMatches(log_entries[0]["message"], r"sub2-cat2", + "First os_log call should have been skipped.") + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(oslist=["macosx"], + bugnumber="llvm.org/pr30299") + def test_filter_accept_message_partial_match(self): + """Test that fall-through reject, accept regex message via partial + match works.""" + log_entries = self.do_test( + ["--no-match-accepts false", + "--filter \"accept message regex [^-]+2\""]) + + # We should only see the second log message as we only accept + # that message contents. + self.assertIsNotNone(log_entries, + "Log entry list should not be None.") + self.assertEqual(len(log_entries), 1, + "Should receive one log entry.") + self.assertRegexpMatches(log_entries[0]["message"], r"sub2-cat2", + "First os_log call should have been skipped.") + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(oslist=["macosx"], + bugnumber="llvm.org/pr30299") + def test_filter_reject_message_full_match(self): + """Test that fall-through accept, reject regex message works.""" + log_entries = self.do_test( + ["--no-match-accepts true", + "--filter \"reject message regex log message sub1-cat1\""]) + + # We should only see the second log message as we rejected the first + # via message contents rejection. + self.assertIsNotNone(log_entries, + "Log entry list should not be None.") + self.assertEqual(len(log_entries), 1, + "Should receive one log entry.") + self.assertRegexpMatches(log_entries[0]["message"], r"sub2-cat2", + "First os_log call should have been skipped.") + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(oslist=["macosx"], + bugnumber="llvm.org/pr30299") + def test_filter_reject_message_partial_match(self): + """Test that fall-through accept, reject regex message by partial + match works.""" + log_entries = self.do_test( + ["--no-match-accepts true", + "--filter \"reject message regex t1\""]) + + # We should only see the second log message as we rejected the first + # via partial message contents rejection. + self.assertIsNotNone(log_entries, + "Log entry list should not be None.") + self.assertEqual(len(log_entries), 1, + "Should receive one log entry.") + self.assertRegexpMatches(log_entries[0]["message"], r"sub2-cat2", + "First os_log call should have been skipped.") + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(oslist=["macosx"], + bugnumber="llvm.org/pr30299") + def test_filter_accept_message_second_rule(self): + """Test that fall-through reject, accept regex message on second rule + works.""" + log_entries = self.do_test( + ["--no-match-accepts false", + "--filter \"accept message regex non-existent\"", + "--filter \"accept message regex cat2\""]) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the message of the second log message. + self.assertIsNotNone(log_entries, + "Log entry list should not be None.") + self.assertEqual(len(log_entries), 1, + "Should receive one log entry.") + self.assertRegexpMatches(log_entries[0]["message"], r"sub2-cat2", + "First os_log call should have been skipped.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/message/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/message/main.c new file mode 100644 index 00000000000..b0b43018746 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/message/main.c @@ -0,0 +1,34 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_log(logger_sub1, "log message sub%d-cat%d", 1, 1); + os_log(logger_sub2, "log message sub%d-cat%d", 2, 2); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/TestDarwinLogFilterRegexSubsystem.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/TestDarwinLogFilterRegexSubsystem.py new file mode 100644 index 00000000000..c5c4e98a8ee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/TestDarwinLogFilterRegexSubsystem.py @@ -0,0 +1,157 @@ +""" +Test basic DarwinLog functionality provided by the StructuredDataDarwinLog +plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogFilterRegexSubsystem(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogFilterRegexSubsystem, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogFilterRegexSubsystem, self).tearDown() + + # ========================================================================== + # basic filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_fallthrough_reject(self): + """Test that a single fall-through reject regex rule rejects all logging.""" + self.do_test( + ["--no-match-accepts false"] + ) + + # We should not match any log lines. + self.assertIsNotNone(self.child.match) + self.assertFalse((len(self.child.match.groups()) > 0) and + (self.child.match.group(1) in ["sub1", "sub2"]), + "log line should not have been received") + + # ========================================================================== + # subsystem filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_filter_accept_subsystem_full_match(self): + """Test that fall-through reject, accept regex single subsystem works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept subsystem regex org.llvm.lldb.test.sub2\""] + ) + + # We should only see the second log message as we only accept + # that subsystem. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_subsystem_partial_match(self): + """Test that fall-through reject, accept regex subsystem via partial-match works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept subsystem regex org.llvm.+.sub2\""] + ) + + # We should only see the second log message as we only accept + # that subsystem. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_subsystem_full_match(self): + """Test that fall-through accept, reject regex subsystem works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject subsystem regex org.llvm.lldb.test.sub1\""] + ) + + # We should only see the second log message as we rejected the first + # via subsystem rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_reject_subsystem_partial_match(self): + """Test that fall-through accept, reject regex subsystem by partial match works.""" + self.do_test( + ["--no-match-accepts true", + "--filter \"reject subsystem regex org.*sub1\""] + ) + + # We should only see the second log message as we rejected the first + # via subsystem rejection. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_filter_accept_subsystem_second_rule(self): + """Test that fall-through reject, accept regex subsystem on second rule works.""" + self.do_test( + ["--no-match-accepts false", + "--filter \"accept subsystem regex non-existent\"", + "--filter \"accept subsystem regex org.llvm.lldb.test.sub2\"" + ] + ) + + # We should only see the second message since we reject by default, + # the first filter doesn't match any, and the second filter matches + # the subsystem of the second log message. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 0) and ( + self.child.match.group(1) == "sub2"), + "first log line should not be present, second log line " + "should be") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/main.c new file mode 100644 index 00000000000..fbe5106b5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/filter/regex/subsystem/main.c @@ -0,0 +1,42 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_activity_t parent_activity = os_activity_create("parent-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(parent_activity, ^{ + os_log(logger_sub1, "source-log-sub1-cat1"); + os_activity_t child_activity = os_activity_create("child-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(child_activity, ^{ + os_log(logger_sub2, "source-log-sub2-cat2"); + }); + }); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/TestDarwinLogMessageFormat.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/TestDarwinLogMessageFormat.py new file mode 100644 index 00000000000..687340e5fd3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/TestDarwinLogMessageFormat.py @@ -0,0 +1,187 @@ +""" +Test DarwinLog log message formatting options provided by the +StructuredDataDarwinLog plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb +import re + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogMessageFormat(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogMessageFormat, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogMessageFormat, self).tearDown() + + # ========================================================================== + # Test settings around log message formatting + # ========================================================================== + + REGEXES = [ + re.compile(r"\[([^]]+)\] This is the log message."), # Match log + # with header. + re.compile(r"This is the log message."), # Match no-header content. + re.compile(r"exited with status") # Fallback if no log emitted. + ] + + @decorators.skipUnlessDarwin + def test_display_without_header_works(self): + """Test that turning off log message headers works as advertised.""" + self.do_test([], expect_regexes=self.REGEXES) + + # We should not match the first pattern as we shouldn't have header + # content. + self.assertIsNotNone(self.child.match) + self.assertFalse((len(self.child.match.groups()) > 0) and + (self.child.match.group(1) != ""), + "we should not have seen a header") + + @decorators.skipUnlessDarwin + def test_display_with_header_works(self): + """Test that displaying any header works.""" + self.do_test( + ["--timestamp-relative", "--subsystem", "--category", + "--activity-chain"], + expect_regexes=self.REGEXES, + settings_commands=[ + "display-header true" + ]) + + # We should match the first pattern as we should have header + # content. + self.assertIsNotNone(self.child.match) + self.assertTrue((len(self.child.match.groups()) > 0) and + (self.child.match.group(1) != ""), + "we should have printed a header") + + def assert_header_contains_timestamp(self, header): + fields = header.split(',') + self.assertGreater(len(fields), 0, + "there should have been header content present") + self.assertRegexpMatches(fields[0], + r"^\d+:\d{2}:\d{2}.\d{9}$", + "time field should match expected format") + + @decorators.skipUnlessDarwin + def test_header_timefield_only_works(self): + """Test that displaying a header with only the timestamp works.""" + self.do_test(["--timestamp-relative"], expect_regexes=self.REGEXES) + + # We should match the first pattern as we should have header + # content. + self.assertIsNotNone(self.child.match) + self.assertTrue((len(self.child.match.groups()) > 0) and + (self.child.match.group(1) != ""), + "we should have printed a header") + header = self.child.match.group(1) + self.assertEqual(len(header.split(',')), 1, + "there should only be one header field") + self.assert_header_contains_timestamp(header) + + @decorators.skipUnlessDarwin + def test_header_subsystem_only_works(self): + """Test that displaying a header with only the subsystem works.""" + self.do_test(["--subsystem"], expect_regexes=self.REGEXES) + + # We should match the first pattern as we should have header + # content. + self.assertIsNotNone(self.child.match) + self.assertTrue((len(self.child.match.groups()) > 0) and + (self.child.match.group(1) != ""), + "we should have printed a header") + header = self.child.match.group(1) + self.assertEqual(len(header.split(',')), 1, + "there should only be one header field") + self.assertEquals(header, + "subsystem=org.llvm.lldb.test.sub1") + + @decorators.skipUnlessDarwin + def test_header_category_only_works(self): + """Test that displaying a header with only the category works.""" + self.do_test(["--category"], expect_regexes=self.REGEXES) + + # We should match the first pattern as we should have header + # content. + self.assertIsNotNone(self.child.match) + self.assertTrue((len(self.child.match.groups()) > 0) and + (self.child.match.group(1) != ""), + "we should have printed a header") + header = self.child.match.group(1) + self.assertEqual(len(header.split(',')), 1, + "there should only be one header field") + self.assertEquals(header, + "category=cat1") + + @decorators.skipUnlessDarwin + def test_header_activity_chain_only_works(self): + """Test that displaying a header with only the activity chain works.""" + self.do_test(["--activity-chain"], expect_regexes=self.REGEXES) + + # We should match the first pattern as we should have header + # content. + self.assertIsNotNone(self.child.match) + self.assertTrue((len(self.child.match.groups()) > 0) and + (self.child.match.group(1) != ""), + "we should have printed a header") + header = self.child.match.group(1) + self.assertEqual(len(header.split(',')), 1, + "there should only be one header field") + self.assertEquals(header, + "activity-chain=parent-activity:child-activity") + + # @decorators.skipUnlessDarwin + # def test_header_activity_no_chain_only_works(self): + # """Test that displaying a header with only the activity works.""" + # self.do_test( + # [], + # expect_regexes=self.REGEXES, + # settings_commands=[ + # "display-header true", + # "format-include-timestamp false", + # "format-include-activity true", + # "format-include-category false", + # "format-include-subsystem false", + # "display-activity-chain false" + # ]) + + # # We should match the first pattern as we should have header + # # content. + # self.assertIsNotNone(self.child.match) + # self.assertTrue((len(self.child.match.groups()) > 0) and + # (self.child.match.group(1) != ""), + # "we should have printed a header") + # header = self.child.match.group(1) + # self.assertEqual(len(header.split(',')), 1, + # "there should only be one header field") + # self.assertEquals(header, + # "activity=child-activity") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/main.c new file mode 100644 index 00000000000..889a4e97856 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/format/main.c @@ -0,0 +1,40 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/activity.h> +#include <os/log.h> +#include <stdio.h> + +#include "../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + if (!logger_sub1) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_activity_t parent_activity = os_activity_create("parent-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(parent_activity, ^{ + os_activity_t child_activity = os_activity_create("child-activity", + OS_ACTIVITY_CURRENT, OS_ACTIVITY_FLAG_DEFAULT); + os_activity_apply(child_activity, ^{ + os_log(logger_sub1, "This is the log message."); + }); + }); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/TestDarwinLogSourceDebug.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/TestDarwinLogSourceDebug.py new file mode 100644 index 00000000000..57a02766683 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/TestDarwinLogSourceDebug.py @@ -0,0 +1,78 @@ +""" +Test DarwinLog "source include debug-level" functionality provided by the +StructuredDataDarwinLog plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogSourceDebug(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogSourceDebug, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + # Indicate we want strict-sources behavior. + self.strict_sources = True + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogSourceDebug, self).tearDown() + + # ========================================================================== + # source include/exclude debug filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + def test_source_default_exclude_debug(self): + """Test that default excluding of debug-level log messages works.""" + self.do_test([]) + + # We should only see the second log message as the first is a + # debug-level message and we're not including debug-level messages. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_source_explicitly_include_debug(self): + """Test that explicitly including debug-level log messages works.""" + self.do_test(["--debug"]) + + # We should only see the second log message as the first is a + # debug-level message and we're not including debug-level messages. + self.assertIsNotNone(self.child.match) + self.assertTrue((len(self.child.match.groups()) > 1) and + (self.child.match.group(2) == "cat1"), + "first log line should be present since we're " + "including debug-level log messages") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/main.c new file mode 100644 index 00000000000..b3af8cb3476 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/debug/main.c @@ -0,0 +1,33 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/log.h> +#include <stdio.h> + +#include "../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_log_debug(logger_sub1, "source-log-sub1-cat1"); + os_log(logger_sub2, "source-log-sub2-cat2"); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/TestDarwinLogSourceInfo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/TestDarwinLogSourceInfo.py new file mode 100644 index 00000000000..5a3eafa2e8c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/TestDarwinLogSourceInfo.py @@ -0,0 +1,81 @@ +""" +Test DarwinLog "source include info-level" functionality provided by the +StructuredDataDarwinLog plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb + +from lldbsuite.test import decorators +from lldbsuite.test import lldbtest +from lldbsuite.test import darwin_log + + +class TestDarwinLogSourceInfo(darwin_log.DarwinLogTestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + super(TestDarwinLogSourceInfo, self).setUp() + + # Source filename. + self.source = 'main.c' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = lldbtest.line_number(self.source, '// break here') + + # Indicate we want strict-sources behavior. + self.strict_sources = True + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(TestDarwinLogSourceInfo, self).tearDown() + + # ========================================================================== + # source include/exclude debug filter tests + # ========================================================================== + + @decorators.skipUnlessDarwin + @decorators.expectedFailureAll(bugnumber="rdar://27316264") + def test_source_exclude_info_level(self): + """Test that default excluding of info-level log messages works.""" + self.do_test([]) + + # We should only see the second log message as the first is an + # info-level message and we're not including debug-level messages. + self.assertIsNotNone(self.child.match) + self.assertTrue( + (len( + self.child.match.groups()) > 1) and ( + self.child.match.group(2) == "cat2"), + "first log line should not be present, second log line " + "should be") + + @decorators.skipUnlessDarwin + def test_source_include_info_level(self): + """Test that explicitly including info-level log messages works.""" + self.do_test( + ["--info"] + ) + + # We should only see the second log message as the first is a + # debug-level message and we're not including debug-level messages. + self.assertIsNotNone(self.child.match) + self.assertTrue((len(self.child.match.groups()) > 1) and + (self.child.match.group(2) == "cat1"), + "first log line should be present since we're " + "including info-level log messages") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/main.c new file mode 100644 index 00000000000..3472a9bc507 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/darwin_log/source/info/main.c @@ -0,0 +1,33 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <os/log.h> +#include <stdio.h> + +#include "../../common/darwin_log_common.h" + +int main(int argc, char** argv) +{ + os_log_t logger_sub1 = os_log_create("org.llvm.lldb.test.sub1", "cat1"); + os_log_t logger_sub2 = os_log_create("org.llvm.lldb.test.sub2", "cat2"); + if (!logger_sub1 || !logger_sub2) + return 1; + + // Note we cannot use the os_log() line as the breakpoint because, as of + // the initial writing of this test, we get multiple breakpoints for that + // line, which confuses the pexpect test logic. + printf("About to log\n"); // break here + os_log_info(logger_sub1, "source-log-sub1-cat1"); + os_log(logger_sub2, "source-log-sub2-cat2"); + + // Sleep, as the darwin log reporting doesn't always happen until a bit + // later. We need the message to come out before the process terminates. + sleep(FINAL_WAIT_SECONDS); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/.categories new file mode 100644 index 00000000000..fe1da0247c6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/.categories @@ -0,0 +1 @@ +dataformatters diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/array_typedef/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/array_typedef/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/array_typedef/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/array_typedef/TestArrayTypedef.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/array_typedef/TestArrayTypedef.py new file mode 100644 index 00000000000..1f2914ad633 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/array_typedef/TestArrayTypedef.py @@ -0,0 +1,15 @@ +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class ArrayTypedefTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_array_typedef(self): + self.build() + lldbutil.run_to_source_breakpoint(self, "// break here", + lldb.SBFileSpec("main.cpp", False)) + self.expect("expr str", substrs=['"abcd"']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/array_typedef/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/array_typedef/main.cpp new file mode 100644 index 00000000000..5c581b07ace --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/array_typedef/main.cpp @@ -0,0 +1,7 @@ +typedef char MCHAR; + +int main() { + MCHAR str[5] = "abcd"; + return 0; // break here +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/Makefile new file mode 100644 index 00000000000..876340159d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/Makefile @@ -0,0 +1,8 @@ +OBJCXX_SOURCES := main.mm + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py new file mode 100644 index 00000000000..25ecdef5948 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py @@ -0,0 +1,77 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DataFormatterBoolRefPtr(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_boolrefptr_with_run_command(self): + """Test the formatters we use for BOOL& and BOOL* in Objective-C.""" + self.build() + self.boolrefptr_data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.mm', '// Set break point at this line.') + + def boolrefptr_data_formatter_commands(self): + """Test the formatters we use for BOOL& and BOOL* in Objective-C.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + isiOS = (lldbplatformutil.getPlatform() == 'ios' or lldbplatformutil.getPlatform() == 'watchos') + + # Now check that we use the right summary for BOOL& + self.expect('frame variable yes_ref', + substrs=['YES']) + self.expect('frame variable no_ref', + substrs=['NO']) + if not(isiOS): + self.expect('frame variable unset_ref', substrs=['12']) + + # Now check that we use the right summary for BOOL* + self.expect('frame variable yes_ptr', + substrs=['YES']) + self.expect('frame variable no_ptr', + substrs=['NO']) + if not(isiOS): + self.expect('frame variable unset_ptr', substrs=['12']) + + # Now check that we use the right summary for BOOL + self.expect('frame variable yes', + substrs=['YES']) + self.expect('frame variable no', + substrs=['NO']) + if not(isiOS): + self.expect('frame variable unset', substrs=['12']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/main.mm new file mode 100644 index 00000000000..e63aa32394e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/main.mm @@ -0,0 +1,30 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +int main (int argc, const char * argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + BOOL yes = YES; + BOOL no = NO; + BOOL unset = 12; + + BOOL &yes_ref = yes; + BOOL &no_ref = no; + BOOL &unset_ref = unset; + + BOOL* yes_ptr = &yes; + BOOL* no_ptr = &no; + BOOL* unset_ptr = &unset; + + [pool drain];// Set break point at this line. + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/Makefile new file mode 100644 index 00000000000..a537b994079 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp +LD_EXTRAS := -framework Accelerate +include Makefile.rules + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py new file mode 100644 index 00000000000..17344283081 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py @@ -0,0 +1,60 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CompactVectorsFormattingTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @skipUnlessDarwin + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.expect( + 'frame variable', + substrs=[ + '(vFloat) valueFL = (1.25, 0, 0.25, 0)', + '(int16_t [8]) valueI16 = (1, 0, 4, 0, 0, 1, 0, 4)', + '(int32_t [4]) valueI32 = (1, 0, 4, 0)', + '(vDouble) valueDL = (1.25, 2.25)', + '(vUInt8) valueU8 = (0x01, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)', + '(vUInt16) valueU16 = (1, 0, 4, 0, 0, 1, 0, 4)', + '(vUInt32) valueU32 = (1, 2, 3, 4)', + "(vSInt8) valueS8 = (1, 0, 4, 0, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0)", + '(vSInt16) valueS16 = (1, 0, 4, 0, 0, 1, 0, 4)', + '(vSInt32) valueS32 = (4, 3, 2, 1)', + '(vBool32) valueBool32 = (0, 1, 0, 1)']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/main.cpp new file mode 100644 index 00000000000..f31d2a1a18a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/main.cpp @@ -0,0 +1,25 @@ + //===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <Accelerate/Accelerate.h> + +int main() +{ + vFloat valueFL = {1.25,0,0.25,0}; + vDouble valueDL = {1.25,2.25}; + int16_t valueI16[8] = {1,0,4,0,0,1,0,4}; + int32_t valueI32[4] = {1,0,4,0}; + vUInt8 valueU8 = {1,0,4,0,0,1,0,4}; + vUInt16 valueU16 = {1,0,4,0,0,1,0,4}; + vUInt32 valueU32 = {1,2,3,4}; + vSInt8 valueS8 = {1,0,4,0,0,1,0,4}; + vSInt16 valueS16 = {1,0,4,0,0,1,0,4}; + vSInt32 valueS32 = {4,3,2,1}; + vBool32 valueBool32 = {false,true,false,true}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py new file mode 100644 index 00000000000..246ebb3d4ae --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py @@ -0,0 +1,326 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class AdvDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("type summary add --summary-string \"pippo\" \"i_am_cool\"") + + self.runCmd( + "type summary add --summary-string \"pluto\" -x \"i_am_cool[a-z]*\"") + + self.expect("frame variable cool_boy", + substrs=['pippo']) + + self.expect("frame variable cooler_boy", + substrs=['pluto']) + + self.runCmd("type summary delete i_am_cool") + + self.expect("frame variable cool_boy", + substrs=['pluto']) + + self.runCmd("type summary clear") + + self.runCmd( + "type summary add --summary-string \"${var[]}\" -x \"int \\[[0-9]\\]") + + self.expect("frame variable int_array", + substrs=['1,2,3,4,5']) + + # this will fail if we don't do [] as regex correctly + self.runCmd( + 'type summary add --summary-string "${var[].integer}" "i_am_cool[]') + + self.expect("frame variable cool_array", + substrs=['1,1,1,1,6']) + + self.runCmd("type summary clear") + + self.runCmd( + "type summary add --summary-string \"${var[1-0]%x}\" \"int\"") + + self.expect("frame variable iAmInt", + substrs=['01']) + + self.runCmd( + "type summary add --summary-string \"${var[0-1]%x}\" \"int\"") + + self.expect("frame variable iAmInt", + substrs=['01']) + + self.runCmd("type summary clear") + + self.runCmd("type summary add --summary-string \"${var[0-1]%x}\" int") + self.runCmd( + "type summary add --summary-string \"${var[0-31]%x}\" float") + + self.expect("frame variable *pointer", + substrs=['0x', + '2']) + + # check fix for <rdar://problem/11338654> LLDB crashes when using a + # "type summary" that uses bitfields with no format + self.runCmd("type summary add --summary-string \"${var[0-1]}\" int") + self.expect("frame variable iAmInt", + substrs=['9 1']) + + self.expect("frame variable cool_array[3].floating", + substrs=['0x']) + + self.runCmd( + "type summary add --summary-string \"low bits are ${*var[0-1]} tgt is ${*var}\" \"int *\"") + + self.expect("frame variable pointer", + substrs=['low bits are', + 'tgt is 6']) + + self.expect( + "frame variable int_array --summary-string \"${*var[0-1]}\"", + substrs=['3']) + + self.runCmd("type summary clear") + + self.runCmd( + 'type summary add --summary-string \"${var[0-1]}\" -x \"int \[[0-9]\]\"') + + self.expect("frame variable int_array", + substrs=['1,2']) + + self.runCmd( + 'type summary add --summary-string \"${var[0-1]}\" "int []"') + + self.expect("frame variable int_array", + substrs=['1,2']) + + # Test the patterns are matched in reverse-chronological order. + self.runCmd( + 'type summary add --summary-string \"${var[2-3]}\" "int []"') + + self.expect("frame variable int_array", + substrs=['3,4']) + + self.runCmd("type summary clear") + + self.runCmd("type summary add -c -x \"i_am_cool \[[0-9]\]\"") + self.runCmd("type summary add -c i_am_cool") + + self.expect("frame variable cool_array", + substrs=['[0]', + '[1]', + '[2]', + '[3]', + '[4]', + 'integer', + 'character', + 'floating']) + + self.runCmd( + "type summary add --summary-string \"int = ${*var.int_pointer}, float = ${*var.float_pointer}\" IWrapPointers") + + self.expect("frame variable wrapper", + substrs=['int = 4', + 'float = 1.1']) + + self.runCmd( + "type summary add --summary-string \"low bits = ${*var.int_pointer[2]}\" IWrapPointers -p") + + self.expect("frame variable wrapper", + substrs=['low bits = 1']) + + self.expect("frame variable *wrap_pointer", + substrs=['low bits = 1']) + + self.runCmd("type summary clear") + + self.expect( + "frame variable int_array --summary-string \"${var[0][0-2]%hex}\"", + substrs=[ + '0x', + '7']) + + self.runCmd("type summary clear") + + self.runCmd( + "type summary add --summary-string \"${*var[].x[0-3]%hex} is a bitfield on a set of integers\" -x \"SimpleWithPointers \[[0-9]\]\"") + + self.expect( + "frame variable couple --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\"", + substrs=[ + '1 are low bits of integer 9.', + 'If I pretend it is an array I get [9,']) + + # if the summary has an error, we still display the value + self.expect( + "frame variable couple --summary-string \"${*var.sp.foo[0-2]\"", + substrs=[ + '(Couple) couple = {', + 'x = 0x', + 'y = 0x', + 'z = 0x', + 's = 0x']) + + self.runCmd( + "type summary add --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\" Couple") + + self.expect("frame variable sparray", + substrs=['[0x0000000f,0x0000000c,0x00000009]']) + + # check that we can format a variable in a summary even if a format is + # defined for its datatype + self.runCmd("type format add -f hex int") + self.runCmd( + "type summary add --summary-string \"x=${var.x%d}\" Simple") + + self.expect("frame variable a_simple_object", + substrs=['x=3']) + + self.expect("frame variable a_simple_object", matching=False, + substrs=['0x0']) + + # now check that the default is applied if we do not hand out a format + self.runCmd("type summary add --summary-string \"x=${var.x}\" Simple") + + self.expect("frame variable a_simple_object", matching=False, + substrs=['x=3']) + + self.expect("frame variable a_simple_object", matching=True, + substrs=['x=0x00000003']) + + # check that we can correctly cap the number of children shown + self.runCmd("settings set target.max-children-count 5") + + self.expect('frame variable a_long_guy', matching=True, + substrs=['a_1', + 'b_1', + 'c_1', + 'd_1', + 'e_1', + '...']) + + # check that no further stuff is printed (not ALL values are checked!) + self.expect('frame variable a_long_guy', matching=False, + substrs=['f_1', + 'g_1', + 'h_1', + 'i_1', + 'j_1', + 'q_1', + 'a_2', + 'f_2', + 't_2', + 'w_2']) + + self.runCmd("settings set target.max-children-count 1") + self.expect('frame variable a_long_guy', matching=True, + substrs=['a_1', + '...']) + self.expect('frame variable a_long_guy', matching=False, + substrs=['b_1', + 'c_1', + 'd_1', + 'e_1']) + self.expect('frame variable a_long_guy', matching=False, + substrs=['f_1', + 'g_1', + 'h_1', + 'i_1', + 'j_1', + 'q_1', + 'a_2', + 'f_2', + 't_2', + 'w_2']) + + self.runCmd("settings set target.max-children-count 30") + self.expect('frame variable a_long_guy', matching=True, + substrs=['a_1', + 'b_1', + 'c_1', + 'd_1', + 'e_1', + 'z_1', + 'a_2', + 'b_2', + 'c_2', + 'd_2', + '...']) + self.expect('frame variable a_long_guy', matching=False, + substrs=['e_2', + 'n_2', + 'r_2', + 'i_2', + 'k_2', + 'o_2']) + + # override the cap + self.expect( + 'frame variable a_long_guy --show-all-children', + matching=True, + substrs=[ + 'a_1', + 'b_1', + 'c_1', + 'd_1', + 'e_1', + 'z_1', + 'a_2', + 'b_2', + 'c_2', + 'd_2']) + self.expect( + 'frame variable a_long_guy --show-all-children', + matching=True, + substrs=[ + 'e_2', + 'n_2', + 'r_2', + 'i_2', + 'k_2', + 'o_2']) + self.expect( + 'frame variable a_long_guy --show-all-children', + matching=False, + substrs=['...']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/main.cpp new file mode 100644 index 00000000000..6eabbb3ae0f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/main.cpp @@ -0,0 +1,173 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> + +struct i_am_cool +{ + int integer; + float floating; + char character; + i_am_cool(int I, float F, char C) : + integer(I), floating(F), character(C) {} + i_am_cool() : integer(1), floating(2), character('3') {} + +}; + +struct i_am_cooler +{ + i_am_cool first_cool; + i_am_cool second_cool; + float floating; + + i_am_cooler(int I1, int I2, float F1, float F2, char C1, char C2) : + first_cool(I1,F1,C1), + second_cool(I2,F2,C2), + floating((F1 + F2)/2) {} +}; + +struct IWrapPointers +{ + int* int_pointer; + float* float_pointer; + IWrapPointers() : int_pointer(new int(4)), float_pointer(new float(1.111)) {} +}; + +struct Simple +{ + int x; + float y; + char z; + Simple(int X, float Y, char Z) : + x(X), + y(Y), + z(Z) + {} +}; + +struct SimpleWithPointers +{ + int *x; + float *y; + char *z; + SimpleWithPointers(int X, float Y, char Z) : + x(new int (X)), + y(new float (Y)), + z(new char[2]) + { + z[0] = Z; + z[1] = '\0'; + } +}; + +struct Couple +{ + SimpleWithPointers sp; + Simple* s; + Couple(int X, float Y, char Z) : sp(X,Y,Z), + s(new Simple(X,Y,Z)) {} +}; + +struct VeryLong +{ + int a_1; + int b_1; + int c_1; + int d_1; + int e_1; + int f_1; + int g_1; + int h_1; + int i_1; + int j_1; + int k_1; + int l_1; + int m_1; + int n_1; + int o_1; + int p_1; + int q_1; + int r_1; + int s_1; + int t_1; + int u_1; + int v_1; + int w_1; + int x_1; + int y_1; + int z_1; + + int a_2; + int b_2; + int c_2; + int d_2; + int e_2; + int f_2; + int g_2; + int h_2; + int i_2; + int j_2; + int k_2; + int l_2; + int m_2; + int n_2; + int o_2; + int p_2; + int q_2; + int r_2; + int s_2; + int t_2; + int u_2; + int v_2; + int w_2; + int x_2; + int y_2; + int z_2; +}; + +int main (int argc, const char * argv[]) +{ + + int iAmInt = 9; + + i_am_cool cool_boy(1,0.5,3); + i_am_cooler cooler_boy(1,2,0.1,0.2,'A','B'); + + i_am_cool *cool_pointer = new i_am_cool(3,-3.141592,'E'); + + i_am_cool cool_array[5]; + + cool_array[3].floating = 5.25; + cool_array[4].integer = 6; + cool_array[2].character = 'Q'; + + int int_array[] = {1,2,3,4,5}; + + IWrapPointers wrapper; + + *int_array = -1; + + int* pointer = &cool_array[4].integer; + + IWrapPointers *wrap_pointer = &wrapper; + + Couple couple(9,9.99,'X'); + + SimpleWithPointers sparray[] = + {SimpleWithPointers(-1,-2,'3'), + SimpleWithPointers(-4,-5,'6'), + SimpleWithPointers(-7,-8,'9')}; + + Simple a_simple_object(3,0.14,'E'); + + VeryLong a_long_guy; + + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/Makefile new file mode 100644 index 00000000000..224ecc3c2f5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := a.c b.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/TestDataFormatterCaching.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/TestDataFormatterCaching.py new file mode 100644 index 00000000000..881913b225b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/TestDataFormatterCaching.py @@ -0,0 +1,24 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil + + +class TestDataFormatterCaching(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """ + Test that hardcoded summary formatter matches aren't improperly cached. + """ + self.build() + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, 'break here', lldb.SBFileSpec('a.c')) + valobj = self.frame().FindVariable('f') + self.assertEqual(valobj.GetValue(), '4') + bkpt_b = target.BreakpointCreateBySourceRegex('break here', + lldb.SBFileSpec('b.c')) + lldbutil.continue_to_breakpoint(process, bkpt_b) + valobj = self.frame().FindVariable('f4') + self.assertEqual(valobj.GetSummary(), '(1, 2, 3, 4)') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/a.c new file mode 100644 index 00000000000..f2dde815518 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/a.c @@ -0,0 +1,9 @@ +typedef float float4; + +int a(); + +int main() { + float4 f = 4.0f; + // break here + return a(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/b.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/b.c new file mode 100644 index 00000000000..0d37c54aa33 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-caching/b.c @@ -0,0 +1,8 @@ +typedef float float4 __attribute__((ext_vector_type(4))); +void stop() {} +int a() { + float4 f4 = {1, 2, 3, 4}; + // break here + stop(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py new file mode 100644 index 00000000000..07f7a538b92 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py @@ -0,0 +1,355 @@ +""" +Test lldb data formatter subsystem. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CategoriesDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @expectedFlakeyNetBSD + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case (most of these categories do not + # exist anymore, but we just make sure we delete all of them) + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type category delete Category1', check=False) + self.runCmd('type category delete Category2', check=False) + self.runCmd('type category delete NewCategory', check=False) + self.runCmd("type category delete CircleCategory", check=False) + self.runCmd( + "type category delete RectangleStarCategory", + check=False) + self.runCmd("type category delete BaseCategory", check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Add a summary to a new category and check that it works + self.runCmd( + "type summary add Rectangle --summary-string \"ARectangle\" -w NewCategory") + + self.expect("frame variable r1 r2 r3", matching=False, + substrs=['r1 = ARectangle', + 'r2 = ARectangle', + 'r3 = ARectangle']) + + self.runCmd("type category enable NewCategory") + + self.expect("frame variable r1 r2 r3", matching=True, + substrs=['r1 = ARectangle', + 'r2 = ARectangle', + 'r3 = ARectangle']) + + # Disable the category and check that the old stuff is there + self.runCmd("type category disable NewCategory") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = {', + 'r2 = {', + 'r3 = {']) + + # Re-enable the category and check that it works + self.runCmd("type category enable NewCategory") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = ARectangle', + 'r2 = ARectangle', + 'r3 = ARectangle']) + + # Delete the category and the old stuff should be there + self.runCmd("type category delete NewCategory") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = {', + 'r2 = {', + 'r3 = {']) + + # Add summaries to two different categories and check that we can + # switch + self.runCmd( + "type summary add --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle -w Category1") + self.runCmd("type summary add --python-script \"return 'Area = ' + str( int(valobj.GetChildMemberWithName('w').GetValue()) * int(valobj.GetChildMemberWithName('h').GetValue()) );\" Rectangle -w Category2") + + # check that enable A B is the same as enable B enable A + self.runCmd("type category enable Category1 Category2") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) + + self.runCmd("type category disable Category1") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Area = ', + 'r2 = Area = ', + 'r3 = Area = ']) + + # switch again + + self.runCmd("type category enable Category1") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) + + # Re-enable the category and show that the preference is persisted + self.runCmd("type category disable Category2") + self.runCmd("type category enable Category2") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Area = ', + 'r2 = Area = ', + 'r3 = Area = ']) + + # Now delete the favorite summary + self.runCmd("type summary delete Rectangle -w Category2") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) + + # Delete the summary from the default category (that does not have it) + self.runCmd("type summary delete Rectangle", check=False) + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) + + # Now add another summary to another category and switch back and forth + self.runCmd("type category delete Category1 Category2") + + self.runCmd( + "type summary add Rectangle -w Category1 --summary-string \"Category1\"") + self.runCmd( + "type summary add Rectangle -w Category2 --summary-string \"Category2\"") + + self.runCmd("type category enable Category2") + self.runCmd("type category enable Category1") + + self.runCmd("type summary list -w Category1") + self.expect("type summary list -w NoSuchCategoryHere", + substrs=['no matching results found']) + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Category1', + 'r2 = Category1', + 'r3 = Category1']) + + self.runCmd("type category disable Category1") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Category2', + 'r2 = Category2', + 'r3 = Category2']) + + # Check that re-enabling an enabled category works + self.runCmd("type category enable Category1") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Category1', + 'r2 = Category1', + 'r3 = Category1']) + + self.runCmd("type category delete Category1") + self.runCmd("type category delete Category2") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = {', + 'r2 = {', + 'r3 = {']) + + # Check that multiple summaries can go into one category + self.runCmd( + "type summary add -w Category1 --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle") + self.runCmd( + "type summary add -w Category1 --summary-string \"Radius = ${var.r}\" Circle") + + self.runCmd("type category enable Category1") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) + + self.expect("frame variable c1 c2 c3", + substrs=['c1 = Radius = ', + 'c2 = Radius = ', + 'c3 = Radius = ']) + + self.runCmd("type summary delete Circle -w Category1") + + self.expect("frame variable c1 c2 c3", + substrs=['c1 = {', + 'c2 = {', + 'c3 = {']) + + # Add a regex based summary to a category + self.runCmd( + "type summary add -w Category1 --summary-string \"Radius = ${var.r}\" -x Circle") + + self.expect("frame variable r1 r2 r3", + substrs=['r1 = Width = ', + 'r2 = Width = ', + 'r3 = Width = ']) + + self.expect("frame variable c1 c2 c3", + substrs=['c1 = Radius = ', + 'c2 = Radius = ', + 'c3 = Radius = ']) + + # Delete it + self.runCmd("type summary delete Circle -w Category1") + + self.expect("frame variable c1 c2 c3", + substrs=['c1 = {', + 'c2 = {', + 'c3 = {']) + + # Change a summary inside a category and check that the change is + # reflected + self.runCmd( + "type summary add Circle -w Category1 --summary-string \"summary1\"") + + self.expect("frame variable c1 c2 c3", + substrs=['c1 = summary1', + 'c2 = summary1', + 'c3 = summary1']) + + self.runCmd( + "type summary add Circle -w Category1 --summary-string \"summary2\"") + + self.expect("frame variable c1 c2 c3", + substrs=['c1 = summary2', + 'c2 = summary2', + 'c3 = summary2']) + + # Check that our order of priority works. Start by clearing categories + self.runCmd("type category delete Category1") + + self.runCmd( + "type summary add Shape -w BaseCategory --summary-string \"AShape\"") + self.runCmd("type category enable BaseCategory") + + self.expect("print (Shape*)&c1", + substrs=['AShape']) + self.expect("print (Shape*)&r1", + substrs=['AShape']) + self.expect("print (Shape*)c_ptr", + substrs=['AShape']) + self.expect("print (Shape*)r_ptr", + substrs=['AShape']) + + self.runCmd( + "type summary add Circle -w CircleCategory --summary-string \"ACircle\"") + self.runCmd( + "type summary add Rectangle -w RectangleCategory --summary-string \"ARectangle\"") + self.runCmd("type category enable CircleCategory") + + self.expect("frame variable c1", + substrs=['ACircle']) + self.expect("frame variable c_ptr", + substrs=['ACircle']) + + self.runCmd( + "type summary add \"Rectangle *\" -w RectangleStarCategory --summary-string \"ARectangleStar\"") + self.runCmd("type category enable RectangleStarCategory") + + self.expect("frame variable c1 r1 c_ptr r_ptr", + substrs=['ACircle', + 'ARectangleStar']) + + self.runCmd("type category enable RectangleCategory") + + self.expect("frame variable c1 r1 c_ptr r_ptr", + substrs=['ACircle', + 'ACircle', + 'ARectangle']) + + # Check that abruptly deleting an enabled category does not crash us + self.runCmd("type category delete RectangleCategory") + + self.expect("frame variable c1 r1 c_ptr r_ptr", + substrs=['ACircle', + '(Rectangle) r1 = ', 'w = 5', 'h = 6', + 'ACircle', + 'ARectangleStar']) + + # check that list commands work + self.expect("type category list", + substrs=['RectangleStarCategory (enabled)']) + + self.expect("type summary list", + substrs=['ARectangleStar']) + + # Disable a category and check that it fallsback + self.runCmd("type category disable CircleCategory") + + # check that list commands work + self.expect("type category list", + substrs=['CircleCategory (disabled']) + + self.expect("frame variable c1 r_ptr", + substrs=['AShape', + 'ARectangleStar']) + + # check that filters work into categories + self.runCmd( + "type filter add Rectangle --child w --category RectangleCategory") + self.runCmd("type category enable RectangleCategory") + self.runCmd( + "type summary add Rectangle --category RectangleCategory --summary-string \" \" -e") + self.expect('frame variable r2', + substrs=['w = 9']) + self.runCmd("type summary add Rectangle --summary-string \" \" -e") + self.expect('frame variable r2', matching=False, + substrs=['h = 16']) + + # Now delete all categories + self.runCmd( + "type category delete CircleCategory RectangleStarCategory BaseCategory RectangleCategory") + + # check that a deleted category with filter does not blow us up + self.expect('frame variable r2', + substrs=['w = 9', + 'h = 16']) + + # and also validate that one can print formatters for a language + self.expect( + 'type summary list -l c++', + substrs=[ + 'vector', + 'map', + 'list', + 'string']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/main.cpp new file mode 100644 index 00000000000..e0e7c7ab9bd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/main.cpp @@ -0,0 +1,45 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> + +struct Shape +{ + bool dummy; + Shape() : dummy(true) {} +}; + +struct Rectangle : public Shape { + int w; + int h; + Rectangle(int W = 3, int H = 5) : w(W), h(H) {} +}; + +struct Circle : public Shape { + int r; + Circle(int R = 6) : r(R) {} +}; + +int main (int argc, const char * argv[]) +{ + Rectangle r1(5,6); + Rectangle r2(9,16); + Rectangle r3(4,4); + + Circle c1(5); + Circle c2(6); + Circle c3(7); + + Circle *c_ptr = new Circle(8); + Rectangle *r_ptr = new Rectangle(9,7); + + return 0; // Set break point at this line. +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py new file mode 100644 index 00000000000..733c427cdaa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py @@ -0,0 +1,294 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CppDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @skipIf(debug_info="gmodules", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=36048") + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("frame variable", + substrs=['(Speed) SPILookHex = 5.55' # Speed by default is 5.55. + ]) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("type format add -C yes -f x Speed BitField") + self.runCmd("type format add -C no -f c RealNumber") + self.runCmd("type format add -C no -f x Type2") + self.runCmd("type format add -C yes -f c Type1") + + # The type format list should show our custom formats. + self.expect("type format list", + substrs=['RealNumber', + 'Speed', + 'BitField', + 'Type1', + 'Type2']) + + self.expect("frame variable", + patterns=['\(Speed\) SPILookHex = 0x[0-9a-f]+' # Speed should look hex-ish now. + ]) + + # gcc4.2 on Mac OS X skips typedef chains in the DWARF output + if self.getCompiler() in ['clang', 'llvm-gcc']: + self.expect("frame variable", + patterns=['\(SignalMask\) SMILookHex = 0x[0-9a-f]+' # SignalMask should look hex-ish now. + ]) + self.expect("frame variable", matching=False, + patterns=['\(Type4\) T4ILookChar = 0x[0-9a-f]+' # Type4 should NOT look hex-ish now. + ]) + + # Now let's delete the 'Speed' custom format. + self.runCmd("type format delete Speed") + + # The type format list should not show 'Speed' at this point. + self.expect("type format list", matching=False, + substrs=['Speed']) + + # Delete type format for 'Speed', we should expect an error message. + self.expect("type format delete Speed", error=True, + substrs=['no custom formatter for Speed']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\" -v") + + self.expect("frame variable strarr", + substrs=['arr = "Hello world!"']) + + self.runCmd("type summary clear") + + self.runCmd( + "type summary add --summary-string \"ptr = ${var%s}\" \"char *\" -v") + + self.expect("frame variable strptr", + substrs=['ptr = "Hello world!"']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\" -v") + + self.expect("frame variable strarr", + substrs=['arr = "Hello world!']) + + # check that rdar://problem/10011145 (Standard summary format for + # char[] doesn't work as the result of "expr".) is solved + self.expect("p strarr", + substrs=['arr = "Hello world!']) + + self.expect("frame variable strptr", + substrs=['ptr = "Hello world!"']) + + self.expect("p strptr", + substrs=['ptr = "Hello world!"']) + + self.expect( + "p (char*)\"1234567890123456789012345678901234567890123456789012345678901234ABC\"", + substrs=[ + '(char *) $', + ' = ptr = ', + ' "1234567890123456789012345678901234567890123456789012345678901234ABC"']) + + self.runCmd("type summary add -c Point") + + self.expect("frame variable iAmSomewhere", + substrs=['x = 4', + 'y = 6']) + + self.expect("type summary list", + substrs=['Point', + 'one-line']) + + self.runCmd("type summary add --summary-string \"y=${var.y%x}\" Point") + + self.expect("frame variable iAmSomewhere", + substrs=['y=0x']) + + self.runCmd( + "type summary add --summary-string \"y=${var.y},x=${var.x}\" Point") + + self.expect("frame variable iAmSomewhere", + substrs=['y=6', + 'x=4']) + + self.runCmd("type summary add --summary-string \"hello\" Point -e") + + self.expect("type summary list", + substrs=['Point', + 'show children']) + + self.expect("frame variable iAmSomewhere", + substrs=['hello', + 'x = 4', + '}']) + + self.runCmd( + "type summary add --summary-string \"Sign: ${var[31]%B} Exponent: ${var[23-30]%x} Mantissa: ${var[0-22]%u}\" ShowMyGuts") + + self.expect("frame variable cool_pointer->floating", + substrs=['Sign: true', + 'Exponent: 0x', + '80']) + + self.runCmd("type summary add --summary-string \"a test\" i_am_cool") + + self.expect("frame variable cool_pointer", + substrs=['a test']) + + self.runCmd( + "type summary add --summary-string \"a test\" i_am_cool --skip-pointers") + + self.expect("frame variable cool_pointer", + substrs=['a test'], + matching=False) + + self.runCmd( + "type summary add --summary-string \"${var[1-3]}\" \"int [5]\"") + + self.expect("frame variable int_array", + substrs=['2', + '3', + '4']) + + self.runCmd("type summary clear") + + self.runCmd( + "type summary add --summary-string \"${var[0-2].integer}\" \"i_am_cool *\"") + self.runCmd( + "type summary add --summary-string \"${var[2-4].integer}\" \"i_am_cool [5]\"") + + self.expect("frame variable cool_array", + substrs=['1,1,6']) + + self.expect("frame variable cool_pointer", + substrs=['3,0,0']) + + # test special symbols for formatting variables into summaries + self.runCmd( + "type summary add --summary-string \"cool object @ ${var%L}\" i_am_cool") + self.runCmd("type summary delete \"i_am_cool [5]\"") + + # this test might fail if the compiler tries to store + # these values into registers.. hopefully this is not + # going to be the case + self.expect("frame variable cool_array", + substrs=['[0] = cool object @ 0x', + '[1] = cool object @ 0x', + '[2] = cool object @ 0x', + '[3] = cool object @ 0x', + '[4] = cool object @ 0x']) + + # test getting similar output by exploiting ${var} = 'type @ location' + # for aggregates + self.runCmd("type summary add --summary-string \"${var}\" i_am_cool") + + # this test might fail if the compiler tries to store + # these values into registers.. hopefully this is not + # going to be the case + self.expect("frame variable cool_array", + substrs=['[0] = i_am_cool @ 0x', + '[1] = i_am_cool @ 0x', + '[2] = i_am_cool @ 0x', + '[3] = i_am_cool @ 0x', + '[4] = i_am_cool @ 0x']) + + # test getting same output by exploiting %T and %L together for + # aggregates + self.runCmd( + "type summary add --summary-string \"${var%T} @ ${var%L}\" i_am_cool") + + # this test might fail if the compiler tries to store + # these values into registers.. hopefully this is not + # going to be the case + self.expect("frame variable cool_array", + substrs=['[0] = i_am_cool @ 0x', + '[1] = i_am_cool @ 0x', + '[2] = i_am_cool @ 0x', + '[3] = i_am_cool @ 0x', + '[4] = i_am_cool @ 0x']) + + self.runCmd("type summary add --summary-string \"goofy\" i_am_cool") + self.runCmd( + "type summary add --summary-string \"${var.second_cool%S}\" i_am_cooler") + + self.expect("frame variable the_coolest_guy", + substrs=['(i_am_cooler) the_coolest_guy = goofy']) + + # check that unwanted type specifiers are removed + self.runCmd("type summary delete i_am_cool") + self.runCmd( + "type summary add --summary-string \"goofy\" \"class i_am_cool\"") + self.expect("frame variable the_coolest_guy", + substrs=['(i_am_cooler) the_coolest_guy = goofy']) + + self.runCmd("type summary delete i_am_cool") + self.runCmd( + "type summary add --summary-string \"goofy\" \"enum i_am_cool\"") + self.expect("frame variable the_coolest_guy", + substrs=['(i_am_cooler) the_coolest_guy = goofy']) + + self.runCmd("type summary delete i_am_cool") + self.runCmd( + "type summary add --summary-string \"goofy\" \"struct i_am_cool\"") + self.expect("frame variable the_coolest_guy", + substrs=['(i_am_cooler) the_coolest_guy = goofy']) + + # many spaces, but we still do the right thing + self.runCmd("type summary delete i_am_cool") + self.runCmd( + "type summary add --summary-string \"goofy\" \"union i_am_cool\"") + self.expect("frame variable the_coolest_guy", + substrs=['(i_am_cooler) the_coolest_guy = goofy']) + + # but that not *every* specifier is removed + self.runCmd("type summary delete i_am_cool") + self.runCmd( + "type summary add --summary-string \"goofy\" \"wrong i_am_cool\"") + self.expect("frame variable the_coolest_guy", matching=False, + substrs=['(i_am_cooler) the_coolest_guy = goofy']) + + # check that formats are not sticking since that is the behavior we + # want + self.expect("frame variable iAmInt --format hex", + substrs=['(int) iAmInt = 0x00000001']) + self.expect( + "frame variable iAmInt", + matching=False, + substrs=['(int) iAmInt = 0x00000001']) + self.expect("frame variable iAmInt", substrs=['(int) iAmInt = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/main.cpp new file mode 100644 index 00000000000..c591313de88 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/main.cpp @@ -0,0 +1,120 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> + +typedef float RealNumber; // should show as char +typedef RealNumber Temperature; // should show as float +typedef RealNumber Speed; // should show as hex + +typedef int Counter; // should show as int +typedef int BitField; // should show as hex + +typedef BitField SignalMask; // should show as hex +typedef BitField Modifiers; // should show as hex + +typedef Counter Accumulator; // should show as int + +typedef int Type1; // should show as char +typedef Type1 Type2; // should show as hex +typedef Type2 Type3; // should show as char +typedef Type3 Type4; // should show as char + +typedef int ChildType; // should show as int +typedef int AnotherChildType; // should show as int + +struct Point { + int x; + int y; + Point(int X = 3, int Y = 2) : x(X), y(Y) {} +}; + +typedef float ShowMyGuts; + +struct i_am_cool +{ + int integer; + ShowMyGuts floating; + char character; + i_am_cool(int I, ShowMyGuts F, char C) : + integer(I), floating(F), character(C) {} + i_am_cool() : integer(1), floating(2), character('3') {} + +}; + +struct i_am_cooler +{ + i_am_cool first_cool; + i_am_cool second_cool; + ShowMyGuts floating; + + i_am_cooler(int I1, int I2, float F1, float F2, char C1, char C2) : + first_cool(I1,F1,C1), + second_cool(I2,F2,C2), + floating((F1 + F2)/2) {} +}; + +struct IUseCharStar +{ + const char* pointer; + IUseCharStar() : pointer("Hello world") {} +}; + +int main (int argc, const char * argv[]) +{ + + int iAmInt = 1; + const float& IAmFloat = float(2.45); + + RealNumber RNILookChar = 3.14; + Temperature TMILookFloat = 4.97; + Speed SPILookHex = 5.55; + + Counter CTILookInt = 6; + BitField BFILookHex = 7; + SignalMask SMILookHex = 8; + Modifiers MFILookHex = 9; + + Accumulator* ACILookInt = new Accumulator(10); + + const Type1& T1ILookChar = 11; + Type2 T2ILookHex = 12; + Type3 T3ILookChar = 13; + Type4 T4ILookChar = 14; + + AnotherChildType AHILookInt = 15; + + Speed* SPPtrILookHex = new Speed(16); + + Point iAmSomewhere(4,6); + + i_am_cool *cool_pointer = (i_am_cool*)malloc(sizeof(i_am_cool)*3); + cool_pointer[0] = i_am_cool(3,-3.141592,'E'); + cool_pointer[1] = i_am_cool(0,-3.141592,'E'); + cool_pointer[2] = i_am_cool(0,-3.141592,'E'); + + i_am_cool cool_array[5]; + + cool_array[3].floating = 5.25; + cool_array[4].integer = 6; + cool_array[2].character = 'Q'; + + int int_array[] = {1,2,3,4,5}; + + IUseCharStar iEncapsulateCharStar; + + char strarr[32] = "Hello world!"; + char* strptr = "Hello world!"; + + i_am_cooler the_coolest_guy(1,2,3.14,6.28,'E','G'); + + return 0; // Set break point at this line. +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py new file mode 100644 index 00000000000..3df6027fdb3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py @@ -0,0 +1,88 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DataFormatterDisablingTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") + def test_with_run_command(self): + """Check that we can properly disable all data formatter categories.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type category enable *', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + #self.runCmd('type category enable system VectorTypes libcxx gnu-libstdc++ CoreGraphics CoreServices AppKit CoreFoundation objc default', check=False) + + self.expect('type category list', substrs=['system', 'enabled', ]) + + self.expect("frame variable numbers", + substrs=['[0] = 1', '[3] = 1234']) + + self.expect('frame variable string1', substrs=['hello world']) + + # now disable them all and check that nothing is formatted + self.runCmd('type category disable *') + + self.expect("frame variable numbers", matching=False, + substrs=['[0] = 1', '[3] = 1234']) + + self.expect( + 'frame variable string1', + matching=False, + substrs=['hello world']) + + self.expect('type summary list', substrs=[ + 'Category: system (disabled)']) + + self.expect('type category list', substrs=['system', 'disabled', ]) + + # now enable and check that we are back to normal + self.runCmd("type category enable *") + + self.expect('type category list', substrs=['system', 'enabled']) + + self.expect("frame variable numbers", + substrs=['[0] = 1', '[3] = 1234']) + + self.expect('frame variable string1', substrs=['hello world']) + + self.expect('type category list', substrs=['system', 'enabled']) + + # last check - our cleanup will re-enable everything + self.runCmd('type category disable *') + self.expect('type category list', substrs=['system', 'disabled']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/main.cpp new file mode 100644 index 00000000000..9374642fb0d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/main.cpp @@ -0,0 +1,18 @@ +#include <vector> + +int main() +{ + + const char* string1 = "hello world"; + + std::vector<int> numbers; + numbers.push_back(1); + numbers.push_back(12); + numbers.push_back(123); + numbers.push_back(1234); + numbers.push_back(12345); + numbers.push_back(123456); + numbers.push_back(1234567); // Set break point at this line. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py new file mode 100644 index 00000000000..ca57442e452 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py @@ -0,0 +1,64 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class EnumFormatTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("frame variable", + substrs=['(Foo) f = Case45', + '(int) x = 1', + '(int) y = 45', + '(int) z = 43' + ]) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("type format add --type Foo int") + + # The type format list should show our custom formats. + self.expect("type format list -w default", + substrs=['int: as type Foo']) + + self.expect("frame variable", + substrs=['(Foo) f = Case45', + '(int) x = Case1', + '(int) y = Case45', + '(int) z = 43' + ]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/main.cpp new file mode 100644 index 00000000000..6a8074ff9fb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/main.cpp @@ -0,0 +1,13 @@ +enum Foo { + Case1 = 1, + Case2 = 2, + Case45 = 45 +}; + +int main() { + Foo f = Case45; + int x = 1; + int y = 45; + int z = 43; + return 1; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py new file mode 100644 index 00000000000..72fe2fb1885 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py @@ -0,0 +1,71 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil + + +class GlobalsDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @skipIf(debug_info="gmodules", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=36048") + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("type summary add --summary-string \"JustATest\" Point") + + # Simply check we can get at global variables + self.expect("target variable g_point", + substrs=['JustATest']) + + self.expect("target variable g_point_pointer", + substrs=['(Point *) g_point_pointer =']) + + # Print some information about the variables + # (we ignore the actual values) + self.runCmd( + "type summary add --summary-string \"(x=${var.x},y=${var.y})\" Point") + + self.expect("target variable g_point", + substrs=['x=', + 'y=']) + + self.expect("target variable g_point_pointer", + substrs=['(Point *) g_point_pointer =']) + + # Test Python code on resulting SBValue + self.runCmd( + "type summary add --python-script \"return 'x=' + str(valobj.GetChildMemberWithName('x').GetValue());\" Point") + + self.expect("target variable g_point", + substrs=['x=']) + + self.expect("target variable g_point_pointer", + substrs=['(Point *) g_point_pointer =']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/main.cpp new file mode 100644 index 00000000000..0f922b31352 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/main.cpp @@ -0,0 +1,26 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> + +struct Point { + int x; + int y; + Point(int X = 3, int Y = 2) : x(X), y(Y) {} +}; + +Point g_point(3,4); +Point* g_point_pointer = new Point(7,5); + +int main (int argc, const char * argv[]) +{ + return 0; // Set break point at this line. +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py new file mode 100644 index 00000000000..4e4c196c298 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py @@ -0,0 +1,130 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class NamedSummariesDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd( + "type summary add --summary-string \"AllUseIt: x=${var.x} {y=${var.y}} {z=${var.z}}\" --name AllUseIt") + self.runCmd( + "type summary add --summary-string \"First: x=${var.x} y=${var.y} dummy=${var.dummy}\" First") + self.runCmd( + "type summary add --summary-string \"Second: x=${var.x} y=${var.y%hex}\" Second") + self.runCmd( + "type summary add --summary-string \"Third: x=${var.x} z=${var.z}\" Third") + + self.expect('type summary list', substrs=['AllUseIt']) + + self.expect("frame variable first", + substrs=['First: x=12']) + + self.expect("frame variable first --summary AllUseIt", + substrs=['AllUseIt: x=12']) + + # We *DO NOT* remember the summary choice anymore + self.expect("frame variable first", matching=False, + substrs=['AllUseIt: x=12']) + self.expect("frame variable first", + substrs=['First: x=12']) + + self.runCmd("thread step-over") # 2 + + self.expect("frame variable first", + substrs=['First: x=12']) + + self.expect("frame variable first --summary AllUseIt", + substrs=['AllUseIt: x=12', + 'y=34']) + + self.expect("frame variable second --summary AllUseIt", + substrs=['AllUseIt: x=65', + 'y=43.25']) + + self.expect("frame variable third --summary AllUseIt", + substrs=['AllUseIt: x=96', + 'z=', + 'E']) + + self.runCmd("thread step-over") # 3 + + self.expect("frame variable second", + substrs=['Second: x=65', + 'y=0x']) + + # <rdar://problem/11576143> decided that invalid summaries will raise an error + # instead of just defaulting to the base summary + self.expect( + "frame variable second --summary NoSuchSummary", + error=True, + substrs=['must specify a valid named summary']) + + self.runCmd("thread step-over") + + self.runCmd( + "type summary add --summary-string \"FirstAndFriends: x=${var.x} {y=${var.y}} {z=${var.z}}\" First --name FirstAndFriends") + + self.expect("frame variable first", + substrs=['FirstAndFriends: x=12', + 'y=34']) + + self.runCmd("type summary delete First") + + self.expect("frame variable first --summary FirstAndFriends", + substrs=['FirstAndFriends: x=12', + 'y=34']) + + self.expect("frame variable first", matching=True, + substrs=['x = 12', + 'y = 34']) + + self.runCmd("type summary delete FirstAndFriends") + self.expect("type summary delete NoSuchSummary", error=True) + self.runCmd("type summary delete AllUseIt") + + self.expect("frame variable first", matching=False, + substrs=['FirstAndFriends']) + + self.runCmd("thread step-over") # 4 + + self.expect("frame variable first", matching=False, + substrs=['FirstAndFriends: x=12', + 'y=34']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/main.cpp new file mode 100644 index 00000000000..62ff7b22777 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/main.cpp @@ -0,0 +1,58 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> + +struct First +{ + int x; + int y; + float dummy; + First(int X, int Y) : + x(X), + y(Y), + dummy(3.14) + {} +}; + +struct Second +{ + int x; + float y; + Second(int X, float Y) : + x(X), + y(Y) + {} +}; + +struct Third +{ + int x; + char z; + Third(int X, char Z) : + x(X), + z(Z) + {} +}; + +int main (int argc, const char * argv[]) +{ + First first(12,34); + Second second(65,43.25); + Third *third = new Third(96,'E'); + + first.dummy = 1; // Set break point at this line. + first.dummy = 2; + first.dummy = 3; + first.dummy = 4; + first.dummy = 5; + +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/.categories new file mode 100644 index 00000000000..72cf07c1efe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/.categories @@ -0,0 +1 @@ +objc diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/Makefile new file mode 100644 index 00000000000..8b322ff320b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/Makefile @@ -0,0 +1,8 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/ObjCDataFormatterTestCase.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/ObjCDataFormatterTestCase.py new file mode 100644 index 00000000000..c31af352037 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/ObjCDataFormatterTestCase.py @@ -0,0 +1,42 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def appkit_tester_impl(self, commands): + self.build() + self.appkit_common_data_formatters_command() + commands() + + def appkit_common_data_formatters_command(self): + """Test formatters for AppKit classes.""" + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Set break point at this line.', + lldb.SBFileSpec('main.m', False)) + + # The stop reason of the thread should be breakpoint. + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCCF.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCCF.py new file mode 100644 index 00000000000..8671146b649 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCCF.py @@ -0,0 +1,59 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterCF(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_coreframeworks_and_run_command(self): + """Test formatters for Core OSX frameworks.""" + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Set break point at this line.', + lldb.SBFileSpec('main.m', False)) + + # The stop reason of the thread should be breakpoint. + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # check formatters for common Objective-C types + expect_strings = [ + '(CFGregorianUnits) cf_greg_units = 1 years, 3 months, 5 days, 12 hours, 5 minutes 7 seconds', + '(CFRange) cf_range = location=4 length=4', + '(NSPoint) ns_point = (x = 4, y = 4)', + '(NSRange) ns_range = location=4, length=4', + '(NSRect) ns_rect = (origin = (x = 1, y = 1), size = (width = 5, height = 5))', + '(NSRectArray) ns_rect_arr = ((x = 1, y = 1), (width = 5, height = 5)), ...', + '(NSSize) ns_size = (width = 5, height = 7)', + '(CGSize) cg_size = (width = 1, height = 6)', + '(CGPoint) cg_point = (x = 2, y = 7)', + '(CGRect) cg_rect = (origin = (x = 1, y = 2), size = (width = 7, height = 7))', + '(Rect) rect = (t=4, l=8, b=4, r=7)', + '(Rect *) rect_ptr = (t=4, l=8, b=4, r=7)', + '(Point) point = (v=7, h=12)', '(Point *) point_ptr = (v=7, h=12)', + '1985', 'foo_selector_impl' + ] + + if self.getArchitecture() in ['i386', 'x86_64']: + expect_strings.append('(HIPoint) hi_point = (x=7, y=12)') + expect_strings.append( + '(HIRect) hi_rect = origin=(x = 3, y = 5) size=(width = 4, height = 6)' + ) + expect_strings.append( + '(RGBColor) rgb_color = red=3 green=56 blue=35') + expect_strings.append( + '(RGBColor *) rgb_color_ptr = red=3 green=56 blue=35') + + self.expect("frame variable", substrs=expect_strings) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCExpr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCExpr.py new file mode 100644 index 00000000000..d27f0b93202 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCExpr.py @@ -0,0 +1,64 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterExpr(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_expr_with_run_command(self): + """Test common cases of expression parser <--> formatters interaction.""" + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Set break point at this line.', + lldb.SBFileSpec('main.m', False)) + + # The stop reason of the thread should be breakpoint. + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # check that the formatters are able to deal safely and correctly + # with ValueObjects that the expression parser returns + self.expect( + 'expression ((id)@"Hello for long enough to avoid short string types")', + matching=False, + substrs=['Hello for long enough to avoid short string types']) + + self.expect( + 'expression -d run -- ((id)@"Hello for long enough to avoid short string types")', + substrs=['Hello for long enough to avoid short string types']) + + self.expect('expr -d run -- label1', substrs=['Process Name']) + + self.expect( + 'expr -d run -- @"Hello for long enough to avoid short string types"', + substrs=['Hello for long enough to avoid short string types']) + + self.expect( + 'expr -d run --object-description -- @"Hello for long enough to avoid short string types"', + substrs=['Hello for long enough to avoid short string types']) + self.expect( + 'expr -d run --object-description -- @"Hello"', + matching=False, + substrs=['@"Hello" Hello']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCKVO.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCKVO.py new file mode 100644 index 00000000000..fae51ffd038 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCKVO.py @@ -0,0 +1,63 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterKVO(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_kvo_with_run_command(self): + """Test the behavior of formatters when KVO is in use.""" + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Set break point at this line.', + lldb.SBFileSpec('main.m', False)) + + # The stop reason of the thread should be breakpoint. + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # as long as KVO is implemented by subclassing, this test should succeed + # we should be able to dynamically figure out that the KVO implementor class + # is a subclass of Molecule, and use the appropriate summary for it + self.runCmd("type summary add -s JustAMoleculeHere Molecule") + self.expect('frame variable molecule', substrs=['JustAMoleculeHere']) + self.runCmd("next") + self.expect("thread list", substrs=['stopped', 'step over']) + self.expect('frame variable molecule', substrs=['JustAMoleculeHere']) + + self.runCmd("next") + # check that NSMutableDictionary's formatter is not confused when + # dealing with a KVO'd dictionary + self.expect( + 'frame variable newMutableDictionary', + substrs=[ + '(NSDictionary *) newMutableDictionary = ', + ' 21 key/value pairs' + ]) + + lldbutil.run_break_set_by_regexp(self, 'setAtoms') + + self.runCmd("continue") + self.expect("frame variable _cmd", substrs=['setAtoms:']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSBundle.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSBundle.py new file mode 100644 index 00000000000..40acc19a5da --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSBundle.py @@ -0,0 +1,31 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterNSBundle(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_nsbundle_with_run_command(self): + """Test formatters for NSBundle.""" + self.appkit_tester_impl(self.nsbundle_data_formatter_commands) + + def nsbundle_data_formatter_commands(self): + self.expect( + 'frame variable bundle_string bundle_url main_bundle', + substrs=[ + '(NSBundle *) bundle_string = ', + ' @"/System/Library/Frameworks/Accelerate.framework"', + '(NSBundle *) bundle_url = ', + ' @"/System/Library/Frameworks/Foundation.framework"', + '(NSBundle *) main_bundle = ', 'data-formatter-objc' + ]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSContainer.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSContainer.py new file mode 100644 index 00000000000..2bd22ff3abd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSContainer.py @@ -0,0 +1,46 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterNSContainer(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_nscontainers_with_run_command(self): + """Test formatters for NS container classes.""" + self.appkit_tester_impl(self.nscontainers_data_formatter_commands) + + def nscontainers_data_formatter_commands(self): + self.expect( + 'frame variable newArray nsDictionary newDictionary nscfDictionary cfDictionaryRef newMutableDictionary cfarray_ref mutable_array_ref', + substrs=[ + '(NSArray *) newArray = ', '@"50 elements"', + '(NSDictionary *) newDictionary = ', ' 12 key/value pairs', + '(NSDictionary *) newMutableDictionary = ', + ' 21 key/value pairs', '(NSDictionary *) nsDictionary = ', + ' 2 key/value pairs', '(CFDictionaryRef) cfDictionaryRef = ', + ' 3 key/value pairs', '(CFArrayRef) cfarray_ref = ', + '@"3 elements"', '(CFMutableArrayRef) mutable_array_ref = ', + '@"11 elements"' + ]) + + self.expect( + 'frame variable iset1 iset2 imset', + substrs=['4 indexes', '512 indexes', '10 indexes']) + + self.expect( + 'frame variable binheap_ref', + substrs=['(CFBinaryHeapRef) binheap_ref = ', '@"21 items"']) + + self.expect( + 'expression -d run -- (NSArray*)[NSArray new]', + substrs=['@"0 elements"']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSData.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSData.py new file mode 100644 index 00000000000..37991ddb99d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSData.py @@ -0,0 +1,34 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterNSData(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_nsdata_with_run_command(self): + """Test formatters for NSData.""" + self.appkit_tester_impl(self.nsdata_data_formatter_commands) + + def nsdata_data_formatter_commands(self): + self.expect( + 'frame variable immutableData mutableData data_ref mutable_data_ref mutable_string_ref concreteData concreteMutableData', + substrs=[ + '(NSData *) immutableData = ', ' 4 bytes', + '(NSData *) mutableData = ', ' 14 bytes', + '(CFDataRef) data_ref = ', '@"5 bytes"', + '(CFMutableDataRef) mutable_data_ref = ', '@"5 bytes"', + '(CFMutableStringRef) mutable_string_ref = ', + ' @"Wish ya knew"', '(NSData *) concreteData = ', + ' 100000 bytes', '(NSMutableData *) concreteMutableData = ', + ' 100000 bytes' + ]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSDate.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSDate.py new file mode 100644 index 00000000000..a064dd7a90b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSDate.py @@ -0,0 +1,34 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterNSDate(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_nsdata_with_run_command(self): + """Test formatters for NSData.""" + self.appkit_tester_impl(self.nsdata_data_formatter_commands) + + def nsdata_data_formatter_commands(self): + self.expect( + 'frame variable immutableData mutableData data_ref mutable_data_ref mutable_string_ref concreteData concreteMutableData', + substrs=[ + '(NSData *) immutableData = ', ' 4 bytes', + '(NSData *) mutableData = ', ' 14 bytes', + '(CFDataRef) data_ref = ', '@"5 bytes"', + '(CFMutableDataRef) mutable_data_ref = ', '@"5 bytes"', + '(CFMutableStringRef) mutable_string_ref = ', + ' @"Wish ya knew"', '(NSData *) concreteData = ', + ' 100000 bytes', '(NSMutableData *) concreteMutableData = ', + ' 100000 bytes' + ]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSError.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSError.py new file mode 100644 index 00000000000..df380aefd88 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSError.py @@ -0,0 +1,35 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterNSError(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_nserror_with_run_command(self): + """Test formatters for NSError.""" + self.appkit_tester_impl(self.nserror_data_formatter_commands) + + def nserror_data_formatter_commands(self): + self.expect( + 'frame variable nserror', substrs=['domain: @"Foobar" - code: 12']) + + self.expect( + 'frame variable nserrorptr', + substrs=['domain: @"Foobar" - code: 12']) + + self.expect( + 'frame variable nserror->_userInfo', substrs=['2 key/value pairs']) + + self.expect( + 'frame variable nserror->_userInfo --ptr-depth 1 -d run-target', + substrs=['@"a"', '@"b"', "1", "2"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSURL.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSURL.py new file mode 100644 index 00000000000..e84818e9a70 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCNSURL.py @@ -0,0 +1,39 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterNSURL(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_nsurl_with_run_command(self): + """Test formatters for NSURL.""" + self.appkit_tester_impl(self.nsurl_data_formatter_commands) + + def nsurl_data_formatter_commands(self): + self.expect( + 'frame variable cfurl_ref cfchildurl_ref cfgchildurl_ref', + substrs=[ + '(CFURLRef) cfurl_ref = ', '@"http://www.foo.bar', + 'cfchildurl_ref = ', '@"page.html -- http://www.foo.bar', + '(CFURLRef) cfgchildurl_ref = ', + '@"?whatever -- http://www.foo.bar/page.html"' + ]) + + self.expect( + 'frame variable nsurl nsurl2 nsurl3', + substrs=[ + '(NSURL *) nsurl = ', '@"http://www.foo.bar', + '(NSURL *) nsurl2 =', '@"page.html -- http://www.foo.bar', + '(NSURL *) nsurl3 = ', + '@"?whatever -- http://www.foo.bar/page.html"' + ]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCPlain.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCPlain.py new file mode 100644 index 00000000000..f438245aad2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjCPlain.py @@ -0,0 +1,77 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterNSPlain(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_plain_objc_with_run_command(self): + """Test basic ObjC formatting behavior.""" + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Set break point at this line.', + lldb.SBFileSpec('main.m', False)) + + # The stop reason of the thread should be breakpoint. + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("type summary add --summary-string \"${var%@}\" MyClass") + + self.expect("frame variable object2", substrs=['MyOtherClass']) + + self.expect("frame variable *object2", substrs=['MyOtherClass']) + + # Now let's delete the 'MyClass' custom summary. + self.runCmd("type summary delete MyClass") + + # The type format list should not show 'MyClass' at this point. + self.expect("type summary list", matching=False, substrs=['MyClass']) + + self.runCmd("type summary add --summary-string \"a test\" MyClass") + + self.expect( + "frame variable *object2", + substrs=['*object2 =', 'MyClass = a test', 'backup = ']) + + self.expect( + "frame variable object2", matching=False, substrs=['a test']) + + self.expect("frame variable object", substrs=['a test']) + + self.expect("frame variable *object", substrs=['a test']) + + self.expect( + 'frame variable myclass', substrs=['(Class) myclass = NSValue']) + self.expect( + 'frame variable myclass2', + substrs=['(Class) myclass2 = ', 'NS', 'String']) + self.expect( + 'frame variable myclass3', substrs=['(Class) myclass3 = Molecule']) + self.expect( + 'frame variable myclass4', + substrs=['(Class) myclass4 = NSMutableArray']) + self.expect( + 'frame variable myclass5', substrs=['(Class) myclass5 = nil']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjNSException.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjNSException.py new file mode 100644 index 00000000000..6265c05c5b7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjNSException.py @@ -0,0 +1,34 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase + + +class ObjCDataFormatterNSException(ObjCDataFormatterTestCase): + + @skipUnlessDarwin + def test_nsexception_with_run_command(self): + """Test formatters for NSException.""" + self.appkit_tester_impl(self.nsexception_data_formatter_commands) + + def nsexception_data_formatter_commands(self): + self.expect( + 'frame variable except0 except1 except2 except3', + substrs=[ + '(NSException *) except0 = ', + '@"First"', + '(NSException *) except1 = ', + '@"Second"', + '(NSException *) except2 = ', + ' @"Third"', + '(NSException *) except3 = ', + ' @"Fourth"' + ]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/cmtime/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/cmtime/Makefile new file mode 100644 index 00000000000..143997cf26e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/cmtime/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -w + +LD_EXTRAS := -framework CoreMedia +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/cmtime/TestDataFormatterCMTime.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/cmtime/TestDataFormatterCMTime.py new file mode 100644 index 00000000000..4c3935c851c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/cmtime/TestDataFormatterCMTime.py @@ -0,0 +1,39 @@ +# encoding: utf-8 + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CMTimeDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_nsindexpath_with_run_command(self): + """Test formatters for CMTime.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + + line = line_number('main.m', '// break here') + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect( + 'frame variable t1', + substrs=[ + '1 10th of a second', 'value = 1', 'timescale = 10', + 'epoch = 0' + ]) + self.expect( + 'frame variable t2', + substrs=['10 seconds', 'value = 10', 'timescale = 1', 'epoch = 0']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/cmtime/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/cmtime/main.m new file mode 100644 index 00000000000..ecf7648c3f9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/cmtime/main.m @@ -0,0 +1,22 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <CoreMedia/CoreMedia.h> + +int main(int argc, const char **argv) +{ + @autoreleasepool + { + CMTime t1 = CMTimeMake(1, 10); + CMTime t2 = CMTimeMake(10, 1); + + CMTimeShow(t1); // break here + CMTimeShow(t2); + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/main.m new file mode 100644 index 00000000000..f0dc2055976 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/main.m @@ -0,0 +1,632 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +#if defined(__APPLE__) +#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) +#define IOS +#endif +#endif + +#if defined(IOS) +#import <Foundation/NSGeometry.h> +#else +#import <Carbon/Carbon.h> +#endif + +@interface MyClass : NSObject +{ + int i; + char c; + float f; +} + +- (id)initWithInt: (int)x andFloat:(float)y andChar:(char)z; +- (int)doIncrementByInt: (int)x; + +@end + +@interface MyOtherClass : MyClass +{ + int i2; + MyClass *backup; +} +- (id)initWithInt: (int)x andFloat:(float)y andChar:(char)z andOtherInt:(int)q; + +@end + +@implementation MyClass + +- (id)initWithInt: (int)x andFloat:(float)y andChar:(char)z +{ + self = [super init]; + if (self) { + self->i = x; + self->f = y; + self->c = z; + } + return self; +} + +- (int)doIncrementByInt: (int)x +{ + self->i += x; + return self->i; +} + +@end + +@implementation MyOtherClass + +- (id)initWithInt: (int)x andFloat:(float)y andChar:(char)z andOtherInt:(int)q +{ + self = [super initWithInt:x andFloat:y andChar:z]; + if (self) { + self->i2 = q; + self->backup = [[MyClass alloc] initWithInt:x andFloat:y andChar:z]; + } + return self; +} + +@end + +@interface Atom : NSObject { + float mass; +} +-(void)setMass:(float)newMass; +-(float)mass; +@end + +@interface Molecule : NSObject { + NSArray *atoms; +} +-(void)setAtoms:(NSArray *)newAtoms; +-(NSArray *)atoms; +@end + +@implementation Atom + +-(void)setMass:(float)newMass +{ + mass = newMass; +} +-(float)mass +{ + return mass; +} + +@end + +@implementation Molecule + +-(void)setAtoms:(NSArray *)newAtoms +{ + atoms = newAtoms; +} +-(NSArray *)atoms +{ + return atoms; +} +@end + +@interface My_KVO_Observer : NSObject +-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change + context:(void *)context; +- (id) init; +- (void) dealloc; +@end + +@implementation My_KVO_Observer +-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change + context:(void *)context { + // we do not really care about KVO'ing - do nothing + return; +} +- (id) init +{ + self = [super init]; + return self; +} + +- (void) dealloc +{ + [super dealloc]; +} +@end + +int main (int argc, const char * argv[]) +{ + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + MyClass *object = [[MyClass alloc] initWithInt:1 andFloat:3.14 andChar: 'E']; + + [object doIncrementByInt:3]; + + MyOtherClass *object2 = [[MyOtherClass alloc] initWithInt:2 andFloat:6.28 andChar: 'G' andOtherInt:-1]; + + [object2 doIncrementByInt:3]; + + NSNumber* num1 = [NSNumber numberWithInt:5]; + NSNumber* num2 = [NSNumber numberWithFloat:3.14]; + NSNumber* num3 = [NSNumber numberWithDouble:3.14]; + NSNumber* num4 = [NSNumber numberWithUnsignedLongLong:0xFFFFFFFFFFFFFFFE]; + NSNumber* num5 = [NSNumber numberWithChar:'A']; + NSNumber* num6 = [NSNumber numberWithUnsignedLongLong:0xFF]; + NSNumber* num7 = [NSNumber numberWithLong:0x1E8480]; + NSNumber* num8_Y = [NSNumber numberWithBool:YES]; + NSNumber* num8_N = [NSNumber numberWithBool:NO]; + NSNumber* num9 = [NSNumber numberWithShort:0x1E8480]; + NSNumber* num_at1 = @12; + NSNumber* num_at2 = @-12; + NSNumber* num_at3 = @12.5; + NSNumber* num_at4 = @-12.5; + + NSDecimalNumber* decimal_number = [NSDecimalNumber decimalNumberWithMantissa:123456 exponent:-10 isNegative:NO]; + NSDecimalNumber* decimal_number_neg = [NSDecimalNumber decimalNumberWithMantissa:123456 exponent:10 isNegative:YES]; + NSDecimalNumber* decimal_one = [NSDecimalNumber one]; + NSDecimalNumber* decimal_zero = [NSDecimalNumber zero]; + NSDecimalNumber* decimal_nan = [NSDecimalNumber notANumber]; + + NSString *str0 = [num6 stringValue]; + + NSString *str1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding]; + + NSString *str2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"]; + + NSString *str3 = @"A string made with the at sign is here"; + + NSString *str4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4]; + + NSRect ns_rect_4str = {{1,1},{5,5}}; + + NSString* str5 = NSStringFromRect(ns_rect_4str); + + NSString* str6 = [@"/usr/doc/README.1ST" pathExtension]; + + const unichar myCharacters[] = {0x03C3,'x','x'}; + NSString *str7 = [NSString stringWithCharacters: myCharacters + length: sizeof myCharacters / sizeof *myCharacters]; + + NSString* str8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension]; + + const unichar myOtherCharacters[] = {'a',' ', 'v','e','r','y',' ', + 'm','u','c','h',' ','b','o','r','i','n','g',' ','t','a','s','k', + ' ','t','o',' ','w','r','i','t','e', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', + 't','h','i','s',' ','w','a','y','!','!',0x03C3, 0}; + NSString *str9 = [NSString stringWithCharacters: myOtherCharacters + length: sizeof myOtherCharacters / sizeof *myOtherCharacters]; + + const unichar myNextCharacters[] = {0x03C3, 0x0000}; + + NSString *str10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4]; + + NSString *str11 = NSStringFromClass([str10 class]); + + NSString *label1 = @"Process Name: "; + NSString *label2 = @"Process Id: "; + NSString *processName = [[NSProcessInfo processInfo] processName]; + NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]]; + NSString *str12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID]; + + NSString *strA1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding]; + + NSString *strA2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"]; + + NSString *strA3 = @"A string made with the at sign is here"; + + NSString *strA4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4]; + + NSString* strA5 = NSStringFromRect(ns_rect_4str); + + NSString* strA6 = [@"/usr/doc/README.1ST" pathExtension]; + + NSString *strA7 = [NSString stringWithCharacters: myCharacters + length: sizeof myCharacters / sizeof *myCharacters]; + + NSString* strA8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension]; + + NSString *strA9 = [NSString stringWithCharacters: myOtherCharacters + length: sizeof myOtherCharacters / sizeof *myOtherCharacters]; + + NSString *strA10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4]; + + NSString *strA11 = NSStringFromClass([str10 class]); + + NSString *strA12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID]; + + NSString *strB1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding]; + + NSString *strB2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"]; + + NSString *strB3 = @"A string made with the at sign is here"; + + NSString *strB4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4]; + + NSString* strB5 = NSStringFromRect(ns_rect_4str); + + NSString* strB6 = [@"/usr/doc/README.1ST" pathExtension]; + + NSString *strB7 = [NSString stringWithCharacters: myCharacters + length: sizeof myCharacters / sizeof *myCharacters]; + + NSString* strB8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension]; + + NSString *strB9 = [NSString stringWithCharacters: myOtherCharacters + length: sizeof myOtherCharacters / sizeof *myOtherCharacters]; + + NSString *strB10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4]; + + NSString *strB11 = NSStringFromClass([str10 class]); + + NSString *strB12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID]; + + NSString *strC11 = NSStringFromClass([str10 class]); + + NSString *strC12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID]; + + NSString *strC1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding]; + + NSString *strC2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"]; + + NSString *strC3 = @"A string made with the at sign is here"; + + NSString *strC4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4]; + + NSString* strC5 = NSStringFromRect(ns_rect_4str); + + NSString* strC6 = [@"/usr/doc/README.1ST" pathExtension]; + + NSString *strC7 = [NSString stringWithCharacters: myCharacters + length: sizeof myCharacters / sizeof *myCharacters]; + + NSString* strC8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension]; + + NSString *strC9 = [NSString stringWithCharacters: myOtherCharacters + length: sizeof myOtherCharacters / sizeof *myOtherCharacters]; + + NSString *strC10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4]; + + NSString *strD11 = NSStringFromClass([str10 class]); + + NSString *strD12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID]; + + NSString *eAcute = [NSString stringWithFormat: @"%C", 0x00E9]; + NSString *randomHaziChar = [NSString stringWithFormat: @"%C", 0x9DC5]; + NSString *japanese = @"色は匂へど散りぬるを"; + NSString *italian = @"L'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione."; + NSString* french = @"Que veut cette horde d'esclaves, De traîtres, de rois conjurés?"; + NSString* german = @"Über-Ich und aus den Ansprüchen der sozialen Umwelt"; + + void* data_set[3] = {str1,str2,str3}; + + NSString *hebrew = [NSString stringWithString:@"לילה טוב"]; + + NSArray* newArray = [[NSMutableArray alloc] init]; + [newArray addObject:str1]; + [newArray addObject:str2]; + [newArray addObject:str3]; + [newArray addObject:str4]; + [newArray addObject:str5]; + [newArray addObject:str6]; + [newArray addObject:str7]; + [newArray addObject:str8]; + [newArray addObject:str9]; + [newArray addObject:str10]; + [newArray addObject:str11]; + [newArray addObject:str12]; + [newArray addObject:strA1]; + [newArray addObject:strA2]; + [newArray addObject:strA3]; + [newArray addObject:strA4]; + [newArray addObject:strA5]; + [newArray addObject:strA6]; + [newArray addObject:strA7]; + [newArray addObject:strA8]; + [newArray addObject:strA9]; + [newArray addObject:strA10]; + [newArray addObject:strA11]; + [newArray addObject:strA12]; + [newArray addObject:strB1]; + [newArray addObject:strB2]; + [newArray addObject:strB3]; + [newArray addObject:strB4]; + [newArray addObject:strB5]; + [newArray addObject:strB6]; + [newArray addObject:strB7]; + [newArray addObject:strB8]; + [newArray addObject:strB9]; + [newArray addObject:strB10]; + [newArray addObject:strB11]; + [newArray addObject:strB12]; + [newArray addObject:strC1]; + [newArray addObject:strC2]; + [newArray addObject:strC3]; + [newArray addObject:strC4]; + [newArray addObject:strC5]; + [newArray addObject:strC6]; + [newArray addObject:strC7]; + [newArray addObject:strC8]; + [newArray addObject:strC9]; + [newArray addObject:strC10]; + [newArray addObject:strC11]; + [newArray addObject:strC12]; + [newArray addObject:strD11]; + [newArray addObject:strD12]; + + NSDictionary* newDictionary = [[NSDictionary alloc] initWithObjects:newArray forKeys:newArray]; + NSDictionary *newMutableDictionary = [[NSMutableDictionary alloc] init]; + [newMutableDictionary setObject:@"foo" forKey:@"bar0"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar1"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar2"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar3"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar4"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar5"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar6"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar7"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar8"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar9"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar10"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar11"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar12"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar13"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar14"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar15"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar16"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar17"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar18"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar19"]; + [newMutableDictionary setObject:@"foo" forKey:@"bar20"]; + + id cfKeys[2] = { @"foo", @"bar", @"baz", @"quux" }; + id cfValues[2] = { @"foo", @"bar", @"baz", @"quux" }; + NSDictionary *nsDictionary = CFBridgingRelease(CFDictionaryCreate(nil, (void *)cfKeys, (void *)cfValues, 2, nil, nil)); + CFDictionaryRef cfDictionaryRef = CFDictionaryCreate(nil, (void *)cfKeys, (void *)cfValues, 3, nil, nil); + + NSAttributedString* attrString = [[NSAttributedString alloc] initWithString:@"hello world from foo" attributes:newDictionary]; + [attrString isEqual:nil]; + NSAttributedString* mutableAttrString = [[NSMutableAttributedString alloc] initWithString:@"hello world from foo" attributes:newDictionary]; + [mutableAttrString isEqual:nil]; + + NSString* mutableString = [[NSMutableString alloc] initWithString:@"foo"]; + [mutableString insertString:@"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear " atIndex:0]; + + NSString* mutableGetConst = [NSString stringWithCString:[mutableString cString]]; + + [mutableGetConst length]; + + NSData *immutableData = [[NSData alloc] initWithBytes:"HELLO" length:4]; + NSData *mutableData = [[NSMutableData alloc] initWithBytes:"NODATA" length:6]; + + // No-copy versions of NSData initializers use NSConcreteData if over 2^16 elements are specified. + unsigned concreteLength = 100000; + void *zeroes1 = calloc(1, concreteLength); + // initWithBytesNoCopy takes ownership of the buffer. + NSData *concreteData = [[NSData alloc] initWithBytesNoCopy:zeroes1 length:concreteLength]; + void *zeroes2 = calloc(1, concreteLength); + NSMutableData *concreteMutableData = [[NSMutableData alloc] initWithBytesNoCopy:zeroes2 length:concreteLength]; + + [mutableData appendBytes:"MOREDATA" length:8]; + + [immutableData length]; + [mutableData length]; + + NSSet* nsset = [[NSSet alloc] initWithObjects:str1,str2,str3,nil]; + NSSet *nsmutableset = [[NSMutableSet alloc] initWithObjects:str1,str2,str3,nil]; + [nsmutableset addObject:str4]; + + CFDataRef data_ref = CFDataCreate(kCFAllocatorDefault, [immutableData bytes], 5); + + CFMutableDataRef mutable_data_ref = CFDataCreateMutable(kCFAllocatorDefault, 8); + CFDataAppendBytes(mutable_data_ref, [mutableData bytes], 5); + + CFMutableStringRef mutable_string_ref = CFStringCreateMutable(NULL,100); + CFStringAppend(mutable_string_ref, CFSTR("Wish ya knew")); + + CFStringRef cfstring_ref = CFSTR("HELLO WORLD"); + + CFArrayRef cfarray_ref = CFArrayCreate(NULL, data_set, 3, NULL); + CFMutableArrayRef mutable_array_ref = CFArrayCreateMutable(NULL, 16, NULL); + + CFArraySetValueAtIndex(mutable_array_ref, 0, str1); + CFArraySetValueAtIndex(mutable_array_ref, 1, str2); + CFArraySetValueAtIndex(mutable_array_ref, 2, str3); + CFArraySetValueAtIndex(mutable_array_ref, 3, str4); + CFArraySetValueAtIndex(mutable_array_ref, 0, str5); // replacing value at 0!! + CFArraySetValueAtIndex(mutable_array_ref, 4, str6); + CFArraySetValueAtIndex(mutable_array_ref, 5, str7); + CFArraySetValueAtIndex(mutable_array_ref, 6, str8); + CFArraySetValueAtIndex(mutable_array_ref, 7, str9); + CFArraySetValueAtIndex(mutable_array_ref, 8, str10); + CFArraySetValueAtIndex(mutable_array_ref, 9, str11); + CFArraySetValueAtIndex(mutable_array_ref, 10, str12); + + CFBinaryHeapRef binheap_ref = CFBinaryHeapCreate(NULL, 15, &kCFStringBinaryHeapCallBacks, NULL); + CFBinaryHeapAddValue(binheap_ref, str1); + CFBinaryHeapAddValue(binheap_ref, str2); + CFBinaryHeapAddValue(binheap_ref, str3); + CFBinaryHeapAddValue(binheap_ref, str4); + CFBinaryHeapAddValue(binheap_ref, str5); + CFBinaryHeapAddValue(binheap_ref, str6); + CFBinaryHeapAddValue(binheap_ref, str7); + CFBinaryHeapAddValue(binheap_ref, str8); + CFBinaryHeapAddValue(binheap_ref, str9); + CFBinaryHeapAddValue(binheap_ref, str10); + CFBinaryHeapAddValue(binheap_ref, str11); + CFBinaryHeapAddValue(binheap_ref, str12); + CFBinaryHeapAddValue(binheap_ref, strA1); + CFBinaryHeapAddValue(binheap_ref, strB1); + CFBinaryHeapAddValue(binheap_ref, strC1); + CFBinaryHeapAddValue(binheap_ref, strA11); + CFBinaryHeapAddValue(binheap_ref, strB11); + CFBinaryHeapAddValue(binheap_ref, strC11); + CFBinaryHeapAddValue(binheap_ref, strB12); + CFBinaryHeapAddValue(binheap_ref, strC12); + CFBinaryHeapAddValue(binheap_ref, strA12); + + CFURLRef cfurl_ref = CFURLCreateWithString(NULL, CFSTR("http://www.foo.bar/"), NULL); + CFURLRef cfchildurl_ref = CFURLCreateWithString(NULL, CFSTR("page.html"), cfurl_ref); + CFURLRef cfgchildurl_ref = CFURLCreateWithString(NULL, CFSTR("?whatever"), cfchildurl_ref); + + NSDictionary *error_userInfo = @{@"a": @1, @"b" : @2}; + NSError *nserror = [[NSError alloc] initWithDomain:@"Foobar" code:12 userInfo:error_userInfo]; + NSError **nserrorptr = &nserror; + + NSBundle* bundle_string = [[NSBundle alloc] initWithPath:@"/System/Library/Frameworks/Accelerate.framework"]; + NSBundle* bundle_url = [[NSBundle alloc] initWithURL:[[NSURL alloc] initWithString:@"file://localhost/System/Library/Frameworks/Foundation.framework"]]; + + NSBundle* main_bundle = [NSBundle mainBundle]; + + NSArray* bundles = [NSBundle allBundles]; + + NSURL *nsurl0; + + for (NSBundle* bundle in bundles) + { + nsurl0 = [bundle bundleURL]; + } + + NSException* except0 = [[NSException alloc] initWithName:@"TheGuyWhoHasNoName" reason:@"First" userInfo:nil]; + NSException* except1 = [[NSException alloc] initWithName:@"TheGuyWhoHasNoName~1" reason:@"Second" userInfo:nil]; + NSException* except2 = [[NSException alloc] initWithName:@"TheGuyWhoHasNoName`2" reason:@"Third" userInfo:nil]; + NSException* except3 = [[NSException alloc] initWithName:@"TheGuyWhoHasNoName/3" reason:@"Fourth" userInfo:nil]; + + NSURL *nsurl = [[NSURL alloc] initWithString:@"http://www.foo.bar"]; + NSURL *nsurl2 = [NSURL URLWithString:@"page.html" relativeToURL:nsurl]; + NSURL *nsurl3 = [NSURL URLWithString:@"?whatever" relativeToURL:nsurl2]; + + NSDate *date1 = [NSDate dateWithNaturalLanguageString:@"6pm April 10, 1985"]; + NSDate *date2 = [NSDate dateWithNaturalLanguageString:@"12am January 1, 2011"]; + NSDate *date3 = [NSDate date]; + NSDate *date4 = [NSDate dateWithTimeIntervalSince1970:24*60*60]; + NSDate *date5 = [NSDate dateWithTimeIntervalSinceReferenceDate: floor([[NSDate date] timeIntervalSinceReferenceDate])]; + + CFAbsoluteTime date1_abs = CFDateGetAbsoluteTime(date1); + CFAbsoluteTime date2_abs = CFDateGetAbsoluteTime(date2); + CFAbsoluteTime date3_abs = CFDateGetAbsoluteTime(date3); + CFAbsoluteTime date4_abs = CFDateGetAbsoluteTime(date4); + CFAbsoluteTime date5_abs = CFDateGetAbsoluteTime(date5); + + NSIndexSet *iset1 = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(1, 4)]; + NSIndexSet *iset2 = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(1, 512)]; + + NSMutableIndexSet *imset = [[NSMutableIndexSet alloc] init]; + [imset addIndex:1936]; + [imset addIndex:7]; + [imset addIndex:9]; + [imset addIndex:11]; + [imset addIndex:24]; + [imset addIndex:41]; + [imset addIndex:58]; + [imset addIndex:61]; + [imset addIndex:62]; + [imset addIndex:63]; + + CFTimeZoneRef cupertino = CFTimeZoneCreateWithName ( + NULL, + CFSTR("PST"), + YES); + CFTimeZoneRef home = CFTimeZoneCreateWithName ( + NULL, + CFSTR("Europe/Rome"), + YES); + CFTimeZoneRef europe = CFTimeZoneCreateWithName ( + NULL, + CFSTR("CET"), + YES); + + NSTimeZone *cupertino_ns = [NSTimeZone timeZoneWithAbbreviation:@"PST"]; + NSTimeZone *home_ns = [NSTimeZone timeZoneWithName:@"Europe/Rome"]; + NSTimeZone *europe_ns = [NSTimeZone timeZoneWithAbbreviation:@"CET"]; + + CFGregorianUnits cf_greg_units = {1,3,5,12,5,7}; + CFGregorianDate cf_greg_date = CFAbsoluteTimeGetGregorianDate(CFDateGetAbsoluteTime(date1), NULL); + CFRange cf_range = {4,4}; + NSPoint ns_point = {4,4}; + NSRange ns_range = {4,4}; + + NSRect ns_rect = {{1,1},{5,5}}; + NSRect* ns_rect_ptr = &ns_rect; + NSRectArray ns_rect_arr = &ns_rect; + NSSize ns_size = {5,7}; + NSSize* ns_size_ptr = &ns_size; + + CGSize cg_size = {1,6}; + CGPoint cg_point = {2,7}; + CGRect cg_rect = {{1,2}, {7,7}}; + +#ifndef IOS + RGBColor rgb_color = {3,56,35}; + RGBColor* rgb_color_ptr = &rgb_color; +#endif + + Rect rect = {4,8,4,7}; + Rect* rect_ptr = ▭ + + Point point = {7,12}; + Point* point_ptr = &point; + +#ifndef IOS + HIPoint hi_point = {7,12}; + HIRect hi_rect = {{3,5},{4,6}}; +#endif + + SEL foo_selector = @selector(foo_selector_impl); + + CFMutableBitVectorRef mut_bv = CFBitVectorCreateMutable(NULL, 64); + CFBitVectorSetCount(mut_bv, 50); + CFBitVectorSetBitAtIndex(mut_bv, 0, 1); + CFBitVectorSetBitAtIndex(mut_bv, 1, 1); + CFBitVectorSetBitAtIndex(mut_bv, 2, 1); + CFBitVectorSetBitAtIndex(mut_bv, 5, 1); + CFBitVectorSetBitAtIndex(mut_bv, 6, 1); + CFBitVectorSetBitAtIndex(mut_bv, 8, 1); + CFBitVectorSetBitAtIndex(mut_bv, 10, 1); + CFBitVectorSetBitAtIndex(mut_bv, 11, 1); + CFBitVectorSetBitAtIndex(mut_bv, 16, 1); + CFBitVectorSetBitAtIndex(mut_bv, 17, 1); + CFBitVectorSetBitAtIndex(mut_bv, 19, 1); + CFBitVectorSetBitAtIndex(mut_bv, 20, 1); + CFBitVectorSetBitAtIndex(mut_bv, 22, 1); + CFBitVectorSetBitAtIndex(mut_bv, 24, 1); + CFBitVectorSetBitAtIndex(mut_bv, 28, 1); + CFBitVectorSetBitAtIndex(mut_bv, 29, 1); + CFBitVectorSetBitAtIndex(mut_bv, 30, 1); + CFBitVectorSetBitAtIndex(mut_bv, 30, 1); + CFBitVectorSetBitAtIndex(mut_bv, 31, 1); + CFBitVectorSetBitAtIndex(mut_bv, 34, 1); + CFBitVectorSetBitAtIndex(mut_bv, 35, 1); + CFBitVectorSetBitAtIndex(mut_bv, 37, 1); + CFBitVectorSetBitAtIndex(mut_bv, 39, 1); + CFBitVectorSetBitAtIndex(mut_bv, 40, 1); + CFBitVectorSetBitAtIndex(mut_bv, 41, 1); + CFBitVectorSetBitAtIndex(mut_bv, 43, 1); + CFBitVectorSetBitAtIndex(mut_bv, 47, 1); + + Molecule *molecule = [Molecule new]; + + Class myclass = NSClassFromString(@"NSValue"); + Class myclass2 = [str0 class]; + Class myclass3 = [molecule class]; + Class myclass4 = NSClassFromString(@"NSMutableArray"); + Class myclass5 = [nil class]; + + NSArray *components = @[@"usr", @"blah", @"stuff"]; + NSString *path = [NSString pathWithComponents: components]; + + [molecule addObserver:[My_KVO_Observer new] forKeyPath:@"atoms" options:0 context:NULL]; // Set break point at this line. + [newMutableDictionary addObserver:[My_KVO_Observer new] forKeyPath:@"weirdKeyToKVO" options:NSKeyValueObservingOptionNew context:NULL]; + + [molecule setAtoms:nil]; + [molecule setAtoms:[NSMutableArray new]]; + + [pool drain]; + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/Makefile new file mode 100644 index 00000000000..8b322ff320b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/Makefile @@ -0,0 +1,8 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py new file mode 100644 index 00000000000..12461ab03de --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/TestDataFormatterNSIndexPath.py @@ -0,0 +1,112 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NSIndexPathDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def appkit_tester_impl(self, commands): + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + commands() + + @skipUnlessDarwin + @expectedFailureAll(archs=['i386'], bugnumber="rdar://28656605") + @expectedFailureAll(archs=['armv7', 'armv7k', 'arm64_32'], bugnumber="rdar://problem/34561607") # NSIndexPath formatter isn't working for 32-bit arm + def test_nsindexpath_with_run_command(self): + """Test formatters for NSIndexPath.""" + self.appkit_tester_impl(self.nsindexpath_data_formatter_commands) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.m', '// break here') + + def nsindexpath_data_formatter_commands(self): + # check 'frame variable' + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath1', + substrs=['[0] = 1']) + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath2', + substrs=[ + '[0] = 1', + '[1] = 2']) + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath3', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3']) + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath4', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3', + '[3] = 4']) + self.expect( + 'frame variable --ptr-depth=1 -d run -- indexPath5', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3', + '[3] = 4', + '[4] = 5']) + + # and 'expression' + self.expect( + 'expression --ptr-depth=1 -d run -- indexPath1', + substrs=['[0] = 1']) + self.expect( + 'expression --ptr-depth=1 -d run -- indexPath2', + substrs=[ + '[0] = 1', + '[1] = 2']) + self.expect( + 'expression --ptr-depth=1 -d run -- indexPath3', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3']) + self.expect('expression --ptr-depth=1 -d run -- indexPath4', + substrs=['[0] = 1', '[1] = 2', '[2] = 3', '[3] = 4']) + self.expect( + 'expression --ptr-depth=1 -d run -- indexPath5', + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3', + '[3] = 4', + '[4] = 5']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/main.m new file mode 100644 index 00000000000..e34cf522299 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsindexpath/main.m @@ -0,0 +1,30 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +int main(int argc, const char **argv) +{ + @autoreleasepool + { + const NSUInteger values[] = { 1, 2, 3, 4, 5 }; + + NSIndexPath* indexPath1 = [NSIndexPath indexPathWithIndexes:values length:1]; + NSIndexPath* indexPath2 = [NSIndexPath indexPathWithIndexes:values length:2]; + NSIndexPath* indexPath3 = [NSIndexPath indexPathWithIndexes:values length:3]; + NSIndexPath* indexPath4 = [NSIndexPath indexPathWithIndexes:values length:4]; + NSIndexPath* indexPath5 = [NSIndexPath indexPathWithIndexes:values length:5]; + + NSLog(@"%@", indexPath1); // break here + NSLog(@"%@", indexPath2); + NSLog(@"%@", indexPath3); + NSLog(@"%@", indexPath4); + NSLog(@"%@", indexPath5); + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/Makefile new file mode 100644 index 00000000000..8b322ff320b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/Makefile @@ -0,0 +1,8 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py new file mode 100644 index 00000000000..6480025e2e1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py @@ -0,0 +1,120 @@ +# encoding: utf-8 +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NSStringDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def appkit_tester_impl(self, commands): + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + commands() + + @skipUnlessDarwin + @no_debug_info_test + def test_nsstring_with_run_command(self): + """Test formatters for NSString.""" + self.appkit_tester_impl(self.nsstring_data_formatter_commands) + + @skipUnlessDarwin + @no_debug_info_test + def test_rdar11106605_with_run_command(self): + """Check that Unicode characters come out of CFString summary correctly.""" + self.appkit_tester_impl(self.rdar11106605_commands) + + @skipUnlessDarwin + @no_debug_info_test + def test_nsstring_withNULS_with_run_command(self): + """Test formatters for NSString.""" + self.appkit_tester_impl(self.nsstring_withNULs_commands) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.m', '// break here') + + def rdar11106605_commands(self): + """Check that Unicode characters come out of CFString summary correctly.""" + self.expect('frame variable italian', substrs=[ + 'L\'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione.']) + self.expect('frame variable french', substrs=[ + 'Que veut cette horde d\'esclaves, De traîtres, de rois conjurés?']) + self.expect('frame variable german', substrs=[ + 'Über-Ich und aus den Ansprüchen der sozialen Umwelt']) + self.expect('frame variable japanese', substrs=['色は匂へど散りぬるを']) + self.expect('frame variable hebrew', substrs=['לילה טוב']) + + def nsstring_data_formatter_commands(self): + self.expect('frame variable str0 str1 str2 str3 str4 str5 str6 str8 str9 str10 str11 label1 label2 processName str12', + substrs=['(NSString *) str1 = ', ' @"A rather short ASCII NSString object is here"', + # '(NSString *) str0 = ',' @"255"', + '(NSString *) str1 = ', ' @"A rather short ASCII NSString object is here"', + '(NSString *) str2 = ', ' @"A rather short UTF8 NSString object is here"', + '(NSString *) str3 = ', ' @"A string made with the at sign is here"', + '(NSString *) str4 = ', ' @"This is string number 4 right here"', + '(NSString *) str5 = ', ' @"{{1, 1}, {5, 5}}"', + '(NSString *) str6 = ', ' @"1ST"', + '(NSString *) str8 = ', ' @"hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime', + '(NSString *) str9 = ', ' @"a very much boring task to write a string this way!!', + '(NSString *) str10 = ', ' @"This is a Unicode string σ number 4 right here"', + '(NSString *) str11 = ', ' @"__NSCFString"', + '(NSString *) label1 = ', ' @"Process Name: "', + '(NSString *) label2 = ', ' @"Process Id: "', + '(NSString *) str12 = ', ' @"Process Name: a.out Process Id:']) + self.expect( + 'frame variable attrString mutableAttrString mutableGetConst', + substrs=[ + '(NSAttributedString *) attrString = ', + ' @"hello world from foo"', + '(NSAttributedString *) mutableAttrString = ', + ' @"hello world from foo"', + '(NSString *) mutableGetConst = ', + ' @"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear foo"']) + + self.expect('expr -d run-target -- path', substrs=['usr/blah/stuff']) + self.expect('frame variable path', substrs=['usr/blah/stuff']) + + def nsstring_withNULs_commands(self): + """Check that the NSString formatter supports embedded NULs in the text""" + self.expect( + 'po strwithNULs', + substrs=['a very much boring task to write']) + self.expect('expr [strwithNULs length]', substrs=['54']) + self.expect('frame variable strwithNULs', substrs=[ + '@"a very much boring task to write\\0a string this way!!']) + self.expect('po strwithNULs2', substrs=[ + 'a very much boring task to write']) + self.expect('expr [strwithNULs2 length]', substrs=['52']) + self.expect('frame variable strwithNULs2', substrs=[ + '@"a very much boring task to write\\0a string this way!!']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/main.m new file mode 100644 index 00000000000..b0d926fd54e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/main.m @@ -0,0 +1,98 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +#if defined(__APPLE__) +#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) +#define IOS +#endif +#endif + +#if defined(IOS) +#import <Foundation/NSGeometry.h> +#else +#import <Carbon/Carbon.h> +#endif + +int main (int argc, const char * argv[]) +{ + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + NSString *str0 = [[NSNumber numberWithUnsignedLongLong:0xFF] stringValue]; + NSString *str1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding]; + NSString *str2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"]; + NSString *str3 = @"A string made with the at sign is here"; + NSString *str4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4]; + NSRect ns_rect_4str = {{1,1},{5,5}}; + NSString* str5 = NSStringFromRect(ns_rect_4str); + NSString* str6 = [@"/usr/doc/README.1ST" pathExtension]; + const unichar myCharacters[] = {0x03C3,'x','x'}; + NSString *str7 = [NSString stringWithCharacters: myCharacters + length: sizeof myCharacters / sizeof *myCharacters]; + NSString* str8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension]; + const unichar myOtherCharacters[] = {'a',' ', 'v','e','r','y',' ', + 'm','u','c','h',' ','b','o','r','i','n','g',' ','t','a','s','k', + ' ','t','o',' ','w','r','i','t','e', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', + 't','h','i','s',' ','w','a','y','!','!',0x03C3, 0}; + NSString *str9 = [NSString stringWithCharacters: myOtherCharacters + length: sizeof myOtherCharacters / sizeof *myOtherCharacters]; + const unichar myNextCharacters[] = {0x03C3, 0x0000}; + NSString *str10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4]; + NSString *str11 = NSStringFromClass([str10 class]); + NSString *label1 = @"Process Name: "; + NSString *label2 = @"Process Id: "; + NSString *processName = [[NSProcessInfo processInfo] processName]; + NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]]; + NSString *str12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID]; + NSString *eAcute = [NSString stringWithFormat: @"%C", 0x00E9]; + NSString *randomHaziChar = [NSString stringWithFormat: @"%C", 0x9DC5]; + NSString *japanese = @"色は匂へど散りぬるを"; + NSString *italian = @"L'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione."; + NSString* french = @"Que veut cette horde d'esclaves, De traîtres, de rois conjurés?"; + NSString* german = @"Über-Ich und aus den Ansprüchen der sozialen Umwelt"; + void* data_set[3] = {str1,str2,str3}; + NSString *hebrew = [NSString stringWithString:@"לילה טוב"]; + + NSAttributedString* attrString = [[NSAttributedString alloc] initWithString:@"hello world from foo" attributes:[NSDictionary new]]; + [attrString isEqual:nil]; + NSAttributedString* mutableAttrString = [[NSMutableAttributedString alloc] initWithString:@"hello world from foo" attributes:[NSDictionary new]]; + [mutableAttrString isEqual:nil]; + + NSString* mutableString = [[NSMutableString alloc] initWithString:@"foo"]; + [mutableString insertString:@"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear " atIndex:0]; + + NSString* mutableGetConst = [NSString stringWithCString:[mutableString cString]]; + + [mutableGetConst length]; + CFMutableStringRef mutable_string_ref = CFStringCreateMutable(NULL,100); + CFStringAppend(mutable_string_ref, CFSTR("Wish ya knew")); + CFStringRef cfstring_ref = CFSTR("HELLO WORLD"); + + NSArray *components = @[@"usr", @"blah", @"stuff"]; + NSString *path = [NSString pathWithComponents: components]; + + const unichar someOfTheseAreNUL[] = {'a',' ', 'v','e','r','y',' ', + 'm','u','c','h',' ','b','o','r','i','n','g',' ','t','a','s','k', + ' ','t','o',' ','w','r','i','t','e', 0, 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', + 't','h','i','s',' ','w','a','y','!','!', 0x03C3, 0}; + NSString *strwithNULs = [NSString stringWithCharacters: someOfTheseAreNUL + length: sizeof someOfTheseAreNUL / sizeof *someOfTheseAreNUL]; + + const unichar someOfTheseAreNUL2[] = {'a',' ', 'v','e','r','y',' ', + 'm','u','c','h',' ','b','o','r','i','n','g',' ','t','a','s','k', + ' ','t','o',' ','w','r','i','t','e', 0, 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', + 't','h','i','s',' ','w','a','y','!','!'}; + NSString *strwithNULs2 = [NSString stringWithCharacters: someOfTheseAreNUL2 + length: sizeof someOfTheseAreNUL2 / sizeof *someOfTheseAreNUL2]; + + [pool drain]; // break here + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/Makefile new file mode 100644 index 00000000000..8b322ff320b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/Makefile @@ -0,0 +1,8 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py new file mode 100644 index 00000000000..4611e162ada --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py @@ -0,0 +1,77 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DataFormatterOneIsSingularTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_one_is_singular_with_run_command(self): + """Test that 1 item is not as reported as 1 items.""" + self.build() + self.oneness_data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.m', '// Set break point at this line.') + + def oneness_data_formatter_commands(self): + """Test that 1 item is not as reported as 1 items.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Now check that we are displaying Cocoa classes correctly + self.expect('frame variable key', + substrs=['@"1 element"']) + self.expect('frame variable key', matching=False, + substrs=['1 elements']) + self.expect('frame variable value', + substrs=['@"1 element"']) + self.expect('frame variable value', matching=False, + substrs=['1 elements']) + self.expect('frame variable dict', + substrs=['1 key/value pair']) + self.expect('frame variable dict', matching=False, + substrs=['1 key/value pairs']) + self.expect('frame variable imset', + substrs=['1 index']) + self.expect('frame variable imset', matching=False, + substrs=['1 indexes']) + self.expect('frame variable binheap_ref', + substrs=['@"1 item"']) + self.expect('frame variable binheap_ref', matching=False, + substrs=['1 items']) + self.expect('frame variable immutableData', + substrs=['1 byte']) + self.expect('frame variable immutableData', matching=False, + substrs=['1 bytes']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/main.m new file mode 100644 index 00000000000..dc9e5609fbe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/main.m @@ -0,0 +1,30 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +int main (int argc, const char * argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + NSArray* key = [NSArray arrayWithObjects:@"foo",nil]; + NSArray* value = [NSArray arrayWithObjects:@"key",nil]; + NSDictionary *dict = [NSDictionary dictionaryWithObjects:value forKeys:key]; + + NSMutableIndexSet *imset = [[NSMutableIndexSet alloc] init]; + [imset addIndex:4]; + + CFBinaryHeapRef binheap_ref = CFBinaryHeapCreate(NULL, 15, &kCFStringBinaryHeapCallBacks, NULL); + CFBinaryHeapAddValue(binheap_ref, CFSTR("Hello world")); + + NSData *immutableData = [[NSData alloc] initWithBytes:"HELLO" length:1]; + + [pool drain];// Set break point at this line. + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py new file mode 100644 index 00000000000..b3c794f3f0c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py @@ -0,0 +1,56 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class PtrToArrayDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """Test that LLDB handles the clang typeclass Paren correctly.""" + self.build() + self.data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def data_formatter_commands(self): + """Test that LLDB handles the clang typeclass Paren correctly.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format delete hex', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.expect('p *(int (*)[3])foo', + substrs=['(int [3]) $', '[0] = 1', '[1] = 2', '[2] = 3']) + + self.expect('p *(int (*)[3])foo', matching=False, + substrs=['01 00 00 00 02 00 00 00 03 00 00 00']) + self.expect('p *(int (*)[3])foo', matching=False, + substrs=['0x000000030000000200000001']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/main.cpp new file mode 100644 index 00000000000..334369576a4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/main.cpp @@ -0,0 +1,16 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +bool bar(int const *foo) { + return foo != 0; // Set break point at this line. +} + +int main() { + int foo[] = {1,2,3}; + return bar(foo); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py new file mode 100644 index 00000000000..5f908f76b0a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py @@ -0,0 +1,289 @@ +""" +Test lldb data formatter subsystem. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PythonSynthDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser + def test_with_run_command(self): + """Test data formatter commands.""" + self.build() + self.data_formatter_commands() + + def test_rdar10960550_with_run_command(self): + """Test data formatter commands.""" + self.build() + self.rdar10960550_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + self.line2 = line_number('main.cpp', + '// Set cast break point at this line.') + self.line3 = line_number( + 'main.cpp', '// Set second cast break point at this line.') + + def data_formatter_commands(self): + """Test using Python synthetic children provider.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + process = self.dbg.GetSelectedTarget().GetProcess() + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # print the f00_1 variable without a synth + self.expect("frame variable f00_1", + substrs=['a = 1', + 'b = 2', + 'r = 34']) + + # now set up the synth + self.runCmd("script from fooSynthProvider import *") + self.runCmd("type synth add -l fooSynthProvider foo") + self.expect("type synthetic list foo", substrs=['fooSynthProvider']) + + # note that the value of fake_a depends on target byte order + if process.GetByteOrder() == lldb.eByteOrderLittle: + fake_a_val = 0x02000000 + else: + fake_a_val = 0x00000100 + + # check that we get the two real vars and the fake_a variables + self.expect("frame variable f00_1", + substrs=['r = 34', + 'fake_a = %d' % fake_a_val, + 'a = 1']) + + # check that we do not get the extra vars + self.expect("frame variable f00_1", matching=False, + substrs=['b = 2']) + + # check access to members by name + self.expect('frame variable f00_1.fake_a', + substrs=['%d' % fake_a_val]) + + # check access to members by index + self.expect('frame variable f00_1[1]', + substrs=['%d' % fake_a_val]) + + # put synthetic children in summary in several combinations + self.runCmd( + "type summary add --summary-string \"fake_a=${svar.fake_a}\" foo") + self.expect('frame variable f00_1', + substrs=['fake_a=%d' % fake_a_val]) + self.runCmd( + "type summary add --summary-string \"fake_a=${svar[1]}\" foo") + self.expect('frame variable f00_1', + substrs=['fake_a=%d' % fake_a_val]) + + # clear the summary + self.runCmd("type summary delete foo") + + # check that the caching does not span beyond the stopoint + self.runCmd("n") + + if process.GetByteOrder() == lldb.eByteOrderLittle: + fake_a_val = 0x02000000 + else: + fake_a_val = 0x00000200 + + self.expect("frame variable f00_1", + substrs=['r = 34', + 'fake_a = %d' % fake_a_val, + 'a = 2']) + + # check that altering the object also alters fake_a + self.runCmd("expr f00_1.a = 280") + + if process.GetByteOrder() == lldb.eByteOrderLittle: + fake_a_val = 0x02000001 + else: + fake_a_val = 0x00011800 + + self.expect("frame variable f00_1", + substrs=['r = 34', + 'fake_a = %d' % fake_a_val, + 'a = 280']) + + # check that expanding a pointer does the right thing + if process.GetByteOrder() == lldb.eByteOrderLittle: + fake_a_val = 0x0d000000 + else: + fake_a_val = 0x00000c00 + + self.expect("frame variable --ptr-depth 1 f00_ptr", + substrs=['r = 45', + 'fake_a = %d' % fake_a_val, + 'a = 12']) + + # now add a filter.. it should fail + self.expect("type filter add foo --child b --child j", error=True, + substrs=['cannot add']) + + # we get the synth again.. + self.expect('frame variable f00_1', matching=False, + substrs=['b = 1', + 'j = 17']) + self.expect("frame variable --ptr-depth 1 f00_ptr", + substrs=['r = 45', + 'fake_a = %d' % fake_a_val, + 'a = 12']) + + # now delete the synth and add the filter + self.runCmd("type synth delete foo") + self.runCmd("type filter add foo --child b --child j") + + self.expect('frame variable f00_1', + substrs=['b = 2', + 'j = 18']) + self.expect("frame variable --ptr-depth 1 f00_ptr", matching=False, + substrs=['r = 45', + 'fake_a = %d' % fake_a_val, + 'a = 12']) + + # now add the synth and it should fail + self.expect("type synth add -l fooSynthProvider foo", error=True, + substrs=['cannot add']) + + # check the listing + self.expect('type synth list', matching=False, + substrs=['foo', + 'Python class fooSynthProvider']) + self.expect('type filter list', + substrs=['foo', + '.b', + '.j']) + + # delete the filter, add the synth + self.runCmd("type filter delete foo") + self.runCmd("type synth add -l fooSynthProvider foo") + + self.expect('frame variable f00_1', matching=False, + substrs=['b = 2', + 'j = 18']) + self.expect("frame variable --ptr-depth 1 f00_ptr", + substrs=['r = 45', + 'fake_a = %d' % fake_a_val, + 'a = 12']) + + # check the listing + self.expect('type synth list', + substrs=['foo', + 'Python class fooSynthProvider']) + self.expect('type filter list', matching=False, + substrs=['foo', + '.b', + '.j']) + + # delete the synth and check that we get good output + self.runCmd("type synth delete foo") + + self.expect("frame variable f00_1", + substrs=['a = 280', + 'b = 2', + 'j = 18']) + + self.expect("frame variable f00_1", matching=False, + substrs=['fake_a = ']) + + def rdar10960550_formatter_commands(self): + """Test that synthetic children persist stoppoints.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + # The second breakpoint is on a multi-line expression, so the comment + # can't be on the right line... + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line2, num_expected_locations=1, loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line3, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("command script import ./ftsp.py --allow-reload") + self.runCmd("type synth add -l ftsp.ftsp wrapint") + + # we need to check that the VO is properly updated so that the same synthetic children are reused + # but their values change correctly across stop-points - in order to do this, self.runCmd("next") + # does not work because it forces a wipe of the stack frame - this is why we are using this more contrived + # mechanism to achieve our goal of preserving test_cast as a VO + test_cast = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('test_cast') + + str_cast = str(test_cast) + + if self.TraceOn(): + print(str_cast) + + self.assertTrue(str_cast.find('A') != -1, 'could not find A in output') + self.assertTrue(str_cast.find('B') != -1, 'could not find B in output') + self.assertTrue(str_cast.find('C') != -1, 'could not find C in output') + self.assertTrue(str_cast.find('D') != -1, 'could not find D in output') + self.assertTrue( + str_cast.find("4 = '\\0'") != -1, + 'could not find item 4 == 0') + + self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().StepOver() + + str_cast = str(test_cast) + + if self.TraceOn(): + print(str_cast) + + # we detect that all the values of the child objects have changed - but the counter-generated item + # is still fixed at 0 because it is cached - this would fail if update(self): in ftsp returned False + # or if synthetic children were not being preserved + self.assertTrue(str_cast.find('Q') != -1, 'could not find Q in output') + self.assertTrue(str_cast.find('X') != -1, 'could not find X in output') + self.assertTrue(str_cast.find('T') != -1, 'could not find T in output') + self.assertTrue(str_cast.find('F') != -1, 'could not find F in output') + self.assertTrue( + str_cast.find("4 = '\\0'") != -1, + 'could not find item 4 == 0') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py new file mode 100644 index 00000000000..45fb00468e0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py @@ -0,0 +1,30 @@ +import lldb + + +class fooSynthProvider: + + def __init__(self, valobj, dict): + self.valobj = valobj + self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) + + def num_children(self): + return 3 + + def get_child_at_index(self, index): + if index == 0: + child = self.valobj.GetChildMemberWithName('a') + if index == 1: + child = self.valobj.CreateChildAtOffset('fake_a', 1, self.int_type) + if index == 2: + child = self.valobj.GetChildMemberWithName('r') + return child + + def get_child_index(self, name): + if name == 'a': + return 0 + if name == 'fake_a': + return 1 + return 2 + + def update(self): + return True diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py new file mode 100644 index 00000000000..b96dbac6f50 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py @@ -0,0 +1,40 @@ +import lldb + +counter = 0 + + +class ftsp: + + def __init__(self, valobj, dict): + self.valobj = valobj + + def num_children(self): + if self.char.IsValid(): + return 5 + return 0 + + def get_child_index(self, name): + return 0 + + def get_child_at_index(self, index): + if index == 0: + return self.x.Cast(self.char) + if index == 4: + return self.valobj.CreateValueFromExpression( + str(index), '(char)(' + str(self.count) + ')') + return self.x.CreateChildAtOffset(str(index), + index, + self.char) + + def update(self): + self.x = self.valobj.GetChildMemberWithName('x') + self.char = self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar) + global counter + self.count = counter + counter = counter + 1 + return True # important: if we return False here, or fail to return, the test will fail + + +def __lldb_init_module(debugger, dict): + global counter + counter = 0 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/main.cpp new file mode 100644 index 00000000000..f45a2abfb9f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/main.cpp @@ -0,0 +1,66 @@ +struct foo +{ + int a; + int b; + int c; + int d; + int e; + int f; + int g; + int h; + int i; + int j; + int k; + int l; + int m; + int n; + int o; + int p; + int q; + int r; + + foo(int X) : + a(X), + b(X+1), + c(X+3), + d(X+5), + e(X+7), + f(X+9), + g(X+11), + h(X+13), + i(X+15), + j(X+17), + k(X+19), + l(X+21), + m(X+23), + n(X+25), + o(X+27), + p(X+29), + q(X+31), + r(X+33) {} +}; + +struct wrapint +{ + int x; + wrapint(int X) : x(X) {} +}; + +int main() +{ + foo f00_1(1); + foo *f00_ptr = new foo(12); + + f00_1.a++; // Set break point at this line. + + wrapint test_cast('A' + + 256*'B' + + 256*256*'C'+ + 256*256*256*'D'); + // Set cast break point at this line. + test_cast.x = 'Q' + + 256*'X' + + 256*256*'T'+ + 256*256*256*'F'; + return 0; // Set second cast break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py new file mode 100644 index 00000000000..14387cde194 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py @@ -0,0 +1,182 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class ScriptDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """Test data formatter commands.""" + self.build() + self.data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def data_formatter_commands(self): + """Test that that file and class static variables display correctly.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Set the script here to ease the formatting + script = 'a = valobj.GetChildMemberWithName(\'integer\'); a_val = a.GetValue(); str = \'Hello from Python, \' + a_val + \' time\'; return str + (\'!\' if a_val == \'1\' else \'s!\');' + + self.runCmd( + "type summary add i_am_cool --python-script \"%s\"" % + script) + self.expect('type summary list i_am_cool', substrs=[script]) + + self.expect("frame variable one", + substrs=['Hello from Python', + '1 time!']) + + self.expect("frame variable two", + substrs=['Hello from Python', + '4 times!']) + + self.runCmd("n") # skip ahead to make values change + + self.expect("frame variable three", + substrs=['Hello from Python, 10 times!', + 'Hello from Python, 4 times!']) + + self.runCmd("n") # skip ahead to make values change + + self.expect("frame variable two", + substrs=['Hello from Python', + '1 time!']) + + script = 'a = valobj.GetChildMemberWithName(\'integer\'); a_val = a.GetValue(); str = \'int says \' + a_val; return str;' + + # Check that changes in the script are immediately reflected + self.runCmd( + "type summary add i_am_cool --python-script \"%s\"" % + script) + + self.expect("frame variable two", + substrs=['int says 1']) + + self.expect("frame variable twoptr", + substrs=['int says 1']) + + # Change the summary + self.runCmd( + "type summary add --summary-string \"int says ${var.integer}, and float says ${var.floating}\" i_am_cool") + + self.expect("frame variable two", + substrs=['int says 1', + 'and float says 2.71']) + # Try it for pointers + self.expect("frame variable twoptr", + substrs=['int says 1', + 'and float says 2.71']) + + # Force a failure for pointers + self.runCmd( + "type summary add i_am_cool -p --python-script \"%s\"" % + script) + + self.expect("frame variable twoptr", matching=False, + substrs=['and float says 2.71']) + + script = 'return \'Python summary\'' + + self.runCmd( + "type summary add --name test_summary --python-script \"%s\"" % + script) + + # attach the Python named summary to someone + self.expect("frame variable one --summary test_summary", + substrs=['Python summary']) + + # should not bind to the type + self.expect("frame variable two", matching=False, + substrs=['Python summary']) + + # and should not stick to the variable + self.expect("frame variable one", matching=False, + substrs=['Python summary']) + + self.runCmd( + "type summary add i_am_cool --summary-string \"Text summary\"") + + # should be temporary only + self.expect("frame variable one", matching=False, + substrs=['Python summary']) + + # use the type summary + self.expect("frame variable two", + substrs=['Text summary']) + + self.runCmd("n") # skip ahead to make values change + + # both should use the type summary now + self.expect("frame variable one", + substrs=['Text summary']) + + self.expect("frame variable two", + substrs=['Text summary']) + + # disable type summary for pointers, and make a Python regex summary + self.runCmd( + "type summary add i_am_cool -p --summary-string \"Text summary\"") + self.runCmd("type summary add -x cool --python-script \"%s\"" % script) + + # variables should stick to the type summary + self.expect("frame variable one", + substrs=['Text summary']) + + self.expect("frame variable two", + substrs=['Text summary']) + + # array and pointer should match the Python one + self.expect("frame variable twoptr", + substrs=['Python summary']) + + self.expect("frame variable array", + substrs=['Python summary']) + + # return pointers to the type summary + self.runCmd( + "type summary add i_am_cool --summary-string \"Text summary\"") + + self.expect("frame variable one", + substrs=['Text summary']) + + self.expect("frame variable two", + substrs=['Text summary']) + + self.expect("frame variable twoptr", + substrs=['Text summary']) + + self.expect("frame variable array", + substrs=['Python summary']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/main.cpp new file mode 100644 index 00000000000..db60981d88c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/main.cpp @@ -0,0 +1,52 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> + +struct i_am_cool +{ + int integer; + float floating; + char character; + i_am_cool(int I, float F, char C) : + integer(I), floating(F), character(C) {} + i_am_cool() : integer(1), floating(2), character('3') {} + +}; + +struct i_am_cooler +{ + i_am_cool first_cool; + i_am_cool second_cool; + float floating; + + i_am_cooler(int I1, int I2, float F1, float F2, char C1, char C2) : + first_cool(I1,F1,C1), + second_cool(I2,F2,C2), + floating((F1 + F2)/2) {} +}; + +int main (int argc, const char * argv[]) +{ + i_am_cool one(1,3.14,'E'); + i_am_cool two(4,2.71,'G'); + + i_am_cool* twoptr = &two; + + i_am_cool array[5]; + + i_am_cooler three(10,4,1985,1/1/2011,'B','E'); // Set break point at this line. + + two.integer = 1; + + int dummy = 1; + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/Makefile new file mode 100644 index 00000000000..6bfb97cd2c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/Makefile @@ -0,0 +1,7 @@ +CXX_SOURCES := main.cpp +USE_LIBSTDCPP := 0 + + + +CXXFLAGS_EXTRAS := -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py new file mode 100644 index 00000000000..fa13e922ce4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py @@ -0,0 +1,184 @@ +""" +Test lldb data formatter subsystem. +""" + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SkipSummaryDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr20548 fails to build on lab.llvm.org buildbot") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24462, Data formatters have problems on Windows") + def test_with_run_command(self): + """Test data formatter commands.""" + self.build() + self.data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def data_formatter_commands(self): + """Test that that file and class static variables display correctly.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + #import lldbsuite.test.lldbutil as lldbutil + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Setup the summaries for this scenario + #self.runCmd("type summary add --summary-string \"${var._M_dataplus._M_p}\" std::string") + self.runCmd( + "type summary add --summary-string \"Level 1\" \"DeepData_1\"") + self.runCmd( + "type summary add --summary-string \"Level 2\" \"DeepData_2\" -e") + self.runCmd( + "type summary add --summary-string \"Level 3\" \"DeepData_3\"") + self.runCmd( + "type summary add --summary-string \"Level 4\" \"DeepData_4\"") + self.runCmd( + "type summary add --summary-string \"Level 5\" \"DeepData_5\"") + + # Default case, just print out summaries + self.expect('frame variable', + substrs=['(DeepData_1) data1 = Level 1', + '(DeepData_2) data2 = Level 2 {', + 'm_child1 = Level 3', + 'm_child2 = Level 3', + 'm_child3 = Level 3', + 'm_child4 = Level 3', + '}']) + + # Skip the default (should be 1) levels of summaries + self.expect('frame variable --no-summary-depth', + substrs=['(DeepData_1) data1 = {', + 'm_child1 = 0x', + '}', + '(DeepData_2) data2 = {', + 'm_child1 = Level 3', + 'm_child2 = Level 3', + 'm_child3 = Level 3', + 'm_child4 = Level 3', + '}']) + + # Now skip 2 levels of summaries + self.expect('frame variable --no-summary-depth=2', + substrs=['(DeepData_1) data1 = {', + 'm_child1 = 0x', + '}', + '(DeepData_2) data2 = {', + 'm_child1 = {', + 'm_child1 = 0x', + 'Level 4', + 'm_child2 = {', + 'm_child3 = {', + '}']) + + # Check that no "Level 3" comes out + self.expect( + 'frame variable data1.m_child1 --no-summary-depth=2', + matching=False, + substrs=['Level 3']) + + # Now expand a pointer with 2 level of skipped summaries + self.expect('frame variable data1.m_child1 --no-summary-depth=2', + substrs=['(DeepData_2 *) data1.m_child1 = 0x']) + + # Deref and expand said pointer + self.expect('frame variable *data1.m_child1 --no-summary-depth=2', + substrs=['(DeepData_2) *data1.m_child1 = {', + 'm_child2 = {', + 'm_child1 = 0x', + 'Level 4', + '}']) + + # Expand an expression, skipping 2 layers of summaries + self.expect( + 'frame variable data1.m_child1->m_child2 --no-summary-depth=2', + substrs=[ + '(DeepData_3) data1.m_child1->m_child2 = {', + 'm_child2 = {', + 'm_child1 = Level 5', + 'm_child2 = Level 5', + 'm_child3 = Level 5', + '}']) + + # Expand same expression, skipping only 1 layer of summaries + self.expect( + 'frame variable data1.m_child1->m_child2 --no-summary-depth=1', + substrs=[ + '(DeepData_3) data1.m_child1->m_child2 = {', + 'm_child1 = 0x', + 'Level 4', + 'm_child2 = Level 4', + '}']) + + # Bad debugging info on SnowLeopard gcc (Apple Inc. build 5666). + # Skip the following tests if the condition is met. + if self.getCompiler().endswith('gcc') and not self.getCompiler().endswith('llvm-gcc'): + import re + gcc_version_output = system( + [[lldbutil.which(self.getCompiler()), "-v"]])[1] + #print("my output:", gcc_version_output) + for line in gcc_version_output.split(os.linesep): + m = re.search('\(Apple Inc\. build ([0-9]+)\)', line) + #print("line:", line) + if m: + gcc_build = int(m.group(1)) + #print("gcc build:", gcc_build) + if gcc_build >= 5666: + # rdar://problem/9804600" + self.skipTest( + "rdar://problem/9804600 wrong namespace for std::string in debug info") + + # Expand same expression, skipping 3 layers of summaries + self.expect( + 'frame variable data1.m_child1->m_child2 --show-types --no-summary-depth=3', + substrs=[ + '(DeepData_3) data1.m_child1->m_child2 = {', + 'm_some_text = "Just a test"', + 'm_child2 = {', + 'm_some_text = "Just a test"']) + + # Change summary and expand, first without --no-summary-depth then with + # --no-summary-depth + self.runCmd( + "type summary add --summary-string \"${var.m_some_text}\" DeepData_5") + + self.expect('fr var data2.m_child4.m_child2.m_child2', substrs=[ + '(DeepData_5) data2.m_child4.m_child2.m_child2 = "Just a test"']) + + self.expect( + 'fr var data2.m_child4.m_child2.m_child2 --no-summary-depth', + substrs=[ + '(DeepData_5) data2.m_child4.m_child2.m_child2 = {', + 'm_some_text = "Just a test"', + '}']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/main.cpp new file mode 100644 index 00000000000..665c9fe75d1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/main.cpp @@ -0,0 +1,57 @@ +#include <string> + +struct DeepData_5 +{ + std::string m_some_text; + DeepData_5() : + m_some_text("Just a test") {} +}; + +struct DeepData_4 +{ + DeepData_5 m_child1; + DeepData_5 m_child2; + DeepData_5 m_child3; +}; + +struct DeepData_3 +{ + DeepData_4& m_child1; + DeepData_4 m_child2; + + DeepData_3() : m_child1(* (new DeepData_4())), m_child2(DeepData_4()) {} +}; + +struct DeepData_2 +{ + DeepData_3 m_child1; + DeepData_3 m_child2; + DeepData_3 m_child3; + DeepData_3 m_child4; +}; + +struct DeepData_1 +{ + DeepData_2 *m_child1; + + DeepData_1() : + m_child1(new DeepData_2()) + {} +}; + +/* + type summary add -f "${var._M_dataplus._M_p}" std::string + type summary add -f "Level 1" "DeepData_1" + type summary add -f "Level 2" "DeepData_2" -e + type summary add -f "Level 3" "DeepData_3" + type summary add -f "Level 4" "DeepData_4" + type summary add -f "Level 5" "DeepData_5" + */ + +int main() +{ + DeepData_1 data1; + DeepData_2 data2; + + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py new file mode 100644 index 00000000000..0f98eb34825 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py @@ -0,0 +1,453 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SmartArrayDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """Test data formatter commands.""" + self.build() + self.data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def data_formatter_commands(self): + """Test that that file and class static variables display correctly.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + process = self.dbg.GetSelectedTarget().GetProcess() + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + +# check that we are not looping here + self.runCmd("type summary add --summary-string \"${var%V}\" SomeData") + + self.expect("frame variable data", + substrs=['SomeData @ 0x']) +# ${var%s} + self.runCmd( + "type summary add --summary-string \"ptr = ${var%s}\" \"char *\"") + + self.expect("frame variable strptr", + substrs=['ptr = \"', + 'Hello world!']) + + self.expect("frame variable other.strptr", + substrs=['ptr = \"', + 'Nested Hello world!']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\"") + + self.expect("frame variable strarr", + substrs=['arr = \"', + 'Hello world!']) + + self.expect("frame variable other.strarr", + substrs=['arr = \"', + 'Nested Hello world!']) + + self.expect("p strarr", + substrs=['arr = \"', + 'Hello world!']) + + self.expect("p other.strarr", + substrs=['arr = \"', + 'Nested Hello world!']) + +# ${var%c} + self.runCmd( + "type summary add --summary-string \"ptr = ${var%c}\" \"char *\"") + + self.expect("frame variable strptr", + substrs=['ptr = \"', + 'Hello world!']) + + self.expect("frame variable other.strptr", + substrs=['ptr = \"', + 'Nested Hello world!']) + + self.expect("p strptr", + substrs=['ptr = \"', + 'Hello world!']) + + self.expect("p other.strptr", + substrs=['ptr = \"', + 'Nested Hello world!']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var%c}\" -x \"char \\[[0-9]+\\]\"") + + self.expect("frame variable strarr", + substrs=['arr = \"', + 'Hello world!']) + + self.expect("frame variable other.strarr", + substrs=['arr = \"', + 'Nested Hello world!']) + + self.expect("p strarr", + substrs=['arr = \"', + 'Hello world!']) + + self.expect("p other.strarr", + substrs=['arr = \"', + 'Nested Hello world!']) + +# ${var%char[]} + self.runCmd( + "type summary add --summary-string \"arr = ${var%char[]}\" -x \"char \\[[0-9]+\\]\"") + + self.expect("frame variable strarr", + substrs=['arr = \"', + 'Hello world!']) + + self.expect("frame variable other.strarr", + substrs=['arr = ', + 'Nested Hello world!']) + + self.expect("p strarr", + substrs=['arr = \"', + 'Hello world!']) + + self.expect("p other.strarr", + substrs=['arr = ', + 'Nested Hello world!']) + + self.runCmd( + "type summary add --summary-string \"ptr = ${var%char[]}\" \"char *\"") + + self.expect("frame variable strptr", + substrs=['ptr = \"', + 'Hello world!']) + + self.expect("frame variable other.strptr", + substrs=['ptr = \"', + 'Nested Hello world!']) + + self.expect("p strptr", + substrs=['ptr = \"', + 'Hello world!']) + + self.expect("p other.strptr", + substrs=['ptr = \"', + 'Nested Hello world!']) + +# ${var%a} + self.runCmd( + "type summary add --summary-string \"arr = ${var%a}\" -x \"char \\[[0-9]+\\]\"") + + self.expect("frame variable strarr", + substrs=['arr = \"', + 'Hello world!']) + + self.expect("frame variable other.strarr", + substrs=['arr = ', + 'Nested Hello world!']) + + self.expect("p strarr", + substrs=['arr = \"', + 'Hello world!']) + + self.expect("p other.strarr", + substrs=['arr = ', + 'Nested Hello world!']) + + self.runCmd( + "type summary add --summary-string \"ptr = ${var%a}\" \"char *\"") + + self.expect("frame variable strptr", + substrs=['ptr = \"', + 'Hello world!']) + + self.expect("frame variable other.strptr", + substrs=['ptr = \"', + 'Nested Hello world!']) + + self.expect("p strptr", + substrs=['ptr = \"', + 'Hello world!']) + + self.expect("p other.strptr", + substrs=['ptr = \"', + 'Nested Hello world!']) + + self.runCmd( + "type summary add --summary-string \"ptr = ${var[]%char[]}\" \"char *\"") + +# I do not know the size of the data, but you are asking for a full array slice.. +# use the ${var%char[]} to obtain a string as result + self.expect("frame variable strptr", matching=False, + substrs=['ptr = \"', + 'Hello world!']) + + self.expect("frame variable other.strptr", matching=False, + substrs=['ptr = \"', + 'Nested Hello world!']) + + self.expect("p strptr", matching=False, + substrs=['ptr = \"', + 'Hello world!']) + + self.expect("p other.strptr", matching=False, + substrs=['ptr = \"', + 'Nested Hello world!']) + +# You asked an array-style printout... + self.runCmd( + "type summary add --summary-string \"ptr = ${var[0-1]%char[]}\" \"char *\"") + + self.expect("frame variable strptr", + substrs=['ptr = ', + '[{H},{e}]']) + + self.expect("frame variable other.strptr", + substrs=['ptr = ', + '[{N},{e}]']) + + self.expect("p strptr", + substrs=['ptr = ', + '[{H},{e}]']) + + self.expect("p other.strptr", + substrs=['ptr = ', + '[{N},{e}]']) + +# using [] is required here + self.runCmd( + "type summary add --summary-string \"arr = ${var%x}\" \"int [5]\"") + + self.expect("frame variable intarr", matching=False, substrs=[ + '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + + self.expect("frame variable other.intarr", matching=False, substrs=[ + '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var[]%x}\" \"int [5]\"") + + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr =', + '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) + +# printing each array item as an array + self.runCmd( + "type summary add --summary-string \"arr = ${var[]%uint32_t[]}\" \"int [5]\"") + + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '{0x00000001},{0x00000001},{0x00000002},{0x00000003},{0x00000005}']) + + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr = ', + '{0x00000009},{0x00000008},{0x00000007},{0x00000006},{0x00000005}']) + +# printing full array as an array + self.runCmd( + "type summary add --summary-string \"arr = ${var%uint32_t[]}\" \"int [5]\"") + + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005']) + + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr =', + '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005']) + +# printing each array item as an array + self.runCmd( + "type summary add --summary-string \"arr = ${var[]%float32[]}\" \"float [7]\"") + + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '{78.5},{77.25},{78},{76.125},{76.75},{76.875},{77}']) + + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr = ', + '{25.5},{25.25},{25.125},{26.75},{27.375},{27.5},{26.125}']) + +# printing full array as an array + self.runCmd( + "type summary add --summary-string \"arr = ${var%float32[]}\" \"float [7]\"") + + self.expect("frame variable flarr", + substrs=['flarr = arr =', + '78.5,77.25,78,76.125,76.75,76.875,77']) + + self.expect("frame variable other.flarr", + substrs=['flarr = arr =', + '25.5,25.25,25.125,26.75,27.375,27.5,26.125']) + +# using array smart summary strings for pointers should make no sense + self.runCmd( + "type summary add --summary-string \"arr = ${var%float32[]}\" \"float *\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%int32_t[]}\" \"int *\"") + + self.expect("frame variable flptr", matching=False, + substrs=['78.5,77.25,78,76.125,76.75,76.875,77']) + + self.expect("frame variable intptr", matching=False, + substrs=['1,1,2,3,5']) + +# use y and Y + self.runCmd( + "type summary add --summary-string \"arr = ${var%y}\" \"float [7]\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%y}\" \"int [5]\"") + + if process.GetByteOrder() == lldb.eByteOrderLittle: + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '00 00 9d 42,00 80 9a 42,00 00 9c 42,00 40 98 42,00 80 99 42,00 c0 99 42,00 00 9a 42']) + else: + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '42 9d 00 00,42 9a 80 00,42 9c 00 00,42 98 40 00,42 99 80 00,42 99 c0 00,42 9a 00 00']) + + if process.GetByteOrder() == lldb.eByteOrderLittle: + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr =', + '00 00 cc 41,00 00 ca 41,00 00 c9 41,00 00 d6 41,00 00 db 41,00 00 dc 41,00 00 d1 41']) + else: + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr =', + '41 cc 00 00,41 ca 00 00,41 c9 00 00,41 d6 00 00,41 db 00 00,41 dc 00 00,41 d1 00 00']) + + if process.GetByteOrder() == lldb.eByteOrderLittle: + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '01 00 00 00,01 00 00 00,02 00 00 00,03 00 00 00,05 00 00 00']) + else: + self.expect( + "frame variable intarr", + substrs=[ + 'intarr = arr =', + '00 00 00 01,00 00 00 01,00 00 00 02,00 00 00 03,00 00 00 05']) + + if process.GetByteOrder() == lldb.eByteOrderLittle: + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr = ', + '09 00 00 00,08 00 00 00,07 00 00 00,06 00 00 00,05 00 00 00']) + else: + self.expect( + "frame variable other.intarr", + substrs=[ + 'intarr = arr = ', + '00 00 00 09,00 00 00 08,00 00 00 07,00 00 00 06,00 00 00 05']) + + self.runCmd( + "type summary add --summary-string \"arr = ${var%Y}\" \"float [7]\"") + self.runCmd( + "type summary add --summary-string \"arr = ${var%Y}\" \"int [5]\"") + + if process.GetByteOrder() == lldb.eByteOrderLittle: + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '00 00 9d 42', '00 80 9a 42', '00 00 9c 42', '00 40 98 42', '00 80 99 42', '00 c0 99 42', '00 00 9a 42']) + else: + self.expect( + "frame variable flarr", + substrs=[ + 'flarr = arr =', + '42 9d 00 00', '42 9a 80 00', '42 9c 00 00', '42 98 40 00', '42 99 80 00', '42 99 c0 00', '42 9a 00 00']) + + if process.GetByteOrder() == lldb.eByteOrderLittle: + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr =', + '00 00 cc 41', '00 00 ca 41', '00 00 c9 41', '00 00 d6 41', '00 00 db 41', '00 00 dc 41', '00 00 d1 41']) + else: + self.expect( + "frame variable other.flarr", + substrs=[ + 'flarr = arr =', + '41 cc 00 00', '41 ca 00 00', '41 c9 00 00', '41 d6 00 00', '41 db 00 00', '41 dc 00 00', '41 d1 00 00']) + + if process.GetByteOrder() == lldb.eByteOrderLittle: + self.expect("frame variable intarr", + substrs=['intarr = arr =', + '....,01 00 00 00', + '....,05 00 00 00']) + else: + self.expect("frame variable intarr", + substrs=['intarr = arr =', + '....,00 00 00 01', + '....,00 00 00 05']) + + if process.GetByteOrder() == lldb.eByteOrderLittle: + self.expect("frame variable other.intarr", + substrs=['intarr = arr = ', + '09 00 00 00', + '....,07 00 00 00']) + else: + self.expect("frame variable other.intarr", + substrs=['intarr = arr = ', + '00 00 00 09', + '....,00 00 00 07']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/main.cpp new file mode 100644 index 00000000000..b9a517d8ceb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/main.cpp @@ -0,0 +1,64 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> +#include <string.h> + +struct SomeData +{ + int x; +}; + +struct SomeOtherData +{ + char strarr[32]; + char *strptr; + int intarr[5]; + float flarr[7]; + + SomeOtherData() + { + strcpy(strarr,"Nested Hello world!"); + strptr = new char[128]; + strcpy(strptr,"Nested Hello world!"); + intarr[0] = 9; + intarr[1] = 8; + intarr[2] = 7; + intarr[3] = 6; + intarr[4] = 5; + + flarr[0] = 25.5; + flarr[1] = 25.25; + flarr[2] = 25.125; + flarr[3] = 26.75; + flarr[4] = 27.375; + flarr[5] = 27.5; + flarr[6] = 26.125; + } +}; + +int main (int argc, const char * argv[]) +{ + char strarr[32] = "Hello world!"; + char *strptr = NULL; + strptr = "Hello world!"; + int intarr[5] = {1,1,2,3,5}; + float flarr[7] = {78.5,77.25,78.0,76.125,76.75,76.875,77.0}; + + SomeData data; + + SomeOtherData other; + + float* flptr = flarr; + int* intptr = intarr; + + return 0; // Set break point at this line. + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/Makefile new file mode 100644 index 00000000000..b016f006747 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp +CXXFLAGS_EXTRAS := -std=c++11 +USE_LIBCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py new file mode 100644 index 00000000000..48e77c1a885 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/TestLibCxxAtomic.py @@ -0,0 +1,60 @@ +""" +Test lldb data formatter subsystem. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibCxxAtomicTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def get_variable(self, name): + var = self.frame().FindVariable(name) + var.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + var.SetPreferSyntheticValue(True) + return var + + @skipIf(compiler=["gcc"]) + @add_test_categories(["libc++"]) + def test(self): + """Test that std::atomic as defined by libc++ is correctly printed by LLDB""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) + + self.runCmd("run", RUN_SUCCEEDED) + + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + s = self.get_variable('s') + i = self.get_variable('i') + + if self.TraceOn(): + print(s) + if self.TraceOn(): + print(i) + + self.assertTrue(i.GetValueAsUnsigned(0) == 5, "i == 5") + self.assertTrue(s.GetNumChildren() == 2, "s has two children") + self.assertTrue( + s.GetChildAtIndex(0).GetValueAsUnsigned(0) == 1, + "s.x == 1") + self.assertTrue( + s.GetChildAtIndex(1).GetValueAsUnsigned(0) == 2, + "s.y == 2") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/main.cpp new file mode 100644 index 00000000000..516331efdde --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/atomic/main.cpp @@ -0,0 +1,25 @@ +//===-- main.cpp --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <atomic> + +struct S { + int x = 1; + int y = 2; +}; + +int main () +{ + std::atomic<S> s; + s.store(S()); + std::atomic<int> i; + i.store(5); + + return 0; // Set break point at this line. +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/bitset/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/bitset/Makefile new file mode 100644 index 00000000000..680e1abfbef --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/bitset/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/bitset/TestDataFormatterLibcxxBitset.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/bitset/TestDataFormatterLibcxxBitset.py new file mode 100644 index 00000000000..26f1972257b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/bitset/TestDataFormatterLibcxxBitset.py @@ -0,0 +1,61 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDataFormatterLibcxxBitset(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + + primes = [1]*300 + primes[0] = primes[1] = 0 + for i in range(2, len(primes)): + for j in range(2*i, len(primes), i): + primes[j] = 0 + self.primes = primes + + def check(self, name, size): + var = self.frame().FindVariable(name) + self.assertTrue(var.IsValid()) + self.assertEqual(var.GetNumChildren(), size) + for i in range(size): + child = var.GetChildAtIndex(i) + self.assertEqual(child.GetValueAsUnsigned(), self.primes[i], + "variable: %s, index: %d"%(name, size)) + + @add_test_categories(["libc++"]) + def test_value(self): + """Test that std::bitset is displayed correctly""" + self.build() + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + self.check("empty", 0) + self.check("small", 13) + self.check("large", 200) + + @add_test_categories(["libc++"]) + def test_ptr_and_ref(self): + """Test that ref and ptr to std::bitset is displayed correctly""" + self.build() + (_, process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, + 'Check ref and ptr', + lldb.SBFileSpec("main.cpp", False)) + + self.check("ref", 13) + self.check("ptr", 13) + + lldbutil.continue_to_breakpoint(process, bkpt) + + self.check("ref", 200) + self.check("ptr", 200) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/bitset/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/bitset/main.cpp new file mode 100644 index 00000000000..2a1532adb4b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/bitset/main.cpp @@ -0,0 +1,29 @@ +#include <bitset> +#include <stdio.h> + +template<std::size_t N> +void fill(std::bitset<N> &b) { + b.set(); + b[0] = b[1] = false; + for (std::size_t i = 2; i < N; ++i) { + for (std::size_t j = 2*i; j < N; j+=i) + b[j] = false; + } +} + +template<std::size_t N> +void by_ref_and_ptr(std::bitset<N> &ref, std::bitset<N> *ptr) { + // Check ref and ptr + return; +} + +int main() { + std::bitset<0> empty; + std::bitset<13> small; + fill(small); + std::bitset<200> large; + fill(large); + by_ref_and_ptr(small, &small); // break here + by_ref_and_ptr(large, &large); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/forward_list/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/forward_list/Makefile new file mode 100644 index 00000000000..680e1abfbef --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/forward_list/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/forward_list/TestDataFormatterLibcxxForwardList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/forward_list/TestDataFormatterLibcxxForwardList.py new file mode 100644 index 00000000000..a9983dd045e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/forward_list/TestDataFormatterLibcxxForwardList.py @@ -0,0 +1,52 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDataFormatterLibcxxForwardList(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.line = line_number('main.cpp', '// break here') + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + @add_test_categories(["libc++"]) + def test(self): + """Test that std::forward_list is displayed correctly""" + self.build() + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + forward_list = self.namespace + '::forward_list' + self.expect("frame variable empty", + substrs=[forward_list, + 'size=0', + '{}']) + + self.expect("frame variable one_elt", + substrs=[forward_list, + 'size=1', + '{', + '[0] = 47', + '}']) + + self.expect("frame variable five_elts", + substrs=[forward_list, + 'size=5', + '{', + '[0] = 1', + '[1] = 22', + '[2] = 333', + '[3] = 4444', + '[4] = 55555', + '}']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/forward_list/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/forward_list/main.cpp new file mode 100644 index 00000000000..73abda6e82e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/forward_list/main.cpp @@ -0,0 +1,7 @@ +#include <forward_list> + +int main() +{ + std::forward_list<int> empty{}, one_elt{47}, five_elts{1,22,333,4444,55555}; + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/Makefile new file mode 100644 index 00000000000..b016f006747 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp +CXXFLAGS_EXTRAS := -std=c++11 +USE_LIBCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py new file mode 100644 index 00000000000..9f0d3e431a3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/TestLibCxxFunction.py @@ -0,0 +1,72 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibCxxFunctionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # Run frame var for a variable twice. Verify we do not hit the cache + # the first time but do the second time. + def run_frame_var_check_cache_use(self, variable, result_to_match, skip_find_function=False): + self.runCmd("log timers reset") + self.expect("frame variable " + variable, + substrs=[variable + " = " + result_to_match]) + if not skip_find_function: + self.expect("log timers dump", + substrs=["lldb_private::CompileUnit::FindFunction"]) + + self.runCmd("log timers reset") + self.expect("frame variable " + variable, + substrs=[variable + " = " + result_to_match]) + self.expect("log timers dump", + matching=False, + substrs=["lldb_private::CompileUnit::FindFunction"]) + + + @add_test_categories(["libc++"]) + def test(self): + """Test that std::function as defined by libc++ is correctly printed by LLDB""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.run_frame_var_check_cache_use("foo2_f", "Lambda in File main.cpp at Line 30") + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.run_frame_var_check_cache_use("add_num2_f", "Lambda in File main.cpp at Line 21") + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.run_frame_var_check_cache_use("f2", "Lambda in File main.cpp at Line 43") + self.run_frame_var_check_cache_use("f3", "Lambda in File main.cpp at Line 47", True) + # TODO reenable this case when std::function formatter supports + # general callable object case. + #self.run_frame_var_check_cache_use("f4", "Function in File main.cpp at Line 16") + + # These cases won't hit the cache at all but also don't require + # an expensive lookup. + self.expect("frame variable f1", + substrs=['f1 = Function = foo(int, int)']) + + self.expect("frame variable f5", + substrs=['f5 = Function = Bar::add_num(int) const']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/main.cpp new file mode 100644 index 00000000000..d0c931ddc8b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/function/main.cpp @@ -0,0 +1,59 @@ +//===-- main.cpp --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <functional> + +int foo(int x, int y) { + return x + y - 1; +} + +struct Bar { + int operator()() { + return 66 ; + } + int add_num(int i) const { return i + 3 ; } + int add_num2(int i) { + std::function<int (int)> add_num2_f = [](int x) { + return x+1; + }; + + return add_num2_f(i); // Set break point at this line. + } +} ; + +int foo2() { + auto f = [](int x) { + return x+1; + }; + + std::function<int (int)> foo2_f = f; + + return foo2_f(10); // Set break point at this line. +} + +int main (int argc, char *argv[]) +{ + int acc = 42; + std::function<int (int,int)> f1 = foo; + std::function<int (int)> f2 = [acc,f1] (int x) -> int { + return x+f1(acc,x); + }; + + auto f = [](int x, int y) { return x + y; }; + auto g = [](int x, int y) { return x * y; } ; + std::function<int (int,int)> f3 = argc %2 ? f : g ; + + Bar bar1 ; + std::function<int ()> f4( bar1 ) ; + std::function<int (const Bar&, int)> f5 = &Bar::add_num; + + int foo2_result = foo2(); + int bar_add_num2_result = bar1.add_num2(10); + + return f1(acc,acc) + f2(acc) + f3(acc+1,acc+2) + f4() + f5(bar1, 10); // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/Makefile new file mode 100644 index 00000000000..e78030cbf75 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp +CXXFLAGS_EXTRAS := -std=c++11 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py new file mode 100644 index 00000000000..5fef10e6d3e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py @@ -0,0 +1,45 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class InitializerListTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfWindows # libc++ not ported to Windows yet + @skipIf(compiler="gcc") + @expectedFailureAll( + oslist=["linux"], + bugnumber="fails on clang 3.5 and tot") + def test(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) + + self.runCmd("run", RUN_SUCCEEDED) + + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("frame variable ili", substrs=['[1] = 2', '[4] = 5']) + self.expect("frame variable ils", substrs=[ + '[4] = "surprise it is a long string!! yay!!"']) + + self.expect('image list', substrs=self.getLibcPlusPlusLibs()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/main.cpp new file mode 100644 index 00000000000..6e5fa43a6b9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/main.cpp @@ -0,0 +1,20 @@ +//===-- main.cpp --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <string> +#include <vector> +#include <initializer_list> + +int main () +{ + std::initializer_list<int> ili{1,2,3,4,5}; + std::initializer_list<std::string> ils{"1","2","3","4","surprise it is a long string!! yay!!"}; + + return 0; // Set break point at this line. +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/Makefile new file mode 100644 index 00000000000..564cbada74e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py new file mode 100644 index 00000000000..2ff3d63d004 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py @@ -0,0 +1,73 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxIteratorDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + @add_test_categories(["libc++"]) + def test_with_run_command(self): + """Test that libc++ iterators format properly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_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=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.expect('frame variable ivI', substrs=['item = 3']) + self.expect('expr ivI', substrs=['item = 3']) + + self.expect( + 'frame variable iimI', + substrs=[ + 'first = 43981', + 'second = 61681']) + self.expect('expr iimI', substrs=['first = 43981', 'second = 61681']) + + self.expect( + 'frame variable simI', + substrs=[ + 'first = "world"', + 'second = 42']) + self.expect('expr simI', substrs=['first = "world"', 'second = 42']) + + self.expect('frame variable svI', substrs=['item = "hello"']) + self.expect('expr svI', substrs=['item = "hello"']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/main.cpp new file mode 100644 index 00000000000..9d1cbfd9128 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/main.cpp @@ -0,0 +1,38 @@ +#include <string> +#include <map> +#include <vector> + +typedef std::map<int, int> intint_map; +typedef std::map<std::string, int> strint_map; + +typedef std::vector<int> int_vector; +typedef std::vector<std::string> string_vector; + +typedef intint_map::iterator iimter; +typedef strint_map::iterator simter; + +typedef int_vector::iterator ivter; +typedef string_vector::iterator svter; + +int main() +{ + intint_map iim; + iim[0xABCD] = 0xF0F1; + + strint_map sim; + sim["world"] = 42; + + int_vector iv; + iv.push_back(3); + + string_vector sv; + sv.push_back("hello"); + + iimter iimI = iim.begin(); + simter simI = sim.begin(); + + ivter ivI = iv.begin(); + svter svI = sv.begin(); + + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/Makefile new file mode 100644 index 00000000000..564cbada74e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py new file mode 100644 index 00000000000..3a2d006c7de --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py @@ -0,0 +1,220 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxListDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + self.line2 = line_number('main.cpp', + '// Set second break point at this line.') + self.line3 = line_number('main.cpp', + '// Set third break point at this line.') + self.line4 = line_number('main.cpp', + '// Set fourth break point at this line.') + + @add_test_categories(["libc++"]) + @skipIf(debug_info="gmodules", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=36048") + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line2, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line3, num_expected_locations=-1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line4, num_expected_locations=-1) + + self.runCmd("run", RUN_SUCCEEDED) + + lldbutil.skip_if_library_missing( + self, self.target(), lldbutil.PrintableRegex("libc\+\+")) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("frame variable numbers_list --show-types") + self.runCmd( + "type summary add std::int_list std::string_list int_list string_list --summary-string \"list has ${svar%#} items\" -e") + self.runCmd("type format add -f hex int") + + self.expect("frame variable numbers_list --raw", matching=False, + substrs=['list has 0 items', + '{}']) + + self.expect("frame variable numbers_list", + substrs=['list has 0 items', + '{}']) + + self.expect("p numbers_list", + substrs=['list has 0 items', + '{}']) + + self.runCmd("n") # This gets up past the printf + self.runCmd("n") # Now advance over the first push_back. + + self.expect("frame variable numbers_list", + substrs=['list has 1 items', + '[0] = ', + '0x12345678']) + + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") + + self.expect("frame variable numbers_list", + substrs=['list has 4 items', + '[0] = ', + '0x12345678', + '[1] =', + '0x11223344', + '[2] =', + '0xbeeffeed', + '[3] =', + '0x00abba00']) + + self.runCmd("n") + self.runCmd("n") + + self.expect("frame variable numbers_list", + substrs=['list has 6 items', + '[0] = ', + '0x12345678', + '0x11223344', + '0xbeeffeed', + '0x00abba00', + '[4] =', + '0x0abcdef0', + '[5] =', + '0x0cab0cab']) + + self.expect("p numbers_list", + substrs=['list has 6 items', + '[0] = ', + '0x12345678', + '0x11223344', + '0xbeeffeed', + '0x00abba00', + '[4] =', + '0x0abcdef0', + '[5] =', + '0x0cab0cab']) + + # check access-by-index + self.expect("frame variable numbers_list[0]", + substrs=['0x12345678']) + self.expect("frame variable numbers_list[1]", + substrs=['0x11223344']) + + self.runCmd("n") + + self.expect("frame variable numbers_list", + substrs=['list has 0 items', + '{}']) + + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") + + self.expect("frame variable numbers_list", + substrs=['list has 4 items', + '[0] = ', '1', + '[1] = ', '2', + '[2] = ', '3', + '[3] = ', '4']) + + ListPtr = self.frame().FindVariable("list_ptr") + self.assertTrue(ListPtr.GetChildAtIndex( + 0).GetValueAsUnsigned(0) == 1, "[0] = 1") + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("numbers_list").MightHaveChildren(), + "numbers_list.MightHaveChildren() says False for non empty!") + + self.runCmd("type format delete int") + + self.runCmd("c") + + self.expect("frame variable text_list", + substrs=['list has 3 items', + '[0]', 'goofy', + '[1]', 'is', + '[2]', 'smart']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("text_list").MightHaveChildren(), + "text_list.MightHaveChildren() says False for non empty!") + + self.expect("p text_list", + substrs=['list has 3 items', + '\"goofy\"', + '\"is\"', + '\"smart\"']) + + self.runCmd("n") # This gets us past the printf + self.runCmd("n") + self.runCmd("n") + + # check access-by-index + self.expect("frame variable text_list[0]", + substrs=['goofy']) + self.expect("frame variable text_list[3]", + substrs=['!!!']) + + self.runCmd("continue") + + # check that the list provider correctly updates if elements move + countingList = self.frame().FindVariable("countingList") + countingList.SetPreferDynamicValue(True) + countingList.SetPreferSyntheticValue(True) + + self.assertTrue(countingList.GetChildAtIndex( + 0).GetValueAsUnsigned(0) == 3141, "list[0] == 3141") + self.assertTrue(countingList.GetChildAtIndex( + 1).GetValueAsUnsigned(0) == 3141, "list[1] == 3141") + + self.runCmd("continue") + + self.assertTrue( + countingList.GetChildAtIndex(0).GetValueAsUnsigned(0) == 3141, + "uniqued list[0] == 3141") + self.assertTrue( + countingList.GetChildAtIndex(1).GetValueAsUnsigned(0) == 3142, + "uniqued list[1] == 3142") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/Makefile new file mode 100644 index 00000000000..564cbada74e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py new file mode 100644 index 00000000000..1678c513e50 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py @@ -0,0 +1,69 @@ +""" +Test that the debugger handles loops in std::list (which can appear as a result of e.g. memory +corruption). +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxListDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(["libc++"]) + @expectedFailureAndroid(bugnumber="llvm.org/pr32592") + def test_with_run_command(self): + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target and target.IsValid(), "Target is valid") + + file_spec = lldb.SBFileSpec("main.cpp", False) + breakpoint1 = target.BreakpointCreateBySourceRegex( + '// Set break point at this line.', file_spec) + self.assertTrue(breakpoint1 and breakpoint1.IsValid()) + breakpoint2 = target.BreakpointCreateBySourceRegex( + '// Set second break point at this line.', file_spec) + self.assertTrue(breakpoint2 and breakpoint2.IsValid()) + + # Run the program, it should stop at breakpoint 1. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) + self.assertEqual( + len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint1)), 1) + + # verify our list is displayed correctly + self.expect( + "frame variable *numbers_list", + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3', + '[3] = 4', + '[5] = 6']) + + # Continue to breakpoint 2. + process.Continue() + self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) + self.assertEqual( + len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint2)), 1) + + # The list is now inconsistent. However, we should be able to get the first three + # elements at least (and most importantly, not crash). + self.expect( + "frame variable *numbers_list", + substrs=[ + '[0] = 1', + '[1] = 2', + '[2] = 3']) + + # Run to completion. + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/main.cpp new file mode 100644 index 00000000000..e07e93838b9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/main.cpp @@ -0,0 +1,35 @@ +// Evil hack: To simulate memory corruption, we want to fiddle with some internals of std::list. +// Make those accessible to us. +#define private public +#define protected public + +#include <list> +#include <stdio.h> +#include <assert.h> + +typedef std::list<int> int_list; + +int main() +{ +#ifdef LLDB_USING_LIBCPP + int_list *numbers_list = new int_list{1,2,3,4,5,6,7,8,9,10}; + + printf("// Set break point at this line."); + +#if _LIBCPP_VERSION >= 3800 + auto *third_elem = numbers_list->__end_.__next_->__next_->__next_; + assert(third_elem->__as_node()->__value_ == 3); + auto *fifth_elem = third_elem->__next_->__next_; + assert(fifth_elem->__as_node()->__value_ == 5); +#else + auto *third_elem = numbers_list->__end_.__next_->__next_->__next_; + assert(third_elem->__value_ == 3); + auto *fifth_elem = third_elem->__next_->__next_; + assert(fifth_elem->__value_ == 5); +#endif + fifth_elem->__next_ = third_elem; +#endif + + // Any attempt to free the list will probably crash the program. Let's just leak it. + return 0; // Set second break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/main.cpp new file mode 100644 index 00000000000..a3ef06b18e7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/main.cpp @@ -0,0 +1,44 @@ +#include <string> +#include <list> +#include <stdio.h> + +typedef std::list<int> int_list; +typedef std::list<std::string> string_list; + +int main() +{ + int_list numbers_list; + std::list<int>* list_ptr = &numbers_list; + + printf("// Set break point at this line."); + (numbers_list.push_back(0x12345678)); + (numbers_list.push_back(0x11223344)); + (numbers_list.push_back(0xBEEFFEED)); + (numbers_list.push_back(0x00ABBA00)); + (numbers_list.push_back(0x0ABCDEF0)); + (numbers_list.push_back(0x0CAB0CAB)); + + numbers_list.clear(); + + (numbers_list.push_back(1)); + (numbers_list.push_back(2)); + (numbers_list.push_back(3)); + (numbers_list.push_back(4)); + + string_list text_list; + (text_list.push_back(std::string("goofy"))); + (text_list.push_back(std::string("is"))); + (text_list.push_back(std::string("smart"))); + + printf("// Set second break point at this line."); + (text_list.push_back(std::string("!!!"))); + + std::list<int> countingList = {3141, 3142, 3142,3142,3142, 3142, 3142, 3141}; + countingList.sort(); + printf("// Set third break point at this line."); + countingList.unique(); + printf("// Set fourth break point at this line."); + countingList.size(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/Makefile new file mode 100644 index 00000000000..564cbada74e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py new file mode 100644 index 00000000000..d9da0c3886e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py @@ -0,0 +1,324 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxMapDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + @add_test_categories(["libc++"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + ns = self.namespace + self.expect('p ii', + substrs=['%s::map' % ns, + 'size=0', + '{}']) + self.expect('frame var ii', + substrs=['%s::map' % ns, + 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('p ii', + substrs=['%s::map' % ns, 'size=2', + '[0] = ', + 'first = 0', + 'second = 0', + '[1] = ', + 'first = 1', + 'second = 1']) + + self.expect('frame variable ii', + substrs=['%s::map' % ns, 'size=2', + '[0] = ', + 'first = 0', + 'second = 0', + '[1] = ', + 'first = 1', + 'second = 1']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable ii', + substrs=['%s::map' % ns, 'size=4', + '[2] = ', + 'first = 2', + 'second = 0', + '[3] = ', + 'first = 3', + 'second = 1']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect("p ii", + substrs=['%s::map' % ns, 'size=8', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) + + self.expect("frame var ii", + substrs=['%s::map' % ns, 'size=8', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) + + # check access-by-index + self.expect("frame variable ii[0]", + substrs=['first = 0', + 'second = 0']) + self.expect("frame variable ii[3]", + substrs=['first =', + 'second =']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("ii").MightHaveChildren(), + "ii.MightHaveChildren() says False for non empty!") + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression ii[8]", matching=False, error=True, + # substrs = ['1234567']) + + self.runCmd("continue") + + self.expect('frame variable ii', + substrs=['%s::map' % ns, 'size=0', + '{}']) + + self.expect('frame variable si', + substrs=['%s::map' % ns, 'size=0', + '{}']) + + self.runCmd("continue") + + self.expect('frame variable si', + substrs=['%s::map' % ns, 'size=1', + '[0] = ', + 'first = \"zero\"', + 'second = 0']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect("frame variable si", + substrs=['%s::map' % ns, 'size=4', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3']) + + self.expect("p si", + substrs=['%s::map' % ns, 'size=4', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("si").MightHaveChildren(), + "si.MightHaveChildren() says False for non empty!") + + # check access-by-index + self.expect("frame variable si[0]", + substrs=['first = ', 'one', + 'second = 1']) + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression si[0]", matching=False, error=True, + # substrs = ['first = ', 'zero']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable si', + substrs=['%s::map' % ns, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable is', + substrs=['%s::map' % ns, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect("frame variable is", + substrs=['%s::map' % ns, 'size=4', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) + + self.expect("p is", + substrs=['%s::map' % ns, 'size=4', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("is").MightHaveChildren(), + "is.MightHaveChildren() says False for non empty!") + + # check access-by-index + self.expect("frame variable is[0]", + substrs=['first = ', + 'second =']) + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression is[0]", matching=False, error=True, + # substrs = ['first = ', 'goofy']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable is', + substrs=['%s::map' % ns, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable ss', + substrs=['%s::map' % ns, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect("frame variable ss", + substrs=['%s::map' % ns, 'size=3', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"']) + + self.expect("p ss", + substrs=['%s::map' % ns, 'size=3', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("ss").MightHaveChildren(), + "ss.MightHaveChildren() says False for non empty!") + + # check access-by-index + self.expect("frame variable ss[2]", + substrs=['gatto', 'cat']) + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression ss[3]", matching=False, error=True, + # substrs = ['gatto']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable ss', + substrs=['%s::map' % ns, 'size=0', + '{}']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/main.cpp new file mode 100644 index 00000000000..da6eca985d2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/main.cpp @@ -0,0 +1,77 @@ +#include <string> +#include <map> + +#define intint_map std::map<int, int> +#define strint_map std::map<std::string, int> +#define intstr_map std::map<int, std::string> +#define strstr_map std::map<std::string, std::string> + +int g_the_foo = 0; + +int thefoo_rw(int arg = 1) +{ + if (arg < 0) + arg = 0; + if (!arg) + arg = 1; + g_the_foo += arg; + return g_the_foo; +} + +int main() +{ + intint_map ii; + + ii[0] = 0; // Set break point at this line. + ii[1] = 1; + thefoo_rw(1); // Set break point at this line. + ii[2] = 0; + ii[3] = 1; + thefoo_rw(1); // Set break point at this line. + ii[4] = 0; + ii[5] = 1; + ii[6] = 0; + ii[7] = 1; + thefoo_rw(1); // Set break point at this line. + ii[85] = 1234567; + + ii.clear(); + + strint_map si; + thefoo_rw(1); // Set break point at this line. + + si["zero"] = 0; + thefoo_rw(1); // Set break point at this line. + si["one"] = 1; + si["two"] = 2; + si["three"] = 3; + thefoo_rw(1); // Set break point at this line. + si["four"] = 4; + + si.clear(); + thefoo_rw(1); // Set break point at this line. + + intstr_map is; + thefoo_rw(1); // Set break point at this line. + is[85] = "goofy"; + is[1] = "is"; + is[2] = "smart"; + is[3] = "!!!"; + thefoo_rw(1); // Set break point at this line. + + is.clear(); + thefoo_rw(1); // Set break point at this line. + + strstr_map ss; + thefoo_rw(1); // Set break point at this line. + + ss["ciao"] = "hello"; + ss["casa"] = "house"; + ss["gatto"] = "cat"; + thefoo_rw(1); // Set break point at this line. + ss["a Mac.."] = "..is always a Mac!"; + + ss.clear(); + thefoo_rw(1); // Set break point at this line. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/Makefile new file mode 100644 index 00000000000..564cbada74e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py new file mode 100644 index 00000000000..39adc04e49a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py @@ -0,0 +1,311 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxMultiMapDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + @add_test_categories(["libc++"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.")) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + multimap = self.namespace + "::multimap" + self.expect('frame variable ii', + substrs=[multimap, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable ii', + substrs=[multimap, 'size=2', + '[0] = ', + 'first = 0', + 'second = 0', + '[1] = ', + 'first = 1', + 'second = 1']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable ii', + substrs=[multimap, 'size=4', + '[2] = ', + 'first = 2', + 'second = 0', + '[3] = ', + 'first = 3', + 'second = 1']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect("frame variable ii", + substrs=[multimap, 'size=8', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) + + self.expect("p ii", + substrs=[multimap, 'size=8', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) + + # check access-by-index + self.expect("frame variable ii[0]", + substrs=['first = 0', + 'second = 0']) + self.expect("frame variable ii[3]", + substrs=['first =', + 'second =']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("ii").MightHaveChildren(), + "ii.MightHaveChildren() says False for non empty!") + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression ii[8]", matching=False, error=True, + # substrs = ['1234567']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable ii', + substrs=[multimap, 'size=0', + '{}']) + + self.expect('frame variable si', + substrs=[multimap, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable si', + substrs=[multimap, 'size=1', + '[0] = ', + 'first = \"zero\"', + 'second = 0']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect("frame variable si", + substrs=[multimap, 'size=4', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3']) + + self.expect("p si", + substrs=[multimap, 'size=4', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("si").MightHaveChildren(), + "si.MightHaveChildren() says False for non empty!") + + # check access-by-index + self.expect("frame variable si[0]", + substrs=['first = ', 'one', + 'second = 1']) + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression si[0]", matching=False, error=True, + # substrs = ['first = ', 'zero']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable si', + substrs=[multimap, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable is', + substrs=[multimap, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect("frame variable is", + substrs=[multimap, 'size=4', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) + + self.expect("p is", + substrs=[multimap, 'size=4', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("is").MightHaveChildren(), + "is.MightHaveChildren() says False for non empty!") + + # check access-by-index + self.expect("frame variable is[0]", + substrs=['first = ', + 'second =']) + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression is[0]", matching=False, error=True, + # substrs = ['first = ', 'goofy']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable is', + substrs=[multimap, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable ss', + substrs=[multimap, 'size=0', + '{}']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect("frame variable ss", + substrs=[multimap, 'size=3', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"']) + + self.expect("p ss", + substrs=[multimap, 'size=3', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("ss").MightHaveChildren(), + "ss.MightHaveChildren() says False for non empty!") + + # check access-by-index + self.expect("frame variable ss[2]", + substrs=['gatto', 'cat']) + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression ss[3]", matching=False, error=True, + # substrs = ['gatto']) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect('frame variable ss', + substrs=[multimap, 'size=0', + '{}']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/main.cpp new file mode 100644 index 00000000000..27bdc0a5772 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/main.cpp @@ -0,0 +1,77 @@ +#include <string> +#include <map> + +#define intint_map std::multimap<int, int> +#define strint_map std::multimap<std::string, int> +#define intstr_map std::multimap<int, std::string> +#define strstr_map std::multimap<std::string, std::string> + +int g_the_foo = 0; + +int thefoo_rw(int arg = 1) +{ + if (arg < 0) + arg = 0; + if (!arg) + arg = 1; + g_the_foo += arg; + return g_the_foo; +} + +int main() +{ + intint_map ii; + + ii.emplace(0,0); // Set break point at this line. + ii.emplace(1,1); + thefoo_rw(1); // Set break point at this line. + ii.emplace(2,0); + ii.emplace(3,1); + thefoo_rw(1); // Set break point at this line. + ii.emplace(4,0); + ii.emplace(5,1); + ii.emplace(6,0); + ii.emplace(7,1); + thefoo_rw(1); // Set break point at this line. + ii.emplace(85,1234567); + + ii.clear(); + + strint_map si; + thefoo_rw(1); // Set break point at this line. + + si.emplace("zero",0); + thefoo_rw(1); // Set break point at this line. + si.emplace("one",1); + si.emplace("two",2); + si.emplace("three",3); + thefoo_rw(1); // Set break point at this line. + si.emplace("four",4); + + si.clear(); + thefoo_rw(1); // Set break point at this line. + + intstr_map is; + thefoo_rw(1); // Set break point at this line. + is.emplace(85,"goofy"); + is.emplace(1,"is"); + is.emplace(2,"smart"); + is.emplace(3,"!!!"); + thefoo_rw(1); // Set break point at this line. + + is.clear(); + thefoo_rw(1); // Set break point at this line. + + strstr_map ss; + thefoo_rw(1); // Set break point at this line. + + ss.emplace("ciao","hello"); + ss.emplace("casa","house"); + ss.emplace("gatto","cat"); + thefoo_rw(1); // Set break point at this line. + ss.emplace("a Mac..","..is always a Mac!"); + + ss.clear(); + thefoo_rw(1); // Set break point at this line. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/Makefile new file mode 100644 index 00000000000..564cbada74e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py new file mode 100644 index 00000000000..621b22a538c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py @@ -0,0 +1,142 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxMultiSetDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + def getVariableType(self, name): + var = self.frame().FindVariable(name) + self.assertTrue(var.IsValid()) + return var.GetType().GetCanonicalType().GetName() + + def check_ii(self, var_name): + """ This checks the value of the bitset stored in ii at the call to by_ref_and_ptr. + We use this to make sure we get the same values for ii when we look at the object + directly, and when we look at a reference to the object. """ + self.expect( + "frame variable " + var_name, + substrs=["size=7", + "[2] = 2", + "[3] = 3", + "[6] = 6"]) + self.expect("frame variable " + var_name + "[2]", substrs=[" = 2"]) + self.expect( + "p " + var_name, + substrs=[ + "size=7", + "[2] = 2", + "[3] = 3", + "[6] = 6"]) + + @add_test_categories(["libc++"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + (self.target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set break point at this line.", lldb.SBFileSpec("main.cpp", False)) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + ii_type = self.getVariableType("ii") + self.assertTrue(ii_type.startswith(self.namespace + "::multiset"), + "Type: " + ii_type) + + self.expect("frame variable ii", substrs=["size=0", "{}"]) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect( + "frame variable ii", + substrs=[ + "size=6", + "[0] = 0", + "[1] = 1", + "[2] = 2", + "[3] = 3", + "[4] = 4", + "[5] = 5"]) + lldbutil.continue_to_breakpoint(process, bkpt) + + self.check_ii("ii") + + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect("frame variable ii", substrs=["size=0", "{}"]) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect("frame variable ii", substrs=["size=0", "{}"]) + ss_type = self.getVariableType("ss") + self.assertTrue(ss_type.startswith(self.namespace + "::multiset"), + "Type: " + ss_type) + self.expect("frame variable ss", substrs=["size=0", "{}"]) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect( + "frame variable ss", + substrs=[ + "size=2", + '[0] = "a"', + '[1] = "a very long string is right here"']) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect( + "frame variable ss", + substrs=[ + "size=4", + '[2] = "b"', + '[3] = "c"', + '[0] = "a"', + '[1] = "a very long string is right here"']) + self.expect( + "p ss", + substrs=[ + "size=4", + '[2] = "b"', + '[3] = "c"', + '[0] = "a"', + '[1] = "a very long string is right here"']) + self.expect("frame variable ss[2]", substrs=[' = "b"']) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect( + "frame variable ss", + substrs=[ + "size=3", + '[0] = "a"', + '[1] = "a very long string is right here"', + '[2] = "c"']) + + @add_test_categories(["libc++"]) + def test_ref_and_ptr(self): + """Test that the data formatters work on ref and ptr.""" + self.build() + (self.target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Stop here to check by ref and ptr.", + lldb.SBFileSpec("main.cpp", False)) + # The reference should print just like the value: + self.check_ii("ref") + + self.expect("frame variable ptr", + substrs=["ptr =", "size=7"]) + self.expect("expr ptr", + substrs=["size=7"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/main.cpp new file mode 100644 index 00000000000..dd3d8be4ae9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/main.cpp @@ -0,0 +1,61 @@ +#include <string> +#include <set> + +typedef std::multiset<int> intset; +typedef std::multiset<std::string> stringset; + +int g_the_foo = 0; + +int thefoo_rw(int arg = 1) +{ + if (arg < 0) + arg = 0; + if (!arg) + arg = 1; + g_the_foo += arg; + return g_the_foo; +} + +void by_ref_and_ptr(intset &ref, intset *ptr) +{ + // Stop here to check by ref and ptr + return; +} + +int main() +{ + intset ii; + thefoo_rw(1); // Set break point at this line. + + ii.insert(0); + ii.insert(1); + ii.insert(2); + ii.insert(3); + ii.insert(4); + ii.insert(5); + thefoo_rw(1); // Set break point at this line. + + ii.insert(6); + thefoo_rw(1); // Set break point at this line. + + by_ref_and_ptr(ii, &ii); + + ii.clear(); + thefoo_rw(1); // Set break point at this line. + + stringset ss; + thefoo_rw(1); // Set break point at this line. + + ss.insert("a"); + ss.insert("a very long string is right here"); + thefoo_rw(1); // Set break point at this line. + + ss.insert("b"); + ss.insert("c"); + thefoo_rw(1); // Set break point at this line. + + ss.erase("b"); + thefoo_rw(1); // Set break point at this line. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/optional/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/optional/Makefile new file mode 100644 index 00000000000..23496eb2065 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/optional/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -std=c++17 -fno-exceptions +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/optional/TestDataFormatterLibcxxOptional.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/optional/TestDataFormatterLibcxxOptional.py new file mode 100644 index 00000000000..f013d02d14f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/optional/TestDataFormatterLibcxxOptional.py @@ -0,0 +1,72 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxOptionalDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + ## We are skipping clang version less that 5.0 since this test requires -std=c++17 + @skipIf(oslist=no_match(["macosx"]), compiler="clang", compiler_version=['<', '5.0']) + ## We are skipping gcc version less that 5.1 since this test requires -std=c++17 + @skipIf(compiler="gcc", compiler_version=['<', '5.1']) + + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + bkpt = self.target().FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp( + self, "break here")) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.runCmd( "frame variable has_optional" ) + + output = self.res.GetOutput() + + ## The variable has_optional tells us if the test program + ## detected we have a sufficient libc++ version to support optional + ## false means we do not and therefore should skip the test + if output.find("(bool) has_optional = false") != -1 : + self.skipTest( "Optional not supported" ) + + lldbutil.continue_to_breakpoint(self.process(), bkpt) + + self.expect("frame variable number_not_engaged", + substrs=['Has Value=false']) + + self.expect("frame variable number_engaged", + substrs=['Has Value=true', + 'Value = 42', + '}']) + + self.expect("frame var numbers", + substrs=['(optional_int_vect) numbers = Has Value=true {', + 'Value = size=4 {', + '[0] = 1', + '[1] = 2', + '[2] = 3', + '[3] = 4', + '}', + '}']) + + self.expect("frame var ostring", + substrs=['(optional_string) ostring = Has Value=true {', + 'Value = "hello"', + '}']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/optional/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/optional/main.cpp new file mode 100644 index 00000000000..16bb98c6105 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/optional/main.cpp @@ -0,0 +1,42 @@ +#include <cstdio> +#include <string> +#include <vector> + +// If we have libc++ 4.0 or greater we should have <optional> +// According to libc++ C++1z status page https://libcxx.llvm.org/cxx1z_status.html +#if _LIBCPP_VERSION >= 4000 +#include <optional> +#define HAVE_OPTIONAL 1 +#else +#define HAVE_OPTIONAL 0 +#endif + + +int main() +{ + bool has_optional = HAVE_OPTIONAL ; + + printf( "%d\n", has_optional ) ; // break here + +#if HAVE_OPTIONAL == 1 + using int_vect = std::vector<int> ; + using optional_int = std::optional<int> ; + using optional_int_vect = std::optional<int_vect> ; + using optional_string = std::optional<std::string> ; + + optional_int number_not_engaged ; + optional_int number_engaged = 42 ; + + printf( "%d\n", *number_engaged) ; + + optional_int_vect numbers{{1,2,3,4}} ; + + printf( "%d %d\n", numbers.value()[0], numbers.value()[1] ) ; + + optional_string ostring = "hello" ; + + printf( "%s\n", ostring->c_str() ) ; +#endif + + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/queue/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/queue/Makefile new file mode 100644 index 00000000000..680e1abfbef --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/queue/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/queue/TestDataFormatterLibcxxQueue.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/queue/TestDataFormatterLibcxxQueue.py new file mode 100644 index 00000000000..b163fa56fae --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/queue/TestDataFormatterLibcxxQueue.py @@ -0,0 +1,43 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDataFormatterLibcxxQueue(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + def check_variable(self, name): + var = self.frame().FindVariable(name) + self.assertTrue(var.IsValid()) + + queue = self.namespace + '::queue' + self.assertTrue(queue in var.GetTypeName()) + self.assertEqual(var.GetNumChildren(), 5) + for i in range(5): + ch = var.GetChildAtIndex(i) + self.assertTrue(ch.IsValid()) + self.assertEqual(ch.GetValueAsSigned(), i+1) + + @expectedFailureAll(bugnumber="llvm.org/pr36109", debug_info="gmodules", triple=".*-android") + @add_test_categories(["libc++"]) + def test(self): + """Test that std::queue is displayed correctly""" + self.build() + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + self.check_variable('q1') + self.check_variable('q2') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/queue/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/queue/main.cpp new file mode 100644 index 00000000000..449be8d99cf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/queue/main.cpp @@ -0,0 +1,11 @@ +#include <queue> +#include <vector> + +using namespace std; + +int main() { + queue<int> q1{{1,2,3,4,5}}; + queue<int, std::vector<int>> q2{{1,2,3,4,5}}; + int ret = q1.size() + q2.size(); // break here + return ret; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/Makefile new file mode 100644 index 00000000000..564cbada74e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py new file mode 100644 index 00000000000..738df85d051 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py @@ -0,0 +1,139 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxSetDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + def getVariableType(self, name): + var = self.frame().FindVariable(name) + self.assertTrue(var.IsValid()) + return var.GetType().GetCanonicalType().GetName() + + def check_ii(self, var_name): + """ This checks the value of the bitset stored in ii at the call to by_ref_and_ptr. + We use this to make sure we get the same values for ii when we look at the object + directly, and when we look at a reference to the object. """ + self.expect( + "frame variable " + var_name, + substrs=["size=7", + "[2] = 2", + "[3] = 3", + "[6] = 6"]) + self.expect("frame variable " + var_name + "[2]", substrs=[" = 2"]) + self.expect( + "p " + var_name, + substrs=[ + "size=7", + "[2] = 2", + "[3] = 3", + "[6] = 6"]) + + @add_test_categories(["libc++"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + (self.target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set break point at this line.", lldb.SBFileSpec("main.cpp", False)) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + ii_type = self.getVariableType("ii") + self.assertTrue(ii_type.startswith(self.namespace + "::set"), + "Type: " + ii_type) + + self.expect("frame variable ii", substrs=["size=0", "{}"]) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect( + "frame variable ii", + substrs=["size=6", + "[0] = 0", + "[1] = 1", + "[2] = 2", + "[3] = 3", + "[4] = 4", + "[5] = 5"]) + lldbutil.continue_to_breakpoint(process, bkpt) + self.check_ii("ii") + + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect("frame variable ii", substrs=["size=0", "{}"]) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect("frame variable ii", substrs=["size=0", "{}"]) + + ss_type = self.getVariableType("ss") + self.assertTrue(ii_type.startswith(self.namespace + "::set"), + "Type: " + ss_type) + + self.expect("frame variable ss", substrs=["size=0", "{}"]) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect( + "frame variable ss", + substrs=["size=2", + '[0] = "a"', + '[1] = "a very long string is right here"']) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect( + "frame variable ss", + substrs=["size=4", + '[2] = "b"', + '[3] = "c"', + '[0] = "a"', + '[1] = "a very long string is right here"']) + self.expect( + "p ss", + substrs=["size=4", + '[2] = "b"', + '[3] = "c"', + '[0] = "a"', + '[1] = "a very long string is right here"']) + self.expect("frame variable ss[2]", substrs=[' = "b"']) + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect( + "frame variable ss", + substrs=["size=3", + '[0] = "a"', + '[1] = "a very long string is right here"', + '[2] = "c"']) + + @add_test_categories(["libc++"]) + def test_ref_and_ptr(self): + """Test that the data formatters work on ref and ptr.""" + self.build() + (self.target, process, _, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Stop here to check by ref and ptr.", + lldb.SBFileSpec("main.cpp", False)) + # The reference should print just like the value: + self.check_ii("ref") + + self.expect("frame variable ptr", + substrs=["ptr =", "size=7"]) + self.expect("expr ptr", + substrs=["size=7"]) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/main.cpp new file mode 100644 index 00000000000..df39e9746c0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/main.cpp @@ -0,0 +1,61 @@ +#include <string> +#include <set> + +typedef std::set<int> intset; +typedef std::set<std::string> stringset; + +int g_the_foo = 0; + +int thefoo_rw(int arg = 1) +{ + if (arg < 0) + arg = 0; + if (!arg) + arg = 1; + g_the_foo += arg; + return g_the_foo; +} + +void by_ref_and_ptr(intset &ref, intset *ptr) +{ + // Stop here to check by ref and ptr + return; +} + +int main() +{ + intset ii; + thefoo_rw(1); // Set break point at this line. + + ii.insert(0); + ii.insert(1); + ii.insert(2); + ii.insert(3); + ii.insert(4); + ii.insert(5); + thefoo_rw(1); // Set break point at this line. + + ii.insert(6); + thefoo_rw(1); // Set break point at this line. + + by_ref_and_ptr(ii, &ii); + + ii.clear(); + thefoo_rw(1); // Set break point at this line. + + stringset ss; + thefoo_rw(1); // Set break point at this line. + + ss.insert("a"); + ss.insert("a very long string is right here"); + thefoo_rw(1); // Set break point at this line. + + ss.insert("b"); + ss.insert("c"); + thefoo_rw(1); // Set break point at this line. + + ss.erase("b"); + thefoo_rw(1); // Set break point at this line. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/Makefile new file mode 100644 index 00000000000..c7c91da728d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -std=c++11 -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py new file mode 100644 index 00000000000..8943b259668 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py @@ -0,0 +1,116 @@ +# coding=utf8 +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxStringDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + @add_test_categories(["libc++"]) + @expectedFailureAll(bugnumber="llvm.org/pr36109", debug_info="gmodules", triple=".*-android") + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_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=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + ns = self.namespace + self.expect( + "frame variable", + substrs=[ + '(%s::wstring) wempty = L""'%ns, + '(%s::wstring) s = L"hello world! מזל טוב!"'%ns, + '(%s::wstring) S = L"!!!!"'%ns, + '(const wchar_t *) mazeltov = 0x', + 'L"מזל טוב"', + '(%s::string) empty = ""'%ns, + '(%s::string) q = "hello world"'%ns, + '(%s::string) Q = "quite a long std::strin with lots of info inside it"'%ns, + '(%s::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"'%ns, + '(%s::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"'%ns, + '(%s::u16string) u16_string = u"ß水氶"'%ns, + # FIXME: This should have a 'u' prefix. + '(%s::u16string) u16_empty = ""'%ns, + '(%s::u32string) u32_string = U"🍄🍅🍆🍌"'%ns, + # FIXME: This should have a 'U' prefix. + '(%s::u32string) u32_empty = ""'%ns, + '(%s::basic_string<unsigned char, %s::char_traits<unsigned char>, ' + '%s::allocator<unsigned char> >) uchar = "aaaaa"'%(ns,ns,ns), + ]) + + self.runCmd("n") + + TheVeryLongOne = self.frame().FindVariable("TheVeryLongOne") + summaryOptions = lldb.SBTypeSummaryOptions() + summaryOptions.SetCapping(lldb.eTypeSummaryUncapped) + uncappedSummaryStream = lldb.SBStream() + TheVeryLongOne.GetSummary(uncappedSummaryStream, summaryOptions) + uncappedSummary = uncappedSummaryStream.GetData() + self.assertTrue(uncappedSummary.find("someText") > 0, + "uncappedSummary does not include the full string") + summaryOptions.SetCapping(lldb.eTypeSummaryCapped) + cappedSummaryStream = lldb.SBStream() + TheVeryLongOne.GetSummary(cappedSummaryStream, summaryOptions) + cappedSummary = cappedSummaryStream.GetData() + self.assertTrue( + cappedSummary.find("someText") <= 0, + "cappedSummary includes the full string") + + self.expect_expr("s", result_type=ns+"::wstring", result_summary='L"hello world! מזל טוב!"') + + self.expect( + "frame variable", + substrs=[ + '(%s::wstring) S = L"!!!!!"'%ns, + '(const wchar_t *) mazeltov = 0x', + 'L"מזל טוב"', + '(%s::string) q = "hello world"'%ns, + '(%s::string) Q = "quite a long std::strin with lots of info inside it"'%ns, + '(%s::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"'%ns, + '(%s::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"'%ns, + '(%s::u16string) u16_string = u"ß水氶"'%ns, + '(%s::u32string) u32_string = U"🍄🍅🍆🍌"'%ns, + '(%s::u32string) u32_empty = ""'%ns, + '(%s::basic_string<unsigned char, %s::char_traits<unsigned char>, ' + '%s::allocator<unsigned char> >) uchar = "aaaaa"'%(ns,ns,ns), + ]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/main.cpp new file mode 100644 index 00000000000..afb56e67f0a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/main.cpp @@ -0,0 +1,22 @@ +#include <string> + +int main() +{ + std::wstring wempty(L""); + std::wstring s(L"hello world! מזל טוב!"); + std::wstring S(L"!!!!"); + const wchar_t *mazeltov = L"מזל טוב"; + std::string empty(""); + std::string q("hello world"); + std::string Q("quite a long std::strin with lots of info inside it"); + std::string TheVeryLongOne("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890someText1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); + std::string IHaveEmbeddedZeros("a\0b\0c\0d",7); + std::wstring IHaveEmbeddedZerosToo(L"hello world!\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監", 38); + std::u16string u16_string(u"ß水氶"); + std::u16string u16_empty(u""); + std::u32string u32_string(U"🍄🍅🍆🍌"); + std::u32string u32_empty(U""); + std::basic_string<unsigned char> uchar(5, 'a'); + S.assign(L"!!!!!"); // Set break point at this line. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/Makefile new file mode 100644 index 00000000000..680e1abfbef --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/TestDataFormatterLibcxxTuple.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/TestDataFormatterLibcxxTuple.py new file mode 100644 index 00000000000..57b77783716 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/TestDataFormatterLibcxxTuple.py @@ -0,0 +1,50 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestDataFormatterLibcxxTuple(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.line = line_number('main.cpp', '// break here') + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + @add_test_categories(["libc++"]) + def test(self): + """Test that std::tuple is displayed correctly""" + self.build() + lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + tuple_name = self.namespace + '::tuple' + self.expect("frame variable empty", + substrs=[tuple_name, + 'size=0', + '{}']) + + self.expect("frame variable one_elt", + substrs=[tuple_name, + 'size=1', + '{', + '[0] = 47', + '}']) + + self.expect("frame variable three_elts", + substrs=[tuple_name, + 'size=3', + '{', + '[0] = 1', + '[1] = 47', + '[2] = "foo"', + '}']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/main.cpp new file mode 100644 index 00000000000..1c0d0f2ae77 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/tuple/main.cpp @@ -0,0 +1,11 @@ +#include <tuple> +#include <string> + +using namespace std; + +int main() { + tuple<> empty; + tuple<int> one_elt{47}; + tuple<int, long, string> three_elts{1, 47l, "foo"}; + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/Makefile new file mode 100644 index 00000000000..913a52fb191 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/Makefile @@ -0,0 +1,9 @@ +CXX_SOURCES := main.cpp + +# Work around "exception specification in declaration does not match previous +# declaration" errors present in older libc++ releases. This error was fixed in +# the 3.8 release. +CFLAGS_EXTRAS := -fno-exceptions + +USE_LIBCPP := 1 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py new file mode 100644 index 00000000000..9566af03130 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py @@ -0,0 +1,79 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxUnorderedDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + ns = 'ndk' if lldbplatformutil.target_is_android() else '' + self.namespace = 'std::__' + ns + '1' + + @add_test_categories(["libc++"]) + def test_with_run_command(self): + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + ns = self.namespace + self.look_for_content_and_continue( + "map", ['%s::unordered_map' % + ns, 'size=5 {', 'hello', 'world', 'this', 'is', 'me']) + + self.look_for_content_and_continue( + "mmap", ['%s::unordered_multimap' % ns, 'size=6 {', 'first = 3', 'second = "this"', + 'first = 2', 'second = "hello"']) + + self.look_for_content_and_continue( + "iset", ['%s::unordered_set' % + ns, 'size=5 {', '\[\d\] = 5', '\[\d\] = 3', '\[\d\] = 2']) + + self.look_for_content_and_continue( + "sset", ['%s::unordered_set' % ns, 'size=5 {', '\[\d\] = "is"', '\[\d\] = "world"', + '\[\d\] = "hello"']) + + self.look_for_content_and_continue( + "imset", ['%s::unordered_multiset' % ns, 'size=6 {', '(\[\d\] = 3(\\n|.)+){3}', + '\[\d\] = 2', '\[\d\] = 1']) + + self.look_for_content_and_continue( + "smset", ['%s::unordered_multiset' % ns, 'size=5 {', '(\[\d\] = "is"(\\n|.)+){2}', + '(\[\d\] = "world"(\\n|.)+){2}']) + + def look_for_content_and_continue(self, var_name, patterns): + self.expect(("frame variable %s" % var_name), patterns=patterns) + self.expect(("frame variable %s" % var_name), patterns=patterns) + self.runCmd("continue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/main.cpp new file mode 100644 index 00000000000..81a5763559d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/main.cpp @@ -0,0 +1,80 @@ +#include <string> +#include <unordered_map> +#include <unordered_set> + +using std::string; + +#define intstr_map std::unordered_map<int, string> +#define intstr_mmap std::unordered_multimap<int, string> + +#define int_set std::unordered_set<int> +#define str_set std::unordered_set<string> +#define int_mset std::unordered_multiset<int> +#define str_mset std::unordered_multiset<string> + +int g_the_foo = 0; + +int thefoo_rw(int arg = 1) +{ + if (arg < 0) + arg = 0; + if (!arg) + arg = 1; + g_the_foo += arg; + return g_the_foo; +} + +int main() +{ + intstr_map map; + map.emplace(1,"hello"); + map.emplace(2,"world"); + map.emplace(3,"this"); + map.emplace(4,"is"); + map.emplace(5,"me"); + thefoo_rw(); // Set break point at this line. + + intstr_mmap mmap; + mmap.emplace(1,"hello"); + mmap.emplace(2,"hello"); + mmap.emplace(2,"world"); + mmap.emplace(3,"this"); + mmap.emplace(3,"this"); + mmap.emplace(3,"this"); + thefoo_rw(); // Set break point at this line. + + int_set iset; + iset.emplace(1); + iset.emplace(2); + iset.emplace(3); + iset.emplace(4); + iset.emplace(5); + thefoo_rw(); // Set break point at this line. + + str_set sset; + sset.emplace("hello"); + sset.emplace("world"); + sset.emplace("this"); + sset.emplace("is"); + sset.emplace("me"); + thefoo_rw(); // Set break point at this line. + + int_mset imset; + imset.emplace(1); + imset.emplace(2); + imset.emplace(2); + imset.emplace(3); + imset.emplace(3); + imset.emplace(3); + thefoo_rw(); // Set break point at this line. + + str_mset smset; + smset.emplace("hello"); + smset.emplace("world"); + smset.emplace("world"); + smset.emplace("is"); + smset.emplace("is"); + thefoo_rw(); // Set break point at this line. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/Makefile new file mode 100644 index 00000000000..7eeff740780 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -std=c++17 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/TestDataFormatterLibcxxVariant.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/TestDataFormatterLibcxxVariant.py new file mode 100644 index 00000000000..a2a6b74faa4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/TestDataFormatterLibcxxVariant.py @@ -0,0 +1,80 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class LibcxxVariantDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libc++"]) + ## We are skipping clang version less that 5.0 since this test requires -std=c++17 + @skipIf(oslist=no_match(["macosx"]), compiler="clang", compiler_version=['<', '5.0']) + ## We are skipping gcc version less that 5.1 since this test requires -std=c++17 + @skipIf(compiler="gcc", compiler_version=['<', '5.1']) + ## std::get is unavailable for std::variant before macOS 10.14 + @skipIf(macos_version=["<", "10.14"]) + + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + + (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + self.runCmd( "frame variable has_variant" ) + + output = self.res.GetOutput() + + ## The variable has_variant tells us if the test program + ## detected we have a sufficient libc++ version to support variant + ## false means we do not and therefore should skip the test + if output.find("(bool) has_variant = false") != -1 : + self.skipTest( "std::variant not supported" ) + + lldbutil.continue_to_breakpoint(self.process, bkpt) + + self.expect("frame variable v1", + substrs=['v1 = Active Type = int {', + 'Value = 12', + '}']) + + self.expect("frame variable v1_ref", + substrs=['v1_ref = Active Type = int : {', + 'Value = 12', + '}']) + + self.expect("frame variable v_v1", + substrs=['v_v1 = Active Type = std::__1::variant<int, double, char> {', + 'Value = Active Type = int {', + 'Value = 12', + '}', + '}']) + + lldbutil.continue_to_breakpoint(self.process, bkpt) + + self.expect("frame variable v1", + substrs=['v1 = Active Type = double {', + 'Value = 2', + '}']) + + lldbutil.continue_to_breakpoint(self.process, bkpt) + + self.expect("frame variable v2", + substrs=['v2 = Active Type = double {', + 'Value = 2', + '}']) + + self.expect("frame variable v3", + substrs=['v3 = Active Type = char {', + 'Value = \'A\'', + '}']) + + self.expect("frame variable v_no_value", + substrs=['v_no_value = No Value']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp new file mode 100644 index 00000000000..c0bc4ae12c1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/variant/main.cpp @@ -0,0 +1,60 @@ +#include <cstdio> +#include <string> +#include <vector> + +// If we have libc++ 4.0 or greater we should have <variant> +// According to libc++ C++1z status page https://libcxx.llvm.org/cxx1z_status.html +#if _LIBCPP_VERSION >= 4000 +#include <variant> +#define HAVE_VARIANT 1 +#else +#define HAVE_VARIANT 0 +#endif + +struct S { + operator int() { throw 42; } +} ; + + +int main() +{ + bool has_variant = HAVE_VARIANT ; + + printf( "%d\n", has_variant ) ; // break here + +#if HAVE_VARIANT == 1 + std::variant<int, double, char> v1; + std::variant<int, double, char> &v1_ref = v1; + std::variant<int, double, char> v2; + std::variant<int, double, char> v3; + std::variant<std::variant<int,double,char>> v_v1 ; + std::variant<int, double, char> v_no_value; + + v1 = 12; // v contains int + v_v1 = v1 ; + int i = std::get<int>(v1); + printf( "%d\n", i ); // break here + + v2 = 2.0 ; + double d = std::get<double>(v2) ; + printf( "%f\n", d ); + + v3 = 'A' ; + char c = std::get<char>(v3) ; + printf( "%d\n", c ); + + // Checking v1 above and here to make sure we done maintain the incorrect + // state when we change its value. + v1 = 2.0; + d = std::get<double>(v1) ; + printf( "%f\n", d ); // break here + + try { + v_no_value.emplace<0>(S()); + } catch( ... ) {} + + printf( "%zu\n", v_no_value.index() ) ; +#endif + + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/Makefile new file mode 100644 index 00000000000..d87cf7d4027 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp +USE_LIBCPP := 1 +include Makefile.rules + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py new file mode 100644 index 00000000000..67e0629e6b7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py @@ -0,0 +1,75 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxVBoolDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @add_test_categories(["libc++"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_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=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.expect( + "frame variable vBool", + substrs=[ + 'size=49', + '[0] = false', + '[1] = true', + '[18] = false', + '[27] = true', + '[36] = false', + '[47] = true', + '[48] = true']) + + self.expect( + "expr vBool", + substrs=[ + 'size=49', + '[0] = false', + '[1] = true', + '[18] = false', + '[27] = true', + '[36] = false', + '[47] = true', + '[48] = true']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/main.cpp new file mode 100644 index 00000000000..026cfc863f2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/main.cpp @@ -0,0 +1,65 @@ +#include <string> +#include <vector> + +int main() +{ + std::vector<bool> vBool; + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(true); + + printf ("size: %d", (int) vBool.size()); // Set break point at this line. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/Makefile new file mode 100644 index 00000000000..564cbada74e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +USE_LIBCPP := 1 + +CXXFLAGS_EXTRAS := -O0 +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py new file mode 100644 index 00000000000..649c0fee4bd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py @@ -0,0 +1,191 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibcxxVectorDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def check_numbers(self, var_name): + self.expect("frame variable " + var_name, + substrs=[var_name + ' = size=7', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '[4] = 12345', + '[5] = 123456', + '[6] = 1234567', + '}']) + + self.expect("p " + var_name, + substrs=['$', 'size=7', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '[4] = 12345', + '[5] = 123456', + '[6] = 1234567', + '}']) + + # check access-by-index + self.expect("frame variable " + var_name + "[0]", + substrs=['1']) + self.expect("frame variable " + var_name + "[1]", + substrs=['12']) + self.expect("frame variable " + var_name + "[2]", + substrs=['123']) + self.expect("frame variable " + var_name + "[3]", + substrs=['1234']) + + @add_test_categories(["libc++"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec("main.cpp", False)) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # empty vectors (and storage pointers SHOULD BOTH BE NULL..) + self.expect("frame variable numbers", + substrs=['numbers = size=0']) + + lldbutil.continue_to_breakpoint(process, bkpt) + + # first value added + self.expect("frame variable numbers", + substrs=['numbers = size=1', + '[0] = 1', + '}']) + + # add some more data + lldbutil.continue_to_breakpoint(process, bkpt) + + self.expect("frame variable numbers", + substrs=['numbers = size=4', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '}']) + + self.expect("p numbers", + substrs=['$', 'size=4', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '}']) + + # check access to synthetic children + self.runCmd( + "type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect") + self.expect('frame variable numbers', + substrs=['item 0 is 1']) + + self.runCmd( + "type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect") + self.expect('frame variable numbers', + substrs=['item 0 is 1']) + # move on with synths + self.runCmd("type summary delete std::int_vect") + self.runCmd("type summary delete int_vect") + + # add some more data + lldbutil.continue_to_breakpoint(process, bkpt) + + self.check_numbers("numbers") + + # clear out the vector and see that we do the right thing once again + lldbutil.continue_to_breakpoint(process, bkpt) + + self.expect("frame variable numbers", + substrs=['numbers = size=0']) + + lldbutil.continue_to_breakpoint(process, bkpt) + + # first value added + self.expect("frame variable numbers", + substrs=['numbers = size=1', + '[0] = 7', + '}']) + + # check if we can display strings + self.expect("frame variable strings", + substrs=['goofy', + 'is', + 'smart']) + + self.expect("p strings", + substrs=['goofy', + 'is', + 'smart']) + + # test summaries based on synthetic children + self.runCmd( + "type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e") + self.expect("frame variable strings", + substrs=['vector has 3 items', + 'goofy', + 'is', + 'smart']) + + self.expect("p strings", + substrs=['vector has 3 items', + 'goofy', + 'is', + 'smart']) + + lldbutil.continue_to_breakpoint(process, bkpt) + + self.expect("frame variable strings", + substrs=['vector has 4 items']) + + # check access-by-index + self.expect("frame variable strings[0]", + substrs=['goofy']) + self.expect("frame variable strings[1]", + substrs=['is']) + + lldbutil.continue_to_breakpoint(process, bkpt) + + self.expect("frame variable strings", + substrs=['vector has 0 items']) + + @add_test_categories(["libc++"]) + def test_ref_and_ptr(self): + """Test that that file and class static variables display correctly.""" + self.build() + (self.target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Stop here to check by ref", lldb.SBFileSpec("main.cpp", False)) + + # The reference should display the same was as the value did + self.check_numbers("ref") + + # The pointer should just show the right number of elements: + + self.expect("frame variable ptr", substrs=['ptr =', ' size=7']) + + self.expect("p ptr", substrs=['$', 'size=7']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/main.cpp new file mode 100644 index 00000000000..0e1dbe4f03e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/main.cpp @@ -0,0 +1,41 @@ +#include <stdio.h> +#include <string> +#include <vector> +typedef std::vector<int> int_vect; +typedef std::vector<std::string> string_vect; + +template <class T> +void by_ref_and_ptr(std::vector<T> &ref, std::vector<T> *ptr) { + // Stop here to check by ref + return; +} + +int main() +{ + int_vect numbers; + (numbers.push_back(1)); // break here + (numbers.push_back(12)); // break here + (numbers.push_back(123)); + (numbers.push_back(1234)); + (numbers.push_back(12345)); // break here + (numbers.push_back(123456)); + (numbers.push_back(1234567)); + by_ref_and_ptr(numbers, &numbers); + + printf("break here"); + numbers.clear(); + + (numbers.push_back(7)); // break here + + string_vect strings; + (strings.push_back(std::string("goofy"))); + (strings.push_back(std::string("is"))); + (strings.push_back(std::string("smart"))); + printf("break here"); + (strings.push_back(std::string("!!!"))); + + printf("break here"); + strings.clear(); + + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/Makefile new file mode 100644 index 00000000000..c825977b1a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +CFLAGS_EXTRAS := -O0 +USE_LIBSTDCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py new file mode 100644 index 00000000000..52387a41484 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py @@ -0,0 +1,71 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StdIteratorDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @add_test_categories(["libstdcxx"]) + def test_with_run_command(self): + """Test that libstdcpp iterators format properly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_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=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.expect('frame variable ivI', substrs=['item = 3']) + self.expect('expr ivI', substrs=['item = 3']) + + self.expect( + 'frame variable iimI', + substrs=[ + 'first = 0', + 'second = 12']) + self.expect('expr iimI', substrs=['first = 0', 'second = 12']) + + self.expect( + 'frame variable simI', + substrs=[ + 'first = "world"', + 'second = 42']) + self.expect('expr simI', substrs=['first = "world"', 'second = 42']) + + self.expect('frame variable svI', substrs=['item = "hello"']) + self.expect('expr svI', substrs=['item = "hello"']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/main.cpp new file mode 100644 index 00000000000..7ddffd19012 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/main.cpp @@ -0,0 +1,38 @@ +#include <string> +#include <map> +#include <vector> + +typedef std::map<int, int> intint_map; +typedef std::map<std::string, int> strint_map; + +typedef std::vector<int> int_vector; +typedef std::vector<std::string> string_vector; + +typedef intint_map::iterator iimter; +typedef strint_map::iterator simter; + +typedef int_vector::iterator ivter; +typedef string_vector::iterator svter; + +int main() +{ + intint_map iim; + iim[0] = 12; + + strint_map sim; + sim["world"] = 42; + + int_vector iv; + iv.push_back(3); + + string_vector sv; + sv.push_back("hello"); + + iimter iimI = iim.begin(); + simter simI = sim.begin(); + + ivter ivI = iv.begin(); + svter svI = sv.begin(); + + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/Makefile new file mode 100644 index 00000000000..c825977b1a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +CFLAGS_EXTRAS := -O0 +USE_LIBSTDCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py new file mode 100644 index 00000000000..c65393f39bb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py @@ -0,0 +1,206 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StdListDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break at for the different tests. + self.line = line_number('main.cpp', '// Set break point at this line.') + self.optional_line = line_number( + 'main.cpp', '// Optional break point at this line.') + self.final_line = line_number( + 'main.cpp', '// Set final break point at this line.') + + @add_test_categories(["libstdcxx"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_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=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("frame variable numbers_list --show-types") + + self.runCmd("type format add -f hex int") + + self.expect("frame variable numbers_list --raw", matching=False, + substrs=['size=0', + '{}']) + self.expect( + "frame variable &numbers_list._M_impl._M_node --raw", + matching=False, + substrs=[ + 'size=0', + '{}']) + + self.expect("frame variable numbers_list", + substrs=['size=0', + '{}']) + + self.expect("p numbers_list", + substrs=['size=0', + '{}']) + + self.runCmd("n") + + self.expect("frame variable numbers_list", + substrs=['size=1', + '[0] = ', + '0x12345678']) + + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") + + self.expect("frame variable numbers_list", + substrs=['size=4', + '[0] = ', + '0x12345678', + '[1] =', + '0x11223344', + '[2] =', + '0xbeeffeed', + '[3] =', + '0x00abba00']) + + self.runCmd("n") + self.runCmd("n") + + self.expect("frame variable numbers_list", + substrs=['size=6', + '[0] = ', + '0x12345678', + '0x11223344', + '0xbeeffeed', + '0x00abba00', + '[4] =', + '0x0abcdef0', + '[5] =', + '0x0cab0cab']) + + self.expect("p numbers_list", + substrs=['size=6', + '[0] = ', + '0x12345678', + '0x11223344', + '0xbeeffeed', + '0x00abba00', + '[4] =', + '0x0abcdef0', + '[5] =', + '0x0cab0cab']) + + # check access-by-index + self.expect("frame variable numbers_list[0]", + substrs=['0x12345678']) + self.expect("frame variable numbers_list[1]", + substrs=['0x11223344']) + + # but check that expression does not rely on us + self.expect("expression numbers_list[0]", matching=False, error=True, + substrs=['0x12345678']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("numbers_list").MightHaveChildren(), + "numbers_list.MightHaveChildren() says False for non empty!") + + self.runCmd("n") + + self.expect("frame variable numbers_list", + substrs=['size=0', + '{}']) + + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") + self.runCmd("n") + + self.expect("frame variable numbers_list", + substrs=['size=4', + '[0] = ', '1', + '[1] = ', '2', + '[2] = ', '3', + '[3] = ', '4']) + + self.runCmd("type format delete int") + + self.runCmd("n") + + self.expect("frame variable text_list", + substrs=['size=0', + '{}']) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.final_line, num_expected_locations=-1) + + self.runCmd("c", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("frame variable text_list", + substrs=['size=4', + '[0]', 'goofy', + '[1]', 'is', + '[2]', 'smart', + '[3]', '!!!']) + + self.expect("p text_list", + substrs=['size=4', + '\"goofy\"', + '\"is\"', + '\"smart\"', + '\"!!!\"']) + + # check access-by-index + self.expect("frame variable text_list[0]", + substrs=['goofy']) + self.expect("frame variable text_list[3]", + substrs=['!!!']) + + # but check that expression does not rely on us + self.expect("expression text_list[0]", matching=False, error=True, + substrs=['goofy']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("text_list").MightHaveChildren(), + "text_list.MightHaveChildren() says False for non empty!") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/main.cpp new file mode 100644 index 00000000000..191acdcc97b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/main.cpp @@ -0,0 +1,34 @@ +#include <list> +#include <string> + +typedef std::list<int> int_list; +typedef std::list<std::string> string_list; + +int main() +{ + int_list numbers_list; + + numbers_list.push_back(0x12345678); // Set break point at this line. + numbers_list.push_back(0x11223344); + numbers_list.push_back(0xBEEFFEED); + numbers_list.push_back(0x00ABBA00); + numbers_list.push_back(0x0ABCDEF0); + numbers_list.push_back(0x0CAB0CAB); + + numbers_list.clear(); + + numbers_list.push_back(1); + numbers_list.push_back(2); + numbers_list.push_back(3); + numbers_list.push_back(4); + + string_list text_list; + text_list.push_back(std::string("goofy")); // Optional break point at this line. + text_list.push_back(std::string("is")); + text_list.push_back(std::string("smart")); + + text_list.push_back(std::string("!!!")); + + return 0; // Set final break point at this line. +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/Makefile new file mode 100644 index 00000000000..bf8e6b8703f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +USE_LIBSTDCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py new file mode 100644 index 00000000000..94d1b573f40 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py @@ -0,0 +1,331 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StdMapDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @add_test_categories(["libstdcxx"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("frame variable ii --show-types") + + self.runCmd( + "type summary add -x \"std::map<\" --summary-string \"map has ${svar%#} items\" -e") + + self.expect('frame variable ii', + substrs=['map has 0 items', + '{}']) + + self.runCmd("c") + + self.expect('frame variable ii', + substrs=['map has 2 items', + '[0] = ', + 'first = 0', + 'second = 0', + '[1] = ', + 'first = 1', + 'second = 1']) + + self.runCmd("c") + + self.expect('frame variable ii', + substrs=['map has 4 items', + '[2] = ', + 'first = 2', + 'second = 0', + '[3] = ', + 'first = 3', + 'second = 1']) + + self.runCmd("c") + + self.expect("frame variable ii", + substrs=['map has 9 items', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) + + self.expect("p ii", + substrs=['map has 9 items', + '[5] = ', + 'first = 5', + 'second = 0', + '[7] = ', + 'first = 7', + 'second = 1']) + + # check access-by-index + self.expect("frame variable ii[0]", + substrs=['first = 0', + 'second = 0']) + self.expect("frame variable ii[3]", + substrs=['first =', + 'second =']) + + self.expect("frame variable ii[8]", matching=True, + substrs=['1234567']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("ii").MightHaveChildren(), + "ii.MightHaveChildren() says False for non empty!") + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression ii[8]", matching=False, error=True, + # substrs = ['1234567']) + + self.runCmd("c") + + self.expect('frame variable ii', + substrs=['map has 0 items', + '{}']) + + self.runCmd("frame variable si --show-types") + + self.expect('frame variable si', + substrs=['map has 0 items', + '{}']) + + self.runCmd("c") + + self.expect('frame variable si', + substrs=['map has 1 items', + '[0] = ', + 'first = \"zero\"', + 'second = 0']) + + self.runCmd("c") + + self.expect("frame variable si", + substrs=['map has 5 items', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3', + '[4] = ', + 'first = \"four\"', + 'second = 4']) + + self.expect("p si", + substrs=['map has 5 items', + '[0] = ', + 'first = \"zero\"', + 'second = 0', + '[1] = ', + 'first = \"one\"', + 'second = 1', + '[2] = ', + 'first = \"two\"', + 'second = 2', + '[3] = ', + 'first = \"three\"', + 'second = 3', + '[4] = ', + 'first = \"four\"', + 'second = 4']) + + # check access-by-index + self.expect("frame variable si[0]", + substrs=['first = ', 'four', + 'second = 4']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("si").MightHaveChildren(), + "si.MightHaveChildren() says False for non empty!") + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression si[0]", matching=False, error=True, + # substrs = ['first = ', 'zero']) + + self.runCmd("c") + + self.expect('frame variable si', + substrs=['map has 0 items', + '{}']) + + self.runCmd("frame variable is --show-types") + + self.expect('frame variable is', + substrs=['map has 0 items', + '{}']) + + self.runCmd("c") + + self.expect("frame variable is", + substrs=['map has 4 items', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) + + self.expect("p is", + substrs=['map has 4 items', + '[0] = ', + 'second = \"goofy\"', + 'first = 85', + '[1] = ', + 'second = \"is\"', + 'first = 1', + '[2] = ', + 'second = \"smart\"', + 'first = 2', + '[3] = ', + 'second = \"!!!\"', + 'first = 3']) + + # check access-by-index + self.expect("frame variable is[0]", + substrs=['first = ', + 'second =']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("is").MightHaveChildren(), + "is.MightHaveChildren() says False for non empty!") + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression is[0]", matching=False, error=True, + # substrs = ['first = ', 'goofy']) + + self.runCmd("c") + + self.expect('frame variable is', + substrs=['map has 0 items', + '{}']) + + self.runCmd("frame variable ss --show-types") + + self.expect('frame variable ss', + substrs=['map has 0 items', + '{}']) + + self.runCmd("c") + + self.expect("frame variable ss", + substrs=['map has 4 items', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"', + '[3] = ', + 'second = \"..is always a Mac!\"', + 'first = \"a Mac..\"']) + + self.expect("p ss", + substrs=['map has 4 items', + '[0] = ', + 'second = \"hello\"', + 'first = \"ciao\"', + '[1] = ', + 'second = \"house\"', + 'first = \"casa\"', + '[2] = ', + 'second = \"cat\"', + 'first = \"gatto\"', + '[3] = ', + 'second = \"..is always a Mac!\"', + 'first = \"a Mac..\"']) + + # check access-by-index + self.expect("frame variable ss[3]", + substrs=['gatto', 'cat']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("ss").MightHaveChildren(), + "ss.MightHaveChildren() says False for non empty!") + + # check that the expression parser does not make use of + # synthetic children instead of running code + # TOT clang has a fix for this, which makes the expression command here succeed + # since this would make the test fail or succeed depending on clang version in use + # this is safer commented for the time being + # self.expect("expression ss[3]", matching=False, error=True, + # substrs = ['gatto']) + + self.runCmd("c") + + self.expect('frame variable ss', + substrs=['map has 0 items', + '{}']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/main.cpp new file mode 100644 index 00000000000..d5e5b212782 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/main.cpp @@ -0,0 +1,55 @@ +#include <map> +#include <string> + +#define intint_map std::map<int, int> +#define strint_map std::map<std::string, int> +#define intstr_map std::map<int, std::string> +#define strstr_map std::map<std::string, std::string> + + +int main() +{ + intint_map ii; + + ii[0] = 0; // Set break point at this line. + ii[1] = 1; + ii[2] = 0;// Set break point at this line. + ii[3] = 1; + ii[4] = 0;// Set break point at this line. + ii[5] = 1; + ii[6] = 0; + ii[7] = 1; + ii[85] = 1234567; + + ii.clear();// Set break point at this line. + + strint_map si; + + si["zero"] = 0;// Set break point at this line. + si["one"] = 1;// Set break point at this line. + si["two"] = 2; + si["three"] = 3; + si["four"] = 4; + + si.clear();// Set break point at this line. + + intstr_map is; + + is[85] = "goofy";// Set break point at this line. + is[1] = "is"; + is[2] = "smart"; + is[3] = "!!!"; + + is.clear();// Set break point at this line. + + strstr_map ss; + + ss["ciao"] = "hello";// Set break point at this line. + ss["casa"] = "house"; + ss["gatto"] = "cat"; + ss["a Mac.."] = "..is always a Mac!"; + + ss.clear();// Set break point at this line. + + return 0;// Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/Makefile new file mode 100644 index 00000000000..654e4b15bd5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS := -O0 +USE_LIBSTDCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py new file mode 100644 index 00000000000..df213a03c72 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/TestDataFormatterStdSmartPtr.py @@ -0,0 +1,44 @@ +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StdSmartPtrDataFormatterTestCase(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libstdcxx"]) + def test_with_run_command(self): + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect("frame variable nsp", substrs=['nsp = nullptr']) + self.expect("frame variable isp", substrs=['isp = 123']) + self.expect("frame variable ssp", substrs=['ssp = "foobar"']) + + self.expect("frame variable nwp", substrs=['nwp = nullptr']) + self.expect("frame variable iwp", substrs=['iwp = 123']) + self.expect("frame variable swp", substrs=['swp = "foobar"']) + + self.runCmd("continue") + + self.expect("frame variable nsp", substrs=['nsp = nullptr']) + self.expect("frame variable isp", substrs=['isp = nullptr']) + self.expect("frame variable ssp", substrs=['ssp = nullptr']) + + self.expect("frame variable nwp", substrs=['nwp = nullptr']) + self.expect("frame variable iwp", substrs=['iwp = nullptr']) + self.expect("frame variable swp", substrs=['swp = nullptr']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/main.cpp new file mode 100644 index 00000000000..7ba50875a6d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/smart_ptr/main.cpp @@ -0,0 +1,20 @@ +#include <memory> +#include <string> + +int +main() +{ + std::shared_ptr<char> nsp; + std::shared_ptr<int> isp(new int{123}); + std::shared_ptr<std::string> ssp = std::make_shared<std::string>("foobar"); + + std::weak_ptr<char> nwp; + std::weak_ptr<int> iwp = isp; + std::weak_ptr<std::string> swp = ssp; + + nsp.reset(); // Set break point at this line. + isp.reset(); + ssp.reset(); + + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/Makefile new file mode 100644 index 00000000000..c825977b1a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +CFLAGS_EXTRAS := -O0 +USE_LIBSTDCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py new file mode 100644 index 00000000000..fa0e4d12398 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py @@ -0,0 +1,85 @@ +# coding=utf8 +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StdStringDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @add_test_categories(["libstdcxx"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_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=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + var_wempty = self.frame().FindVariable('wempty') + var_s = self.frame().FindVariable('s') + var_S = self.frame().FindVariable('S') + var_mazeltov = self.frame().FindVariable('mazeltov') + var_empty = self.frame().FindVariable('empty') + var_q = self.frame().FindVariable('q') + var_Q = self.frame().FindVariable('Q') + var_uchar = self.frame().FindVariable('uchar') + + # TODO: This is currently broken + # self.assertEqual(var_wempty.GetSummary(), 'L""', "wempty summary wrong") + self.assertEqual( + var_s.GetSummary(), 'L"hello world! מזל טוב!"', + "s summary wrong") + self.assertEqual(var_S.GetSummary(), 'L"!!!!"', "S summary wrong") + self.assertEqual( + var_mazeltov.GetSummary(), 'L"מזל טוב"', + "mazeltov summary wrong") + self.assertEqual(var_empty.GetSummary(), '""', "empty summary wrong") + self.assertEqual( + var_q.GetSummary(), '"hello world"', + "q summary wrong") + self.assertEqual( + var_Q.GetSummary(), '"quite a long std::strin with lots of info inside it"', + "Q summary wrong") + self.assertEqual(var_uchar.GetSummary(), '"aaaaa"', "u summary wrong") + + self.runCmd("next") + + self.assertEqual( + var_S.GetSummary(), 'L"!!!!!"', + "new S summary wrong") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/main.cpp new file mode 100644 index 00000000000..73519197d8c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/main.cpp @@ -0,0 +1,15 @@ +#include <string> + +int main() +{ + std::wstring wempty(L""); + std::wstring s(L"hello world! מזל טוב!"); + std::wstring S(L"!!!!"); + const wchar_t *mazeltov = L"מזל טוב"; + std::string empty(""); + std::string q("hello world"); + std::string Q("quite a long std::strin with lots of info inside it"); + std::basic_string<unsigned char> uchar(5, 'a'); + S.assign(L"!!!!!"); // Set break point at this line. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/Makefile new file mode 100644 index 00000000000..bf8e6b8703f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +USE_LIBSTDCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/TestDataFormatterStdTuple.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/TestDataFormatterStdTuple.py new file mode 100644 index 00000000000..c71cffe788a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/TestDataFormatterStdTuple.py @@ -0,0 +1,44 @@ +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StdTupleDataFormatterTestCase(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libstdcxx"]) + def test_with_run_command(self): + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + frame = self.frame() + self.assertTrue(frame.IsValid()) + + self.expect("frame variable ti", substrs=['[0] = 1']) + self.expect("frame variable ts", substrs=['[0] = "foobar"']) + self.expect("frame variable tt", substrs=['[0] = 1', '[1] = "baz"', '[2] = 2']) + + self.assertEqual(1, frame.GetValueForVariablePath("ti[0]").GetValueAsUnsigned()) + self.assertFalse(frame.GetValueForVariablePath("ti[1]").IsValid()) + + self.assertEqual('"foobar"', frame.GetValueForVariablePath("ts[0]").GetSummary()) + self.assertFalse(frame.GetValueForVariablePath("ts[1]").IsValid()) + + self.assertEqual(1, frame.GetValueForVariablePath("tt[0]").GetValueAsUnsigned()) + self.assertEqual('"baz"', frame.GetValueForVariablePath("tt[1]").GetSummary()) + self.assertEqual(2, frame.GetValueForVariablePath("tt[2]").GetValueAsUnsigned()) + self.assertFalse(frame.GetValueForVariablePath("tt[3]").IsValid()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/main.cpp new file mode 100644 index 00000000000..7247742ee6b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/tuple/main.cpp @@ -0,0 +1,9 @@ +#include <memory> +#include <string> + +int main() { + std::tuple<int> ti{1}; + std::tuple<std::string> ts{"foobar"}; + std::tuple<int, std::string, int> tt{1, "baz", 2}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/Makefile new file mode 100644 index 00000000000..bf8e6b8703f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +USE_LIBSTDCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/TestDataFormatterStdUniquePtr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/TestDataFormatterStdUniquePtr.py new file mode 100644 index 00000000000..2ead4fab559 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/TestDataFormatterStdUniquePtr.py @@ -0,0 +1,93 @@ +""" +Test lldb data formatter subsystem. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StdUniquePtrDataFormatterTestCase(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["libstdcxx"]) + def test_with_run_command(self): + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + frame = self.frame() + self.assertTrue(frame.IsValid()) + + self.expect("frame variable nup", substrs=['nup = nullptr']) + self.expect("frame variable iup", substrs=['iup = 0x']) + self.expect("frame variable sup", substrs=['sup = 0x']) + + self.expect("frame variable ndp", substrs=['ndp = nullptr']) + self.expect("frame variable idp", substrs=['idp = 0x', 'deleter = ', 'a = 1', 'b = 2']) + self.expect("frame variable sdp", substrs=['sdp = 0x', 'deleter = ', 'a = 3', 'b = 4']) + + self.assertEqual(123, frame.GetValueForVariablePath("iup.object").GetValueAsUnsigned()) + self.assertEqual(123, frame.GetValueForVariablePath("*iup").GetValueAsUnsigned()) + self.assertFalse(frame.GetValueForVariablePath("iup.deleter").IsValid()) + + self.assertEqual('"foobar"', frame.GetValueForVariablePath("sup.object").GetSummary()) + self.assertEqual('"foobar"', frame.GetValueForVariablePath("*sup").GetSummary()) + self.assertFalse(frame.GetValueForVariablePath("sup.deleter").IsValid()) + + self.assertEqual(456, frame.GetValueForVariablePath("idp.object").GetValueAsUnsigned()) + self.assertEqual(456, frame.GetValueForVariablePath("*idp").GetValueAsUnsigned()) + self.assertEqual('"baz"', frame.GetValueForVariablePath("sdp.object").GetSummary()) + self.assertEqual('"baz"', frame.GetValueForVariablePath("*sdp").GetSummary()) + + idp_deleter = frame.GetValueForVariablePath("idp.deleter") + self.assertTrue(idp_deleter.IsValid()) + self.assertEqual(1, idp_deleter.GetChildMemberWithName("a").GetValueAsUnsigned()) + self.assertEqual(2, idp_deleter.GetChildMemberWithName("b").GetValueAsUnsigned()) + + sdp_deleter = frame.GetValueForVariablePath("sdp.deleter") + self.assertTrue(sdp_deleter.IsValid()) + self.assertEqual(3, sdp_deleter.GetChildMemberWithName("a").GetValueAsUnsigned()) + self.assertEqual(4, sdp_deleter.GetChildMemberWithName("b").GetValueAsUnsigned()) + + @skipIfFreeBSD + @skipIfWindows # libstdcpp not ported to Windows + @skipIfDarwin # doesn't compile on Darwin + @skipIfwatchOS # libstdcpp not ported to watchos + @add_test_categories(["libstdcxx"]) + def test_recursive_unique_ptr(self): + # Tests that LLDB can handle when we have a loop in the unique_ptr + # reference chain and that it correctly handles the different options + # for the frame variable command in this case. + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") + self.runCmd("run", RUN_SUCCEEDED) + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect("frame variable f1->fp", + substrs=['fp = 0x']) + self.expect("frame variable --ptr-depth=1 f1->fp", + substrs=['data = 2', 'fp = 0x']) + self.expect("frame variable --ptr-depth=2 f1->fp", + substrs=['data = 2', 'fp = 0x', 'data = 1']) + + frame = self.frame() + self.assertTrue(frame.IsValid()) + self.assertEqual(2, frame.GetValueForVariablePath("f1->fp.object.data").GetValueAsUnsigned()) + self.assertEqual(2, frame.GetValueForVariablePath("f1->fp->data").GetValueAsUnsigned()) + self.assertEqual(1, frame.GetValueForVariablePath("f1->fp.object.fp.object.data").GetValueAsUnsigned()) + self.assertEqual(1, frame.GetValueForVariablePath("f1->fp->fp->data").GetValueAsUnsigned()) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/TestDataFormatterInvalidStdUniquePtr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/TestDataFormatterInvalidStdUniquePtr.py new file mode 100644 index 00000000000..190cf78a3b4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/TestDataFormatterInvalidStdUniquePtr.py @@ -0,0 +1,5 @@ +import lldbsuite.test.lldbinline as lldbinline +from lldbsuite.test.decorators import * + +lldbinline.MakeInlineTest(__file__, globals(), [no_debug_info_test]) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/main.cpp new file mode 100644 index 00000000000..b12cab23169 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/invalid/main.cpp @@ -0,0 +1,11 @@ +// Test that we don't crash when trying to pretty-print structures that don't +// have the layout our data formatters expect. +namespace std { +template<typename T, typename Deleter = void> +class unique_ptr {}; +} + +int main() { + std::unique_ptr<int> U; + return 0; //% self.expect("frame variable U", substrs=["unique_ptr", "{}"]) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/main.cpp new file mode 100644 index 00000000000..dd0072764d4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/unique_ptr/main.cpp @@ -0,0 +1,35 @@ +#include <memory> +#include <string> + +struct Deleter { + void operator()(void *) {} + + int a; + int b; +}; + +struct Foo { + int data; + std::unique_ptr<Foo> fp; +}; + +int main() { + std::unique_ptr<char> nup; + std::unique_ptr<int> iup(new int{123}); + std::unique_ptr<std::string> sup(new std::string("foobar")); + + std::unique_ptr<char, Deleter> ndp; + std::unique_ptr<int, Deleter> idp(new int{456}, Deleter{1, 2}); + std::unique_ptr<std::string, Deleter> sdp(new std::string("baz"), + Deleter{3, 4}); + + std::unique_ptr<Foo> fp(new Foo{3}); + + // Set up a structure where we have a loop in the unique_ptr chain. + Foo* f1 = new Foo{1}; + Foo* f2 = new Foo{2}; + f1->fp.reset(f2); + f2->fp.reset(f1); + + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/Makefile new file mode 100644 index 00000000000..c825977b1a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +CFLAGS_EXTRAS := -O0 +USE_LIBSTDCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py new file mode 100644 index 00000000000..5a767b34c23 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py @@ -0,0 +1,75 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StdVBoolDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @add_test_categories(["libstdcxx"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_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=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.expect( + "frame variable vBool", + substrs=[ + 'size=49', + '[0] = false', + '[1] = true', + '[18] = false', + '[27] = true', + '[36] = false', + '[47] = true', + '[48] = true']) + + self.expect( + "expr vBool", + substrs=[ + 'size=49', + '[0] = false', + '[1] = true', + '[18] = false', + '[27] = true', + '[36] = false', + '[47] = true', + '[48] = true']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/main.cpp new file mode 100644 index 00000000000..73956dd3fda --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/main.cpp @@ -0,0 +1,63 @@ +#include <vector> + +int main() +{ + std::vector<bool> vBool; + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(false); + vBool.push_back(true); + vBool.push_back(true); + + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/Makefile new file mode 100644 index 00000000000..654e4b15bd5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS := -O0 +USE_LIBSTDCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py new file mode 100644 index 00000000000..27cdf1e73ac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py @@ -0,0 +1,213 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StdVectorDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + @add_test_categories(["libstdcxx"]) + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp( + self, "Set break point at this line.") + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # empty vectors (and storage pointers SHOULD BOTH BE NULL..) + self.expect("frame variable numbers", + substrs=['numbers = size=0']) + + self.runCmd("c") + + # first value added + self.expect("frame variable numbers", + substrs=['numbers = size=1', + '[0] = 1', + '}']) + + # add some more data + self.runCmd("c") + + self.expect("frame variable numbers", + substrs=['numbers = size=4', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '}']) + + self.expect("p numbers", + substrs=['$', 'size=4', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '}']) + + # check access to synthetic children + self.runCmd( + "type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect") + self.expect('frame variable numbers', + substrs=['item 0 is 1']) + + self.runCmd( + "type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect") + #import time + # time.sleep(19) + self.expect('frame variable numbers', + substrs=['item 0 is 1']) + # move on with synths + self.runCmd("type summary delete std::int_vect") + self.runCmd("type summary delete int_vect") + + # add some more data + self.runCmd("c") + + self.expect("frame variable numbers", + substrs=['numbers = size=7', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '[4] = 12345', + '[5] = 123456', + '[6] = 1234567', + '}']) + + self.expect("p numbers", + substrs=['$', 'size=7', + '[0] = 1', + '[1] = 12', + '[2] = 123', + '[3] = 1234', + '[4] = 12345', + '[5] = 123456', + '[6] = 1234567', + '}']) + + # check access-by-index + self.expect("frame variable numbers[0]", + substrs=['1']) + self.expect("frame variable numbers[1]", + substrs=['12']) + self.expect("frame variable numbers[2]", + substrs=['123']) + self.expect("frame variable numbers[3]", + substrs=['1234']) + + # but check that expression does not rely on us + # (when expression gets to call into STL code correctly, we will have to find + # another way to check this) + self.expect("expression numbers[6]", matching=False, error=True, + substrs=['1234567']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("numbers").MightHaveChildren(), + "numbers.MightHaveChildren() says False for non empty!") + + # clear out the vector and see that we do the right thing once again + self.runCmd("c") + + self.expect("frame variable numbers", + substrs=['numbers = size=0']) + + self.runCmd("c") + + # first value added + self.expect("frame variable numbers", + substrs=['numbers = size=1', + '[0] = 7', + '}']) + + # check if we can display strings + self.runCmd("c") + + self.expect("frame variable strings", + substrs=['goofy', + 'is', + 'smart']) + + self.expect("p strings", + substrs=['goofy', + 'is', + 'smart']) + + # test summaries based on synthetic children + self.runCmd( + "type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e") + self.expect("frame variable strings", + substrs=['vector has 3 items', + 'goofy', + 'is', + 'smart']) + + self.expect("p strings", + substrs=['vector has 3 items', + 'goofy', + 'is', + 'smart']) + + self.runCmd("c") + + self.expect("frame variable strings", + substrs=['vector has 4 items']) + + # check access-by-index + self.expect("frame variable strings[0]", + substrs=['goofy']) + self.expect("frame variable strings[1]", + substrs=['is']) + + # but check that expression does not rely on us + # (when expression gets to call into STL code correctly, we will have to find + # another way to check this) + self.expect("expression strings[0]", matching=False, error=True, + substrs=['goofy']) + + # check that MightHaveChildren() gets it right + self.assertTrue( + self.frame().FindVariable("strings").MightHaveChildren(), + "strings.MightHaveChildren() says False for non empty!") + + self.runCmd("c") + + self.expect("frame variable strings", + substrs=['vector has 0 items']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/main.cpp new file mode 100644 index 00000000000..010917995e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/main.cpp @@ -0,0 +1,31 @@ +#include <string> +#include <vector> +typedef std::vector<int> int_vect; +typedef std::vector<std::string> string_vect; + +int main() +{ + int_vect numbers; + numbers.push_back(1); // Set break point at this line. + numbers.push_back(12); // Set break point at this line. + numbers.push_back(123); + numbers.push_back(1234); + numbers.push_back(12345); // Set break point at this line. + numbers.push_back(123456); + numbers.push_back(1234567); + + numbers.clear(); // Set break point at this line. + + numbers.push_back(7); // Set break point at this line. + + string_vect strings; // Set break point at this line. + strings.push_back(std::string("goofy")); + strings.push_back(std::string("is")); + strings.push_back(std::string("smart")); + + strings.push_back(std::string("!!!")); // Set break point at this line. + + strings.clear(); // Set break point at this line. + + return 0;// Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py new file mode 100644 index 00000000000..51d42fc5e7b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py @@ -0,0 +1,217 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class SynthDataFormatterTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Pick some values and check that the basics work + self.runCmd("type filter add BagOfInts --child x --child z") + self.expect("frame variable int_bag", + substrs=['x = 6', + 'z = 8']) + + # Check we can still access the missing child by summary + self.runCmd( + "type summary add BagOfInts --summary-string \"y=${var.y}\"") + self.expect('frame variable int_bag', + substrs=['y=7']) + + # Even if we have synth children, the summary prevails + self.expect("frame variable int_bag", matching=False, + substrs=['x = 6', + 'z = 8']) + + # if we skip synth and summary show y + self.expect( + "frame variable int_bag --synthetic-type false --no-summary-depth=1", + substrs=[ + 'x = 6', + 'y = 7', + 'z = 8']) + + # if we ask for raw output same happens + self.expect("frame variable int_bag --raw-output", + substrs=['x = 6', + 'y = 7', + 'z = 8']) + + # Summary+Synth must work together + self.runCmd( + "type summary add BagOfInts --summary-string \"x=${var.x}\" -e") + self.expect('frame variable int_bag', + substrs=['x=6', + 'x = 6', + 'z = 8']) + + # Same output, but using Python + self.runCmd( + "type summary add BagOfInts --python-script \"return 'x=%s' % valobj.GetChildMemberWithName('x').GetValue()\" -e") + self.expect('frame variable int_bag', + substrs=['x=6', + 'x = 6', + 'z = 8']) + + # If I skip summaries, still give me the artificial children + self.expect("frame variable int_bag --no-summary-depth=1", + substrs=['x = 6', + 'z = 8']) + + # Delete synth and check that the view reflects it immediately + self.runCmd("type filter delete BagOfInts") + self.expect("frame variable int_bag", + substrs=['x = 6', + 'y = 7', + 'z = 8']) + + # Add the synth again and check that it's honored deeper in the + # hierarchy + self.runCmd("type filter add BagOfInts --child x --child z") + self.expect('frame variable bag_bag', + substrs=['x = x=69 {', + 'x = 69', + 'z = 71', + 'y = x=66 {', + 'x = 66', + 'z = 68']) + self.expect('frame variable bag_bag', matching=False, + substrs=['y = 70', + 'y = 67']) + + # Check that a synth can expand nested stuff + self.runCmd("type filter add BagOfBags --child x.y --child y.z") + self.expect('frame variable bag_bag', + substrs=['x.y = 70', + 'y.z = 68']) + + # ...even if we get -> and . wrong + self.runCmd("type filter add BagOfBags --child x.y --child \"y->z\"") + self.expect('frame variable bag_bag', + substrs=['x.y = 70', + 'y->z = 68']) + + # ...even bitfields + self.runCmd( + "type filter add BagOfBags --child x.y --child \"y->z[1-2]\"") + self.expect('frame variable bag_bag --show-types', + substrs=['x.y = 70', + '(int:2) y->z[1-2] = 2']) + + # ...even if we format the bitfields + self.runCmd( + "type filter add BagOfBags --child x.y --child \"y->y[0-0]\"") + self.runCmd("type format add \"int:1\" -f bool") + self.expect('frame variable bag_bag --show-types', + substrs=['x.y = 70', + '(int:1) y->y[0-0] = true']) + + # ...even if we use one-liner summaries + self.runCmd("type summary add -c BagOfBags") + self.expect('frame variable bag_bag', substrs=[ + '(BagOfBags) bag_bag = (x.y = 70, y->y[0-0] = true)']) + + self.runCmd("type summary delete BagOfBags") + + # now check we are dynamic (and arrays work) + self.runCmd( + "type filter add Plenty --child bitfield --child array[0] --child array[2]") + self.expect('frame variable plenty_of_stuff', + substrs=['bitfield = 1', + 'array[0] = 5', + 'array[2] = 3']) + + self.runCmd("n") + self.expect('frame variable plenty_of_stuff', + substrs=['bitfield = 17', + 'array[0] = 5', + 'array[2] = 3']) + + # skip synthetic children + self.expect('frame variable plenty_of_stuff --synthetic-type no', + substrs=['some_values = 0x', + 'array = 0x', + 'array_size = 5']) + + # check flat printing with synthetic children + self.expect('frame variable plenty_of_stuff --flat', + substrs=['plenty_of_stuff.bitfield = 17', + '*(plenty_of_stuff.array) = 5', + '*(plenty_of_stuff.array) = 3']) + + # check that we do not lose location information for our children + self.expect('frame variable plenty_of_stuff --location', + substrs=['0x', + ': bitfield = 17']) + + # check we work across pointer boundaries + self.expect('frame variable plenty_of_stuff.some_values --ptr-depth=1', + substrs=['(BagOfInts *) plenty_of_stuff.some_values', + 'x = 5', + 'z = 7']) + + # but not if we don't want to + self.runCmd("type filter add BagOfInts --child x --child z -p") + self.expect('frame variable plenty_of_stuff.some_values --ptr-depth=1', + substrs=['(BagOfInts *) plenty_of_stuff.some_values', + 'x = 5', + 'y = 6', + 'z = 7']) + + # check we're dynamic even if nested + self.runCmd("type filter add BagOfBags --child x.z") + self.expect('frame variable bag_bag', + substrs=['x.z = 71']) + + self.runCmd("n") + self.expect('frame variable bag_bag', + substrs=['x.z = 12']) + + self.runCmd( + 'type summary add -e -s "I am always empty but have" EmptyStruct') + self.expect('frame variable es', substrs=[ + "I am always empty but have {}"]) + self.runCmd('type summary add -e -h -s "I am really empty" EmptyStruct') + self.expect('frame variable es', substrs=["I am really empty"]) + self.expect( + 'frame variable es', + substrs=["I am really empty {}"], + matching=False) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/main.cpp new file mode 100644 index 00000000000..acb90323b6c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/main.cpp @@ -0,0 +1,85 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> + +struct BagOfInts +{ + int x; + int y; + int z; + BagOfInts(int X) : + x(X), + y(X+1), + z(X+2) {} +}; + +struct BagOfFloats +{ + float x; + float y; + float z; + BagOfFloats(float X) : + x(X+0.334), + y(X+0.500), + z(X+0.667) {} +}; + +struct BagOfBags +{ + BagOfInts x; + BagOfInts y; + BagOfFloats z; + BagOfFloats q; + BagOfBags() : + x('E'), + y('B'), + z(1.1), + q(20.11) {} +}; + +struct EmptyStruct {}; + +struct Plenty +{ + BagOfInts *some_values; + int* array; + int array_size; + int bitfield; + + Plenty(int N, bool flagA, bool flagB) : + some_values(new BagOfInts(N)), + array(new int[N]), + array_size(N), + bitfield( (flagA ? 0x01 : 0x00) | (flagB ? 0x10 : 0x00) ) + { + for (int j = 0; j < N; j++) + array[j] = N-j; + } +}; + +int main (int argc, const char * argv[]) +{ + BagOfInts int_bag(6); + BagOfFloats float_bag(2.71); + + BagOfBags bag_bag; + EmptyStruct es; + + Plenty plenty_of_stuff(5,true,false); + + plenty_of_stuff.bitfield = 0x11; // Set break point at this line. + + bag_bag.x.z = 12; + + return 0; + +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py new file mode 100644 index 00000000000..2c7d5b2d0e1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/TestDataFormatterSynthType.py @@ -0,0 +1,55 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DataFormatterSynthTypeTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', 'break here') + + @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser + def test_with_run_command(self): + """Test using Python synthetic children provider to provide a typename.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("script from myIntSynthProvider import *") + self.runCmd("type synth add -l myIntSynthProvider myInt") + + self.expect('frame variable x', substrs=['ThisTestPasses']) + self.expect('frame variable y', substrs=['ThisTestPasses']) + self.expect('frame variable z', substrs=['ThisTestPasses']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/main.cpp new file mode 100644 index 00000000000..accbf0a5a57 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/main.cpp @@ -0,0 +1,29 @@ +class myInt { + private: int theValue; + public: myInt() : theValue(0) {} + public: myInt(int _x) : theValue(_x) {} + int val() { return theValue; } +}; + +class myArray { +public: + int array[16]; +}; + +class hasAnInt { + public: + myInt theInt; + hasAnInt() : theInt(42) {} +}; + +myInt operator + (myInt x, myInt y) { return myInt(x.val() + y.val()); } + +int main() { + myInt x{3}; + myInt y{4}; + myInt z {x+y}; + hasAnInt hi; + myArray ma; + + return z.val(); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py new file mode 100644 index 00000000000..fa47ca2cfe6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthtype/myIntSynthProvider.py @@ -0,0 +1,44 @@ +class myIntSynthProvider(object): + + def __init__(self, valobj, dict): + self.valobj = valobj + self.val = self.valobj.GetChildMemberWithName("theValue") + + def num_children(self): + return 0 + + def get_child_at_index(self, index): + return None + + def get_child_index(self, name): + return None + + def update(self): + return False + + def has_children(self): + return False + + def get_type_name(self): + return "ThisTestPasses" + + +class myArraySynthProvider(object): + + def __init__(self, valobj, dict): + self.valobj = valobj + self.array = self.valobj.GetChildMemberWithName("array") + + def num_children(self, max_count): + if 16 < max_count: + return 16 + return max_count + + def get_child_at_index(self, index): + return None # Keep it simple when this is not tested here. + + def get_child_index(self, name): + return None # Keep it simple when this is not tested here. + + def has_children(self): + return True diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py new file mode 100644 index 00000000000..fc7ffa0e78f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py @@ -0,0 +1,117 @@ +""" +Test lldb data formatter subsystem. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DataFormatterSynthValueTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', 'break here') + + @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser + def test_with_run_command(self): + """Test using Python synthetic children provider to provide a value.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + x = self.frame().FindVariable("x") + x.SetPreferSyntheticValue(True) + y = self.frame().FindVariable("y") + y.SetPreferSyntheticValue(True) + z = self.frame().FindVariable("z") + z.SetPreferSyntheticValue(True) + q = self.frame().FindVariable("q") + z.SetPreferSyntheticValue(True) + + x_val = x.GetValueAsUnsigned + y_val = y.GetValueAsUnsigned + z_val = z.GetValueAsUnsigned + q_val = q.GetValueAsUnsigned + + if self.TraceOn(): + print( + "x_val = %s; y_val = %s; z_val = %s; q_val = %s" % + (x_val(), y_val(), z_val(), q_val())) + + self.assertFalse(x_val() == 3, "x == 3 before synthetics") + self.assertFalse(y_val() == 4, "y == 4 before synthetics") + self.assertFalse(z_val() == 7, "z == 7 before synthetics") + self.assertFalse(q_val() == 8, "q == 8 before synthetics") + + # now set up the synth + self.runCmd("script from myIntSynthProvider import *") + self.runCmd("type synth add -l myIntSynthProvider myInt") + self.runCmd("type synth add -l myArraySynthProvider myArray") + self.runCmd("type synth add -l myIntSynthProvider myIntAndStuff") + + if self.TraceOn(): + print( + "x_val = %s; y_val = %s; z_val = %s; q_val = %s" % + (x_val(), y_val(), z_val(), q_val())) + + self.assertTrue(x_val() == 3, "x != 3 after synthetics") + self.assertTrue(y_val() == 4, "y != 4 after synthetics") + self.assertTrue(z_val() == 7, "z != 7 after synthetics") + self.assertTrue(q_val() == 8, "q != 8 after synthetics") + + self.expect("frame variable x", substrs=['3']) + self.expect( + "frame variable x", + substrs=['theValue = 3'], + matching=False) + self.expect("frame variable q", substrs=['8']) + self.expect( + "frame variable q", + substrs=['theValue = 8'], + matching=False) + + # check that an aptly defined synthetic provider does not affect + # one-lining + self.expect( + "expression struct Struct { myInt theInt{12}; }; Struct()", + substrs=['(theInt = 12)']) + + # check that we can use a synthetic value in a summary + self.runCmd("type summary add hasAnInt -s ${var.theInt}") + hi = self.frame().FindVariable("hi") + self.assertEqual(hi.GetSummary(), "42") + + ma = self.frame().FindVariable("ma") + self.assertTrue(ma.IsValid()) + self.assertEqual(ma.GetNumChildren(15), 15) + self.assertEqual(ma.GetNumChildren(16), 16) + self.assertEqual(ma.GetNumChildren(17), 16) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/main.cpp new file mode 100644 index 00000000000..1a5925a05a6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/main.cpp @@ -0,0 +1,41 @@ +class myInt { + private: int theValue; + public: myInt() : theValue(0) {} + public: myInt(int _x) : theValue(_x) {} + int val() { return theValue; } +}; + +class myIntAndStuff { +private: + int theValue; + double theExtraFluff; +public: + myIntAndStuff() : theValue(0), theExtraFluff(1.25) {} + myIntAndStuff(int _x) : theValue(_x), theExtraFluff(1.25) {} + int val() { return theValue; } +}; + +class myArray { +public: + int array[16]; +}; + +class hasAnInt { + public: + myInt theInt; + hasAnInt() : theInt(42) {} +}; + +myInt operator + (myInt x, myInt y) { return myInt(x.val() + y.val()); } +myInt operator + (myInt x, myIntAndStuff y) { return myInt(x.val() + y.val()); } + +int main() { + myInt x{3}; + myInt y{4}; + myInt z {x+y}; + myIntAndStuff q {z.val()+1}; + hasAnInt hi; + myArray ma; + + return z.val(); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py new file mode 100644 index 00000000000..82da6f9da92 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py @@ -0,0 +1,44 @@ +class myIntSynthProvider(object): + + def __init__(self, valobj, dict): + self.valobj = valobj + self.val = self.valobj.GetChildMemberWithName("theValue") + + def num_children(self): + return 0 + + def get_child_at_index(self, index): + return None + + def get_child_index(self, name): + return None + + def update(self): + return False + + def has_children(self): + return False + + def get_value(self): + return self.val + + +class myArraySynthProvider(object): + + def __init__(self, valobj, dict): + self.valobj = valobj + self.array = self.valobj.GetChildMemberWithName("array") + + def num_children(self, max_count): + if 16 < max_count: + return 16 + return max_count + + def get_child_at_index(self, index): + return None # Keep it simple when this is not tested here. + + def get_child_index(self, name): + return None # Keep it simple when this is not tested here. + + def has_children(self): + return True diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py new file mode 100644 index 00000000000..734e711fb7f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py @@ -0,0 +1,8 @@ +from __future__ import absolute_import + +from lldbsuite.test import lldbinline + +lldbinline.MakeInlineTest( + __file__, globals(), [ + lldbinline.expectedFailureAll( + oslist=["windows"], bugnumber="llvm.org/pr24663")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/main.cpp new file mode 100644 index 00000000000..c59e9f0ee72 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/main.cpp @@ -0,0 +1,34 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +class Base { +public: + Base () = default; + virtual int func() { return 1; } + virtual ~Base() = default; +}; + +class Derived : public Base { +private: + int m_derived_data; +public: + Derived () : Base(), m_derived_data(0x0fedbeef) {} + virtual ~Derived() = default; + virtual int func() { return m_derived_data; } +}; + +int main (int argc, char const *argv[]) +{ + Base *base = new Derived(); + return 0; //% stream = lldb.SBStream() + //% base = self.frame().FindVariable("base") + //% base.SetPreferDynamicValue(lldb.eDynamicDontRunTarget) + //% base.GetDescription(stream) + //% if self.TraceOn(): print(stream.GetData()) + //% self.assertTrue(stream.GetData().startswith("(Derived *")) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py new file mode 100644 index 00000000000..8994831216b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py @@ -0,0 +1,82 @@ +""" +Check if changing Format on an SBValue correctly propagates that new format to children as it should +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class FormatPropagationTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + # rdar://problem/14035604 + def test_with_run_command(self): + """Check for an issue where capping does not work because the Target pointer appears to be changing behind our backs.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + pass + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # extract the parent and the children + frame = self.frame() + parent = self.frame().FindVariable("f") + self.assertTrue( + parent is not None and parent.IsValid(), + "could not find f") + X = parent.GetChildMemberWithName("X") + self.assertTrue(X is not None and X.IsValid(), "could not find X") + Y = parent.GetChildMemberWithName("Y") + self.assertTrue(Y is not None and Y.IsValid(), "could not find Y") + # check their values now + self.assertTrue(X.GetValue() == "1", "X has an invalid value") + self.assertTrue(Y.GetValue() == "2", "Y has an invalid value") + # set the format on the parent + parent.SetFormat(lldb.eFormatHex) + self.assertTrue( + X.GetValue() == "0x00000001", + "X has not changed format") + self.assertTrue( + Y.GetValue() == "0x00000002", + "Y has not changed format") + # Step and check if the values make sense still + self.runCmd("next") + self.assertTrue(X.GetValue() == "0x00000004", "X has not become 4") + self.assertTrue(Y.GetValue() == "0x00000002", "Y has not stuck as hex") + # Check that children can still make their own choices + Y.SetFormat(lldb.eFormatDecimal) + self.assertTrue(X.GetValue() == "0x00000004", "X is still hex") + self.assertTrue(Y.GetValue() == "2", "Y has not been reset") + # Make a few more changes + parent.SetFormat(lldb.eFormatDefault) + X.SetFormat(lldb.eFormatHex) + Y.SetFormat(lldb.eFormatDefault) + self.assertTrue( + X.GetValue() == "0x00000004", + "X is not hex as it asked") + self.assertTrue(Y.GetValue() == "2", "Y is not defaulted") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/main.cpp new file mode 100644 index 00000000000..5822fbc2a71 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/main.cpp @@ -0,0 +1,13 @@ +struct foo +{ + int X; + int Y; + foo(int a, int b) : X(a), Y(b) {} +}; + +int main() +{ + foo f(1,2); + f.X = 4; // Set break point at this line. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py new file mode 100644 index 00000000000..a6a61f1d7bd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py @@ -0,0 +1,37 @@ +""" +Test that the user can input a format but it will not prevail over summary format's choices. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class FrameFormatSmallStructTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that the user can input a format but it will not prevail over summary format's choices.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("thread list", substrs=['addPair(p=(x = 3, y = -3))']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/main.cpp new file mode 100644 index 00000000000..a77f2c42e8d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/main.cpp @@ -0,0 +1,24 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +struct Pair { + int x; + int y; + + Pair(int _x, int _y) : x(_x), y(_y) {} +}; + +int addPair(Pair p) +{ + return p.x + p.y; // Set break point at this line. +} + +int main() { + Pair p1(3,-3); + return addPair(p1); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py new file mode 100644 index 00000000000..80a02d06cfe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py @@ -0,0 +1,86 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class DataFormatterHexCapsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format delete hex', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("type format add -f uppercase int") + + self.expect('frame variable mine', + substrs=['mine = ', + 'first = 0x001122AA', 'second = 0x1122BB44']) + + self.runCmd("type format add -f hex int") + + self.expect('frame variable mine', + substrs=['mine = ', + 'first = 0x001122aa', 'second = 0x1122bb44']) + + self.runCmd("type format delete int") + + self.runCmd( + "type summary add -s \"${var.first%X} and ${var.second%x}\" foo") + + self.expect('frame variable mine', + substrs=['(foo) mine = 0x001122AA and 0x1122bb44']) + + self.runCmd( + "type summary add -s \"${var.first%X} and ${var.second%X}\" foo") + self.runCmd("next") + self.runCmd("next") + self.expect('frame variable mine', + substrs=['(foo) mine = 0xAABBCCDD and 0x1122BB44']) + + self.runCmd( + "type summary add -s \"${var.first%x} and ${var.second%X}\" foo") + self.expect('frame variable mine', + substrs=['(foo) mine = 0xaabbccdd and 0x1122BB44']) + self.runCmd("next") + self.runCmd("next") + self.runCmd( + "type summary add -s \"${var.first%x} and ${var.second%x}\" foo") + self.expect('frame variable mine', + substrs=['(foo) mine = 0xaabbccdd and 0xff00ff00']) + self.runCmd( + "type summary add -s \"${var.first%X} and ${var.second%X}\" foo") + self.expect('frame variable mine', + substrs=['(foo) mine = 0xAABBCCDD and 0xFF00FF00']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/main.cpp new file mode 100644 index 00000000000..fc4204b1984 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/main.cpp @@ -0,0 +1,27 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +struct foo +{ + int first; + int second; +}; + +int main () +{ + struct foo mine = {0x001122AA, 0x1122BB44}; + printf("main.first = 0x%8.8x, main.second = 0x%8.8x\n", mine.first, mine.second); + mine.first = 0xAABBCCDD; // Set break point at this line. + printf("main.first = 0x%8.8x, main.second = 0x%8.8x\n", mine.first, mine.second); + mine.second = 0xFF00FF00; + printf("main.first = 0x%8.8x, main.second = 0x%8.8x\n", mine.first, mine.second); + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py new file mode 100644 index 00000000000..62bd058666b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py @@ -0,0 +1,83 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class LanguageCategoryUpdatesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// break here') + + def test_with_run_command(self): + """Test that LLDB correctly cleans caches when language categories change.""" + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + if hasattr( + self, + 'type_category') and hasattr( + self, + 'type_specifier'): + self.type_category.DeleteTypeSummary(self.type_specifier) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect( + "frame variable", + substrs=[ + '(S)', + 'object', + '123', + '456'], + matching=True) + + self.type_category = self.dbg.GetCategory( + lldb.eLanguageTypeC_plus_plus) + type_summary = lldb.SBTypeSummary.CreateWithSummaryString( + "this is an object of type S") + self.type_specifier = lldb.SBTypeNameSpecifier('S') + self.type_category.AddTypeSummary(self.type_specifier, type_summary) + + self.expect( + "frame variable", + substrs=['this is an object of type S'], + matching=True) + + self.type_category.DeleteTypeSummary(self.type_specifier) + self.expect( + "frame variable", + substrs=['this is an object of type S'], + matching=False) + self.expect( + "frame variable", + substrs=[ + '(S)', + 'object', + '123', + '456'], + matching=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/main.cpp new file mode 100644 index 00000000000..86ee8d5a8e8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/main.cpp @@ -0,0 +1,19 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +struct S { + int x; + int y; + + S() : x(123), y(456) {} +}; + +int main() { + S object; + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/Makefile new file mode 100644 index 00000000000..8b322ff320b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/Makefile @@ -0,0 +1,8 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py new file mode 100644 index 00000000000..466eb5d5b7f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py @@ -0,0 +1,106 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NSArraySyntheticTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.m', '// Set break point at this line.') + + @skipUnlessDarwin + def test_rdar11086338_with_run_command(self): + """Test that NSArray reports its synthetic children properly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Now check that we are displaying Cocoa classes correctly + self.expect('frame variable arr', + substrs=['@"6 elements"']) + self.expect('frame variable other_arr', + substrs=['@"4 elements"']) + self.expect( + 'frame variable arr --ptr-depth 1', + substrs=[ + '@"6 elements"', + '[0] = 0x', + '[1] = 0x', + '[2] = 0x', + '[3] = 0x', + '[4] = 0x', + '[5] = 0x']) + self.expect( + 'frame variable other_arr --ptr-depth 1', + substrs=[ + '@"4 elements"', + '[0] = 0x', + '[1] = 0x', + '[2] = 0x', + '[3] = 0x']) + self.expect( + 'frame variable arr --ptr-depth 1 -d no-run-target', + substrs=[ + '@"6 elements"', + '@"hello"', + '@"world"', + '@"this"', + '@"is"', + '@"me"', + '@"http://www.apple.com']) + self.expect( + 'frame variable other_arr --ptr-depth 1 -d no-run-target', + substrs=[ + '@"4 elements"', + '(int)5', + '@"a string"', + '@"6 elements"']) + self.expect( + 'frame variable other_arr --ptr-depth 2 -d no-run-target', + substrs=[ + '@"4 elements"', + '@"6 elements" {', + '@"hello"', + '@"world"', + '@"this"', + '@"is"', + '@"me"', + '@"http://www.apple.com']) + + self.assertTrue( + self.frame().FindVariable("arr").MightHaveChildren(), + "arr says it does not have children!") + self.assertTrue( + self.frame().FindVariable("other_arr").MightHaveChildren(), + "arr says it does not have children!") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/main.m new file mode 100644 index 00000000000..e65ee6f0c85 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/main.m @@ -0,0 +1,34 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +int main (int argc, const char * argv[]) +{ + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + + NSMutableArray* arr = [[NSMutableArray alloc] init]; + [arr addObject:@"hello"]; + [arr addObject:@"world"]; + [arr addObject:@"this"]; + [arr addObject:@"is"]; + [arr addObject:@"me"]; + [arr addObject:[NSURL URLWithString:@"http://www.apple.com/"]]; + + NSDate *aDate = [NSDate distantFuture]; + NSValue *aValue = [NSNumber numberWithInt:5]; + NSString *aString = @"a string"; + + NSArray *other_arr = [NSArray arrayWithObjects:aDate, aValue, aString, arr, nil]; + + [pool drain];// Set break point at this line. + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/Makefile new file mode 100644 index 00000000000..8b322ff320b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/Makefile @@ -0,0 +1,8 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py new file mode 100644 index 00000000000..b77d01a8086 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py @@ -0,0 +1,120 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NSDictionarySyntheticTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.m', '// Set break point at this line.') + + @skipUnlessDarwin + def test_rdar11988289_with_run_command(self): + """Test that NSDictionary reports its synthetic children properly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Now check that we are displaying Cocoa classes correctly + self.expect('frame variable dictionary', + substrs=['3 key/value pairs']) + self.expect('frame variable mutabledict', + substrs=['4 key/value pairs']) + self.expect( + 'frame variable dictionary --ptr-depth 1', + substrs=[ + '3 key/value pairs', + '[0] = ', + 'key = 0x', + 'value = 0x', + '[1] = ', + '[2] = ']) + self.expect( + 'frame variable mutabledict --ptr-depth 1', + substrs=[ + '4 key/value pairs', + '[0] = ', + 'key = 0x', + 'value = 0x', + '[1] = ', + '[2] = ', + '[3] = ']) + self.expect( + 'frame variable dictionary --ptr-depth 1 --dynamic-type no-run-target', + substrs=[ + '3 key/value pairs', + '@"bar"', + '@"2 elements"', + '@"baz"', + '2 key/value pairs']) + self.expect( + 'frame variable mutabledict --ptr-depth 1 --dynamic-type no-run-target', + substrs=[ + '4 key/value pairs', + '(int)23', + '@"123"', + '@"http://www.apple.com"', + '@"sourceofstuff"', + '3 key/value pairs']) + self.expect( + 'frame variable mutabledict --ptr-depth 2 --dynamic-type no-run-target', + substrs=[ + '4 key/value pairs', + '(int)23', + '@"123"', + '@"http://www.apple.com"', + '@"sourceofstuff"', + '3 key/value pairs', + '@"bar"', + '@"2 elements"']) + self.expect( + 'frame variable mutabledict --ptr-depth 3 --dynamic-type no-run-target', + substrs=[ + '4 key/value pairs', + '(int)23', + '@"123"', + '@"http://www.apple.com"', + '@"sourceofstuff"', + '3 key/value pairs', + '@"bar"', + '@"2 elements"', + '(int)1', + '@"two"']) + + self.assertTrue( + self.frame().FindVariable("dictionary").MightHaveChildren(), + "dictionary says it does not have children!") + self.assertTrue( + self.frame().FindVariable("mutabledict").MightHaveChildren(), + "mutable says it does not have children!") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/main.m new file mode 100644 index 00000000000..65faaeaba09 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/main.m @@ -0,0 +1,29 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +int main (int argc, const char * argv[]) +{ + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + + NSArray* keys = @[@"foo",@"bar",@"baz"]; + NSArray* values = @[@"hello",@[@"X",@"Y"],@{@1 : @"one",@2 : @"two"}]; + NSDictionary* dictionary = [NSDictionary dictionaryWithObjects:values forKeys:keys]; + NSMutableDictionary* mutabledict = [NSMutableDictionary dictionaryWithCapacity:5]; + [mutabledict setObject:@"123" forKey:@23]; + [mutabledict setObject:[NSURL URLWithString:@"http://www.apple.com"] forKey:@"foobar"]; + [mutabledict setObject:@[@"a",@12] forKey:@57]; + [mutabledict setObject:dictionary forKey:@"sourceofstuff"]; + + [pool drain];// Set break point at this line. + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/Makefile new file mode 100644 index 00000000000..8b322ff320b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/Makefile @@ -0,0 +1,8 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py new file mode 100644 index 00000000000..2e8ca4591c9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py @@ -0,0 +1,111 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NSSetSyntheticTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.m', '// Set break point at this line.') + + @skipUnlessDarwin + def test_rdar12529957_with_run_command(self): + """Test that NSSet reports its synthetic children properly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Now check that we are displaying Cocoa classes correctly + self.expect('frame variable set', + substrs=['4 elements']) + self.expect('frame variable mutable', + substrs=['9 elements']) + self.expect( + 'frame variable set --ptr-depth 1 -d run -T', + substrs=[ + '4 elements', + '[0]', + '[1]', + '[2]', + '[3]', + 'hello', + 'world', + '(int)1', + '(int)2']) + self.expect( + 'frame variable mutable --ptr-depth 1 -d run -T', + substrs=[ + '9 elements', + '(int)5', + '@"3 elements"', + '@"www.apple.com"', + '(int)3', + '@"world"', + '(int)4']) + + self.runCmd("next") + self.expect('frame variable mutable', + substrs=['0 elements']) + + self.runCmd("next") + self.expect('frame variable mutable', + substrs=['4 elements']) + self.expect( + 'frame variable mutable --ptr-depth 1 -d run -T', + substrs=[ + '4 elements', + '[0]', + '[1]', + '[2]', + '[3]', + 'hello', + 'world', + '(int)1', + '(int)2']) + + self.runCmd("next") + self.expect('frame variable mutable', + substrs=['4 elements']) + self.expect( + 'frame variable mutable --ptr-depth 1 -d run -T', + substrs=[ + '4 elements', + '[0]', + '[1]', + '[2]', + '[3]', + 'hello', + 'world', + '(int)1', + '(int)2']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/main.m new file mode 100644 index 00000000000..207e23f51f9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/main.m @@ -0,0 +1,33 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +int main (int argc, const char * argv[]) +{ + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + NSSet* set = [NSSet setWithArray:@[@1,@"hello",@2,@"world"]]; + NSMutableSet* mutable = [NSMutableSet setWithCapacity:5]; + [mutable addObject:@1]; + [mutable addObject:@2]; + [mutable addObject:@3]; + [mutable addObject:@4]; + [mutable addObject:@5]; + [mutable addObject:[NSURL URLWithString:@"www.apple.com"]]; + [mutable addObject:@[@1,@2,@3]]; + [mutable unionSet:set]; + [mutable removeAllObjects]; // Set break point at this line. + [mutable unionSet:set]; + [mutable addObject:@1]; + + [pool drain]; + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/Makefile new file mode 100644 index 00000000000..876340159d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/Makefile @@ -0,0 +1,8 @@ +OBJCXX_SOURCES := main.mm + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py new file mode 100644 index 00000000000..c4180089ffa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py @@ -0,0 +1,51 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DataFormatterOSTypeTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.mm', '// Set break point at this line.') + + @skipUnlessDarwin + def test_ostype_with_run_command(self): + """Test the formatters we use for OSType.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Now check that we use the right summary for OSType + self.expect('frame variable', + substrs=["'test'", "'best'"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/main.mm new file mode 100644 index 00000000000..18d37b70dfd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/main.mm @@ -0,0 +1,22 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +int main (int argc, const char * argv[]) +{ + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + OSType a = 'test'; + OSType b = 'best'; + + [pool drain];// Set break point at this line. + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/TestPrintArray.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/TestPrintArray.py new file mode 100644 index 00000000000..c3062646886 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/TestPrintArray.py @@ -0,0 +1,132 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PrintArrayTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_print_array(self): + """Test that expr -Z works""" + self.build() + self.printarray_data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', 'break here') + + def printarray_data_formatter_commands(self): + """Test that expr -Z works""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.expect( + 'expr --element-count 3 -- data', + substrs=[ + '[0] = 1', + '[1] = 3', + '[2] = 5']) + self.expect('expr data', substrs=['int *', '$', '0x']) + self.expect( + 'expr -f binary --element-count 0 -- data', + substrs=[ + 'int *', + '$', + '0b']) + self.expect( + 'expr -f hex --element-count 3 -- data', + substrs=[ + '[0] = 0x', + '1', + '[1] = 0x', + '3', + '[2] = 0x', + '5']) + self.expect( + 'expr -f binary --element-count 2 -- data', + substrs=[ + 'int *', + '$', + '0x', + '[0] = 0b', + '1', + '[1] = 0b', + '11']) + self.expect('parray 3 data', substrs=['[0] = 1', '[1] = 3', '[2] = 5']) + self.expect( + 'parray `1 + 1 + 1` data', + substrs=[ + '[0] = 1', + '[1] = 3', + '[2] = 5']) + self.expect( + 'parray `data[1]` data', + substrs=[ + '[0] = 1', + '[1] = 3', + '[2] = 5']) + self.expect( + 'parray/x 3 data', + substrs=[ + '[0] = 0x', + '1', + '[1] = 0x', + '3', + '[2] = 0x', + '5']) + self.expect( + 'parray/x `data[1]` data', + substrs=[ + '[0] = 0x', + '1', + '[1] = 0x', + '3', + '[2] = 0x', + '5']) + + # check error conditions + self.expect( + 'expr --element-count 10 -- 123', + error=True, + substrs=['expression cannot be used with --element-count as it does not refer to a pointer']) + self.expect( + 'expr --element-count 10 -- (void*)123', + error=True, + substrs=['expression cannot be used with --element-count as it refers to a pointer to void']) + self.expect('parray data', error=True, substrs=[ + "invalid element count 'data'"]) + self.expect( + 'parray data data', + error=True, + substrs=["invalid element count 'data'"]) + self.expect('parray', error=True, substrs=[ + 'Not enough arguments provided']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/main.cpp new file mode 100644 index 00000000000..5d52383819a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/parray/main.cpp @@ -0,0 +1,28 @@ +//===-- main.cpp -------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <functional> +#include <stdlib.h> + +template<typename ElemType> +ElemType* alloc(size_t count, std::function<ElemType(size_t)> get) +{ + ElemType *elems = new ElemType[count]; + for(size_t i = 0; i < count; i++) + elems[i] = get(i); + return elems; +} + +int main (int argc, const char * argv[]) +{ + int* data = alloc<int>(5, [] (size_t idx) -> int { + return 2 * idx + 1; + }); + return 0; // break here +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/Makefile new file mode 100644 index 00000000000..876340159d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/Makefile @@ -0,0 +1,8 @@ +OBJCXX_SOURCES := main.mm + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/TestPrintObjectArray.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/TestPrintObjectArray.py new file mode 100644 index 00000000000..400607d84eb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/TestPrintObjectArray.py @@ -0,0 +1,108 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PrintObjectArrayTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_print_array(self): + """Test that expr -O -Z works""" + self.build() + self.printarray_data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.mm', 'break here') + + def printarray_data_formatter_commands(self): + """Test that expr -O -Z works""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.expect( + 'expr --element-count 3 --object-description -- objects', + substrs=[ + '3735928559', + '4276993775', + '3203398366', + 'Hello', + 'World', + 'Two =', + '1 =']) + self.expect( + 'poarray 3 objects', + substrs=[ + '3735928559', + '4276993775', + '3203398366', + 'Hello', + 'World', + 'Two =', + '1 =']) + self.expect( + 'expr --element-count 3 --object-description --description-verbosity=full -- objects', + substrs=[ + '[0] =', + '3735928559', + '4276993775', + '3203398366', + '[1] =', + 'Hello', + 'World', + '[2] =', + 'Two =', + '1 =']) + self.expect( + 'parray 3 objects', + substrs=[ + '[0] = 0x', + '[1] = 0x', + '[2] = 0x']) + self.expect( + 'expr --element-count 3 -d run -- objects', + substrs=[ + '3 elements', + '2 elements', + '2 key/value pairs']) + self.expect( + 'expr --element-count 3 -d run --ptr-depth=1 -- objects', + substrs=[ + '3 elements', + '2 elements', + '2 key/value pairs', + '3735928559', + '4276993775', + '3203398366', + '"Hello"', + '"World"']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/main.mm new file mode 100644 index 00000000000..be822dd7ab0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/poarray/main.mm @@ -0,0 +1,29 @@ +//===-- main.cpp -------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +struct ThreeObjects +{ + id one; + id two; + id three; +}; + +int main() +{ + NSArray *array1 = @[@0xDEADBEEF, @0xFEEDBEEF, @0xBEEFFADE]; + NSArray *array2 = @[@"Hello", @"World"]; + NSDictionary *dictionary = @{@1: array2, @"Two": array2}; + ThreeObjects *tobjects = new ThreeObjects(); + tobjects->one = array1; + tobjects->two = array2; + tobjects->three = dictionary; + id* objects = (id*)tobjects; + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/Makefile new file mode 100644 index 00000000000..83eb77ec8a9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +CFLAGS_EXTRAS := -std=c++11 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py new file mode 100644 index 00000000000..b0f7002966c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py @@ -0,0 +1,64 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class PtrRef2TypedefTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set breakpoint here') + + def test_with_run_command(self): + """Test that a pointer/reference to a typedef is formatted as we want.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd('type summary add --cascade true -s "IntPointer" "int *"') + self.runCmd('type summary add --cascade true -s "IntLRef" "int &"') + self.runCmd('type summary add --cascade true -s "IntRRef" "int &&"') + + self.expect( + "frame variable x", + substrs=[ + '(Foo *) x = 0x', + 'IntPointer']) + # note: Ubuntu 12.04 x86_64 build with gcc 4.8.2 is getting a + # const after the ref that isn't showing up on FreeBSD. This + # tweak changes the behavior so that the const is not part of + # the match. + self.expect( + "frame variable y", substrs=[ + '(Foo &', ') y = 0x', 'IntLRef']) + self.expect( + "frame variable z", substrs=[ + '(Foo &&', ') z = 0x', 'IntRRef']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/main.cpp new file mode 100644 index 00000000000..4520165758d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/main.cpp @@ -0,0 +1,18 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +typedef int Foo; + +int main() { + int lval = 1; + Foo* x = &lval; + Foo& y = lval; + Foo&& z = 1; + return 0; // Set breakpoint here +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py new file mode 100644 index 00000000000..22ce7442a62 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py @@ -0,0 +1,68 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PyObjectSynthProviderTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_print_array(self): + """Test that expr -Z works""" + self.build() + self.provider_data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', 'break here') + + def provider_data_formatter_commands(self): + """Test that the PythonObjectSyntheticChildProvider helper class works""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd('command script import provider.py') + self.runCmd( + 'type synthetic add Foo --python-class provider.SyntheticChildrenProvider') + self.expect('frame variable f.Name', substrs=['"Enrico"']) + self.expect( + 'frame variable f', + substrs=[ + 'ID = 123456', + 'Name = "Enrico"', + 'Rate = 1.25']) + self.expect( + 'expression f', + substrs=[ + 'ID = 123456', + 'Name = "Enrico"', + 'Rate = 1.25']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/main.cpp new file mode 100644 index 00000000000..4e7c633b591 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/main.cpp @@ -0,0 +1,19 @@ +//===-- main.cpp -------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +struct Foo +{ + double x; + int y; + Foo() : x(3.1415), y(1234) {} +}; + +int main() { + Foo f; + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/provider.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/provider.py new file mode 100644 index 00000000000..c263190c102 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/provider.py @@ -0,0 +1,16 @@ +import lldb +import lldb.formatters +import lldb.formatters.synth + + +class SyntheticChildrenProvider( + lldb.formatters.synth.PythonObjectSyntheticChildProvider): + + def __init__(self, value, internal_dict): + lldb.formatters.synth.PythonObjectSyntheticChildProvider.__init__( + self, value, internal_dict) + + def make_children(self): + return [("ID", 123456), + ("Name", "Enrico"), + ("Rate", 1.25)] diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py new file mode 100644 index 00000000000..1dc37c64f36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py @@ -0,0 +1,40 @@ +""" +Test that ValueObjectPrinter does not cause an infinite loop when a reference to a struct that contains a pointer to itself is printed. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class DataFormatterRefPtrRecursionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that ValueObjectPrinter does not cause an infinite loop when a reference to a struct that contains a pointer to itself is printed.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("frame variable foo", substrs=[]) + self.expect("frame variable foo --ptr-depth=1", substrs=['ID = 1']) + self.expect("frame variable foo --ptr-depth=2", substrs=['ID = 1']) + self.expect("frame variable foo --ptr-depth=3", substrs=['ID = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/main.cpp new file mode 100644 index 00000000000..4b576bd266d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/main.cpp @@ -0,0 +1,21 @@ +int _ID = 0; + +class Foo { + public: + Foo *next; + int ID; + + Foo () : next(0), ID(++_ID) {} +}; + +int evalFoo(Foo& foo) +{ + return foo.ID; // Set break point at this line. +} + +int main() { + Foo f; + f.next = &f; + return evalFoo(f); +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py new file mode 100644 index 00000000000..e08667fd24c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py @@ -0,0 +1,7 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, + decorators.skipIfNetBSD, decorators.skipIfWindows]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/main.m new file mode 100644 index 00000000000..e66c6b15e7f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/main.m @@ -0,0 +1,18 @@ +//===-- main.m ---------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#import <Foundation/Foundation.h> + +int main() { + NSDictionary* dic = @{@1 : @2}; + NSLog(@"hello world"); //% dic = self.frame().FindVariable("dic") + //% dic.SetPreferSyntheticValue(True) + //% dic.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + //% dic.SetValueFromCString("12") + return 0; //% dic = self.frame().FindVariable("dic") + //% self.assertTrue(dic.GetValueAsUnsigned() == 0xC, "failed to read what I wrote") +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py new file mode 100644 index 00000000000..c76b421a1ea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py @@ -0,0 +1,7 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.expectedFailureAll( + oslist=["windows"], bugnumber="llvm.org/pr24772")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/main.cpp new file mode 100644 index 00000000000..2631171ebf8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/main.cpp @@ -0,0 +1,39 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <string> + +int main (int argc, char const *argv[]) +{ + std::string stdstring("Hello\t\tWorld\nI am here\t\tto say hello\n"); //%self.addTearDownHook(lambda x: x.runCmd("setting set escape-non-printables true")) + const char* constcharstar = stdstring.c_str(); + std::string longstring( +"I am a very long string; in fact I am longer than any reasonable length that a string should be; quite long indeed; oh my, so many words; so many letters; this is kind of like writing a poem; except in real life all that is happening" +" is just me producing a very very long set of words; there is text here, text there, text everywhere; it fills me with glee to see so much text; all around me it's just letters, and symbols, and other pleasant drawings that cause me" +" a large amount of joy upon visually seeing them with my eyes; well, this is now a lot of letters, but it is still not enough for the purpose of the test I want to test, so maybe I should copy and paste this a few times, you know.." +" for science, or something" + "I am a very long string; in fact I am longer than any reasonable length that a string should be; quite long indeed; oh my, so many words; so many letters; this is kind of like writing a poem; except in real life all that is happening" + " is just me producing a very very long set of words; there is text here, text there, text everywhere; it fills me with glee to see so much text; all around me it's just letters, and symbols, and other pleasant drawings that cause me" + " a large amount of joy upon visually seeing them with my eyes; well, this is now a lot of letters, but it is still not enough for the purpose of the test I want to test, so maybe I should copy and paste this a few times, you know.." + " for science, or something" + "I am a very long string; in fact I am longer than any reasonable length that a string should be; quite long indeed; oh my, so many words; so many letters; this is kind of like writing a poem; except in real life all that is happening" + " is just me producing a very very long set of words; there is text here, text there, text everywhere; it fills me with glee to see so much text; all around me it's just letters, and symbols, and other pleasant drawings that cause me" + " a large amount of joy upon visually seeing them with my eyes; well, this is now a lot of letters, but it is still not enough for the purpose of the test I want to test, so maybe I should copy and paste this a few times, you know.." + " for science, or something" + ); + const char* longconstcharstar = longstring.c_str(); + return 0; //% if self.TraceOn(): self.runCmd('frame variable') + //% self.assertTrue(self.frame().FindVariable('stdstring').GetSummary() == '"Hello\\t\\tWorld\\nI am here\\t\\tto say hello\\n"') + //% self.assertTrue(self.frame().FindVariable('constcharstar').GetSummary() == '"Hello\\t\\tWorld\\nI am here\\t\\tto say hello\\n"') + //% self.runCmd("setting set escape-non-printables false") + //% self.assertTrue(self.frame().FindVariable('stdstring').GetSummary() == '"Hello\t\tWorld\nI am here\t\tto say hello\n"') + //% self.assertTrue(self.frame().FindVariable('constcharstar').GetSummary() == '"Hello\t\tWorld\nI am here\t\tto say hello\n"') + //% self.assertTrue(self.frame().FindVariable('longstring').GetSummary().endswith('"...')) + //% self.assertTrue(self.frame().FindVariable('longconstcharstar').GetSummary().endswith('"...')) +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py new file mode 100644 index 00000000000..88ec1ff8c82 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py @@ -0,0 +1,144 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class Radar9974002DataFormatterTestCase(TestBase): + + # test for rdar://problem/9974002 () + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): + self.skipTest( + "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") + + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '<parent is NULL>']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '0x000000']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer%S}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '0x000000']) + + self.runCmd("type summary add -s foo contained") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', 'foo']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', 'foo']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer%V}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '0x000000']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '<parent is NULL>']) + + self.runCmd("type summary delete contained") + self.runCmd("n") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '<parent is NULL>']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '0x000000']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer%S}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '0x000000']) + + self.runCmd("type summary add -s foo contained") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', 'foo']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', 'foo']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer%V}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '0x000000']) + + self.runCmd( + "type summary add -s \"${var.scalar} and ${var.pointer.first}\" container") + + self.expect('frame variable mine', + substrs=['mine = ', + '1', '<parent is NULL>']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/main.cpp new file mode 100644 index 00000000000..9d483ebb470 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/main.cpp @@ -0,0 +1,29 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +struct contained +{ + int first; + int second; +}; + +struct container +{ + int scalar; + struct contained *pointer; +}; + +int main () +{ + struct container mine = {1, 0}; + printf ("Mine's scalar is the only thing that is good: %d.\n", mine.scalar); // Set break point at this line. + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py new file mode 100644 index 00000000000..53df271fdcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py @@ -0,0 +1,85 @@ +""" +Check for an issue where capping does not work because the Target pointer appears to be changing behind our backs +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SyntheticCappingTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Check for an issue where capping does not work because the Target pointer appears to be changing behind our backs.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + process = self.dbg.GetSelectedTarget().GetProcess() + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + self.runCmd( + "settings set target.max-children-count 256", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # set up the synthetic children provider + self.runCmd("script from fooSynthProvider import *") + self.runCmd("type synth add -l fooSynthProvider foo") + + # note that the value of fake_a depends on target byte order + if process.GetByteOrder() == lldb.eByteOrderLittle: + fake_a_val = 0x02000000 + else: + fake_a_val = 0x00000100 + + # check that the synthetic children work, so we know we are doing the + # right thing + self.expect("frame variable f00_1", + substrs=['r = 34', + 'fake_a = %d' % fake_a_val, + 'a = 1']) + + # check that capping works + self.runCmd("settings set target.max-children-count 2", check=False) + + self.expect("frame variable f00_1", + substrs=['...', + 'fake_a = %d' % fake_a_val, + 'a = 1']) + + self.expect("frame variable f00_1", matching=False, + substrs=['r = 34']) + + self.runCmd("settings set target.max-children-count 256", check=False) + + self.expect("frame variable f00_1", matching=True, + substrs=['r = 34']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py new file mode 100644 index 00000000000..124eb5d31ba --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py @@ -0,0 +1,27 @@ +import lldb + + +class fooSynthProvider: + + def __init__(self, valobj, dict): + self.valobj = valobj + self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt) + + def num_children(self): + return 3 + + def get_child_at_index(self, index): + if index == 0: + child = self.valobj.GetChildMemberWithName('a') + if index == 1: + child = self.valobj.CreateChildAtOffset('fake_a', 1, self.int_type) + if index == 2: + child = self.valobj.GetChildMemberWithName('r') + return child + + def get_child_index(self, name): + if name == 'a': + return 0 + if name == 'fake_a': + return 1 + return 2 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/main.cpp new file mode 100644 index 00000000000..90571b59f81 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/main.cpp @@ -0,0 +1,62 @@ +struct foo +{ + int a; + int b; + int c; + int d; + int e; + int f; + int g; + int h; + int i; + int j; + int k; + int l; + int m; + int n; + int o; + int p; + int q; + int r; + + foo(int X) : + a(X), + b(X+1), + c(X+3), + d(X+5), + e(X+7), + f(X+9), + g(X+11), + h(X+13), + i(X+15), + j(X+17), + k(X+19), + l(X+21), + m(X+23), + n(X+25), + o(X+27), + p(X+29), + q(X+31), + r(X+33) {} +}; + +struct wrapint +{ + int x; + wrapint(int X) : x(X) {} +}; + +int main() +{ + foo f00_1(1); + foo *f00_ptr = new foo(12); + + f00_1.a++; // Set break point at this line. + + wrapint test_cast('A' + + 256*'B' + + 256*256*'C'+ + 256*256*256*'D'); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/Makefile new file mode 100644 index 00000000000..3767ff17e35 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/Makefile @@ -0,0 +1,8 @@ +OBJC_SOURCES := main.m +CFLAGS_EXTRAS := -w +LD_EXTRAS := -framework Foundation + +include Makefile.rules + +clean:: + rm -rf $(wildcard *.o *.d *.dSYM *.log) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py new file mode 100644 index 00000000000..e9e570eda58 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py @@ -0,0 +1,83 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SyntheticFilterRecomputingTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.m', '// Set break point at this line.') + + @skipUnlessDarwin + def test_rdar12437442_with_run_command(self): + """Test that we update SBValues correctly as dynamic types change.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Now run the bulk of the test + id_x = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable("x") + id_x.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + id_x.SetPreferSyntheticValue(True) + + if self.TraceOn(): + self.runCmd("expr --dynamic-type run-target --ptr-depth 1 -- x") + + self.assertTrue( + id_x.GetSummary() == '@"5 elements"', + "array does not get correct summary") + + self.runCmd("next") + self.runCmd("frame select 0") + + id_x = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable("x") + id_x.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + id_x.SetPreferSyntheticValue(True) + + if self.TraceOn(): + self.runCmd("expr --dynamic-type run-target --ptr-depth 1 -- x") + + self.assertTrue( + id_x.GetNumChildren() == 7, + "dictionary does not have 7 children") + id_x.SetPreferSyntheticValue(False) + self.assertFalse( + id_x.GetNumChildren() == 7, + "dictionary still looks synthetic") + id_x.SetPreferSyntheticValue(True) + self.assertTrue( + id_x.GetSummary() == "7 key/value pairs", + "dictionary does not get correct summary") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/main.m new file mode 100644 index 00000000000..eb27ff9d1e3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/main.m @@ -0,0 +1,24 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +int main (int argc, const char * argv[]) +{ + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + NSArray* foo = [NSArray arrayWithObjects:@1,@2,@3,@4,@5, nil]; + NSDictionary *bar = @{@1 : @"one",@2 : @"two", @3 : @"three", @4 : @"four", @5 : @"five", @6 : @"six", @7 : @"seven"}; + id x = foo; + x = bar; // Set break point at this line. + + [pool drain]; + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py new file mode 100644 index 00000000000..e1dc52e8394 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_arg/TestTypeSummaryListArg.py @@ -0,0 +1,44 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TypeSummaryListArgumentTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_type_summary_list_with_arg(self): + """Test that the 'type summary list' command handles command line arguments properly""" + self.expect( + 'type summary list Foo', + substrs=[ + 'Category: default', + 'Category: system']) + self.expect( + 'type summary list char', + substrs=[ + 'char *', + 'unsigned char']) + + self.expect( + 'type summary list -w default', + substrs=['system'], + matching=False) + self.expect( + 'type summary list -w system unsigned', + substrs=[ + 'default', + '0-9'], + matching=False) + self.expect( + 'type summary list -w system char', + substrs=['unsigned char *'], + matching=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py new file mode 100644 index 00000000000..7d70ad3da9c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/TestTypeSummaryListScript.py @@ -0,0 +1,62 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TypeSummaryListScriptTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_typesummarylist_script(self): + """Test data formatter commands.""" + self.build() + self.data_formatter_commands() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', 'Break here') + + def data_formatter_commands(self): + """Test printing out Python summary formatters.""" + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type category delete TSLSFormatters', check=False) + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + + self.addTearDownHook(cleanup) + + self.runCmd("command script import tslsformatters.py") + + self.expect( + "frame variable myStruct", + substrs=['A data formatter at work']) + + self.expect('type summary list', substrs=['Struct_SummaryFormatter']) + self.expect( + 'type summary list Struct', + substrs=['Struct_SummaryFormatter']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/main.cpp new file mode 100644 index 00000000000..2de37041f26 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/main.cpp @@ -0,0 +1,15 @@ +#include <stdio.h> + +typedef struct Struct +{ + int one; + int two; +} Struct; + +int +main() +{ + Struct myStruct = {10, 20}; + printf ("Break here: %d\n.", myStruct.one); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/tslsformatters.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/tslsformatters.py new file mode 100644 index 00000000000..03fe17bfe76 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/type_summary_list_script/tslsformatters.py @@ -0,0 +1,12 @@ +import lldb + + +def Struct_SummaryFormatter(valobj, internal_dict): + return 'A data formatter at work' + +category = lldb.debugger.CreateCategory("TSLSFormatters") +category.SetEnabled(True) +summary = lldb.SBTypeSummary.CreateWithFunctionName( + "tslsformatters.Struct_SummaryFormatter", lldb.eTypeOptionCascade) +spec = lldb.SBTypeNameSpecifier("Struct", False) +category.AddTypeSummary(spec, summary) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py new file mode 100644 index 00000000000..7e67f73b709 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py @@ -0,0 +1,7 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.expectedFailureAll( + compiler="gcc")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/main.cpp new file mode 100644 index 00000000000..cb6dc18655f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/main.cpp @@ -0,0 +1,18 @@ +//===-- main.cpp --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +typedef int Foo; + +int main() { + // CHECK: (Foo [3]) array = { + // CHECK-NEXT: (Foo) [0] = 1 + // CHECK-NEXT: (Foo) [1] = 2 + // CHECK-NEXT: (Foo) [2] = 3 + // CHECK-NEXT: } + Foo array[3] = {1,2,3}; + return 0; //% self.filecheck("frame variable array --show-types --", 'main.cpp') +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py new file mode 100644 index 00000000000..ad4db01411f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py @@ -0,0 +1,71 @@ +""" +Test that the user can input a format but it will not prevail over summary format's choices. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class UserFormatVSSummaryTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that the user can input a format but it will not prevail over summary format's choices.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("frame variable p1", substrs=[ + '(Pair) p1 = (x = 3, y = -3)']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd('type summary add Pair -s "x=${var.x%d},y=${var.y%u}"') + + self.expect("frame variable p1", substrs=[ + '(Pair) p1 = x=3,y=4294967293']) + self.expect( + "frame variable -f x p1", + substrs=['(Pair) p1 = x=0x00000003,y=0xfffffffd'], + matching=False) + self.expect( + "frame variable -f d p1", + substrs=['(Pair) p1 = x=3,y=-3'], + matching=False) + self.expect("frame variable p1", substrs=[ + '(Pair) p1 = x=3,y=4294967293']) + + self.runCmd('type summary add Pair -s "x=${var.x%x},y=${var.y%u}"') + + self.expect("frame variable p1", substrs=[ + '(Pair) p1 = x=0x00000003,y=4294967293']) + self.expect( + "frame variable -f d p1", + substrs=['(Pair) p1 = x=3,y=-3'], + matching=False) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/main.cpp new file mode 100644 index 00000000000..b7ac006eb68 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/main.cpp @@ -0,0 +1,19 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +struct Pair { + int x; + int y; + + Pair(int _x, int _y) : x(_x), y(_y) {} +}; + +int main() { + Pair p1(3,-3); + return p1.x + p1.y; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py new file mode 100644 index 00000000000..c1ec60e9e10 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py @@ -0,0 +1,77 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class VarInAggregateMisuseTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd( + "type summary add --summary-string \"SUMMARY SUCCESS ${var}\" Summarize") + + self.expect('frame variable mine_ptr', + substrs=['SUMMARY SUCCESS summarize_ptr_t @ ']) + + self.expect('frame variable *mine_ptr', + substrs=['SUMMARY SUCCESS summarize_t @']) + + self.runCmd( + "type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize") + + self.expect('frame variable mine_ptr', + substrs=['SUMMARY SUCCESS 10']) + + self.expect('frame variable *mine_ptr', + substrs=['SUMMARY SUCCESS 10']) + + self.runCmd("type summary add --summary-string \"${var}\" Summarize") + self.runCmd( + "type summary add --summary-string \"${var}\" -e TwoSummarizes") + + self.expect('frame variable', + substrs=['(TwoSummarizes) twos = TwoSummarizes @ ', + 'first = summarize_t @ ', + 'second = summarize_t @ ']) + + self.runCmd( + "type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize") + self.expect('frame variable', + substrs=['(TwoSummarizes) twos = TwoSummarizes @ ', + 'first = SUMMARY SUCCESS 1', + 'second = SUMMARY SUCCESS 3']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/main.cpp new file mode 100644 index 00000000000..e35f7f359e3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/main.cpp @@ -0,0 +1,40 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +struct Summarize +{ + int first; + int second; +}; + +typedef struct Summarize summarize_t; +typedef summarize_t *summarize_ptr_t; + +summarize_t global_mine = {30, 40}; + +struct TwoSummarizes +{ + summarize_t first; + summarize_t second; +}; + +int +main() +{ + summarize_t mine = {10, 20}; + summarize_ptr_t mine_ptr = &mine; + + TwoSummarizes twos = { {1,2}, {3,4} }; + + printf ("Summarize: first: %d second: %d and address: 0x%p\n", mine.first, mine.second, mine_ptr); // Set break point at this line. + printf ("Global summarize: first: %d second: %d.\n", global_mine.first, global_mine.second); + return 0; +} + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py new file mode 100644 index 00000000000..c7391f432f4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py @@ -0,0 +1,56 @@ +""" +Test lldb data formatter subsystem. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DataFormatterVarScriptFormatting(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', ' // Set breakpoint here.') + + @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser + def test_with_run_command(self): + """Test using Python synthetic children provider.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synth clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + self.runCmd("command script import helperfunc.py") + self.runCmd( + 'type summary add -x "^something<.*>$" -s "T is a ${script.var:helperfunc.f}"') + + self.expect("frame variable x", substrs=['T is a non-pointer type']) + + self.expect("frame variable y", substrs=['T is a pointer type']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py new file mode 100644 index 00000000000..75654e4b4ed --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py @@ -0,0 +1,6 @@ +import lldb + + +def f(value, d): + return "pointer type" if value.GetType().GetTemplateArgumentType( + 0).IsPointerType() else "non-pointer type" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/main.cpp new file mode 100644 index 00000000000..e9a36f91196 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/main.cpp @@ -0,0 +1,8 @@ +template <typename T> +struct something {}; + +int main() { + something<int> x; + something<void*> y; + return 0; // Set breakpoint here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py new file mode 100644 index 00000000000..e4632afe7b9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py @@ -0,0 +1,88 @@ +""" +Check that vector types format properly +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class VectorTypesFormattingTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// break here') + + # rdar://problem/14035604 + @skipIf(compiler='gcc') # gcc don't have ext_vector_type extension + def test_with_run_command(self): + """Check that vector types format properly""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + pass + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + pass # my code never fails + + v = self.frame().FindVariable("v") + v.SetPreferSyntheticValue(True) + v.SetFormat(lldb.eFormatVectorOfFloat32) + + if self.TraceOn(): + print(v) + + self.assertTrue( + v.GetNumChildren() == 4, + "v as float32[] has 4 children") + self.assertTrue(v.GetChildAtIndex(0).GetData().float[ + 0] == 1.25, "child 0 == 1.25") + self.assertTrue(v.GetChildAtIndex(1).GetData().float[ + 0] == 1.25, "child 1 == 1.25") + self.assertTrue(v.GetChildAtIndex(2).GetData().float[ + 0] == 2.50, "child 2 == 2.50") + self.assertTrue(v.GetChildAtIndex(3).GetData().float[ + 0] == 2.50, "child 3 == 2.50") + + self.expect("expr -f int16_t[] -- v", + substrs=['(0, 16288, 0, 16288, 0, 16416, 0, 16416)']) + self.expect("expr -f uint128_t[] -- v", + substrs=['(85236745249553456609335044694184296448)']) + self.expect( + "expr -f float32[] -- v", + substrs=['(1.25, 1.25, 2.5, 2.5)']) + + oldValue = v.GetChildAtIndex(0).GetValue() + v.SetFormat(lldb.eFormatHex) + newValue = v.GetChildAtIndex(0).GetValue() + self.assertFalse(oldValue == newValue, + "values did not change along with format") + + v.SetFormat(lldb.eFormatVectorOfFloat32) + oldValueAgain = v.GetChildAtIndex(0).GetValue() + self.assertTrue( + oldValue == oldValueAgain, + "same format but different values") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/main.cpp new file mode 100644 index 00000000000..5470147f08a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/main.cpp @@ -0,0 +1,16 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +typedef float float4 __attribute__((ext_vector_type(4))); +typedef unsigned char vec __attribute__((ext_vector_type(16))); + +int main() { + float4 f4 = {1.25, 1.25, 2.50, 2.50}; + vec v = (vec)f4; + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/Makefile new file mode 100644 index 00000000000..3e7e139ddd6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/Makefile @@ -0,0 +1,20 @@ +C_SOURCES := main.c + +ifeq "$(OS)" "" + OS = $(shell uname -s) +endif + +ifeq "$(OS)" "Darwin" + LD_EXTRAS = -Xlinker -dead_strip +else + CFLAGS_EXTRAS += -fdata-sections -ffunction-sections + ifeq "$(OS)" "Windows_NT" + LD_EXTRAS = -Xlinker /OPT:REF + else + LD_EXTRAS = -Wl,--gc-sections + endif +endif + +MAKE_DSYM := NO + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py new file mode 100644 index 00000000000..bc1f3f8003f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py @@ -0,0 +1,58 @@ +""" +Test that breakpoint works correctly in the presence of dead-code stripping. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DeadStripTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr44429") + def test(self): + """Test breakpoint works correctly with dead-code stripping.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break by function name f1 (live code). + lldbutil.run_break_set_by_symbol( + self, "f1", num_expected_locations=1, module_name="a.out") + + # Break by function name f2 (dead code). + lldbutil.run_break_set_by_symbol( + self, "f2", num_expected_locations=0, module_name="a.out") + + # Break by function name f3 (live code). + lldbutil.run_break_set_by_symbol( + self, "f3", num_expected_locations=1, module_name="a.out") + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint (breakpoint #1). + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'a.out`f1', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f 1", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.runCmd("continue") + + # The stop reason of the thread should be breakpoint (breakpoint #3). + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'a.out`f3', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f 3", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/cmds.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/cmds.txt new file mode 100644 index 00000000000..f6fd0450288 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/cmds.txt @@ -0,0 +1,4 @@ +b main.c:21 +b main.c:41 +lines -shlib a.out main.c +c diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/main.c new file mode 100644 index 00000000000..cde8c18ba36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dead-strip/main.c @@ -0,0 +1,52 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + + +int f1 (char *s); +int f2 (char *s); +int f3 (char *s); + + +// We want f1 to start on line 20 +int f1 (char *s) +{ + return printf("f1: %s\n", s); +} + + + + + +// We want f2 to start on line 30, this should get stripped +int f2 (char *s) +{ + return printf("f2: %s\n", s); +} + + + + + +// We want f3 to start on line 40 +int f3 (char *s) +{ + return printf("f3: %s\n", s); +} + + + + + +// We want main to start on line 50 +int main (int argc, const char * argv[]) +{ + f1("carp"); + f3("dong"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/deleted-executable/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/deleted-executable/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/deleted-executable/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/deleted-executable/TestDeletedExecutable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/deleted-executable/TestDeletedExecutable.py new file mode 100644 index 00000000000..ed17d9b36b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/deleted-executable/TestDeletedExecutable.py @@ -0,0 +1,46 @@ +""" +Test process attach when executable was deleted. +""" + + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestDeletedExecutable(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipIfWindows # cannot delete a running executable + @expectedFailureAll(oslist=["linux"], + triple=no_match('aarch64-.*-android')) + # determining the architecture of the process fails + @expectedFailureNetBSD + def test(self): + self.build() + exe = self.getBuildArtifact("a.out") + + # Use a file as a synchronization point between test and inferior. + pid_file_path = lldbutil.append_to_process_working_directory(self, + "token_pid_%d" % (int(os.getpid()))) + self.addTearDownHook( + lambda: self.run_platform_command( + "rm %s" % + (pid_file_path))) + + # Spawn a new process + popen = self.spawnSubprocess(exe, [pid_file_path]) + self.addTearDownHook(self.cleanupSubprocesses) + + # Wait until process has fully started up. + pid = lldbutil.wait_for_file_on_target(self, pid_file_path) + + # Now we can safely remove the executable and test if we can attach. + os.remove(exe) + + self.runCmd("process attach -p " + str(popen.pid)) + self.runCmd("kill") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/deleted-executable/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/deleted-executable/main.cpp new file mode 100644 index 00000000000..af00ac263cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/deleted-executable/main.cpp @@ -0,0 +1,15 @@ +#include <chrono> +#include <fstream> +#include <thread> + +int main(int argc, char const *argv[]) { + lldb_enable_attach(); + + { + // Create file to signal that this process has started up. + std::ofstream f; + f.open(argv[1]); + } + + std::this_thread::sleep_for(std::chrono::seconds(60)); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/Makefile new file mode 100644 index 00000000000..2bba8e757f7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := pass-to-base.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py new file mode 100644 index 00000000000..e7f984081ea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py @@ -0,0 +1,80 @@ +""" +Test that dynamic values update their child count correctly +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DynamicValueChildCountTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # Find the line number to break for main.c. + + self.main_third_call_line = line_number( + 'pass-to-base.cpp', '// Break here and check b has 0 children') + self.main_fourth_call_line = line_number( + 'pass-to-base.cpp', '// Break here and check b still has 0 children') + self.main_fifth_call_line = line_number( + 'pass-to-base.cpp', '// Break here and check b has one child now') + self.main_sixth_call_line = line_number( + 'pass-to-base.cpp', '// Break here and check b has 0 children again') + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24663") + def test_get_dynamic_vals(self): + """Test fetching C++ dynamic values from pointers & references.""" + """Get argument vals for the call stack when stopped on a breakpoint.""" + self.build(dictionary=self.getBuildFlags()) + exe = self.getBuildArtifact("a.out") + + # Create a target from the debugger. + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set up our breakpoints: + + third_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_third_call_line) + self.assertTrue(third_call_bpt, + VALID_BREAKPOINT) + fourth_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_fourth_call_line) + self.assertTrue(fourth_call_bpt, + VALID_BREAKPOINT) + fifth_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_fifth_call_line) + self.assertTrue(fifth_call_bpt, + VALID_BREAKPOINT) + sixth_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_sixth_call_line) + self.assertTrue(sixth_call_bpt, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + b = self.frame().FindVariable("b").GetDynamicValue(lldb.eDynamicCanRunTarget) + self.assertTrue(b.GetNumChildren() == 0, "b has 0 children") + self.runCmd("continue") + self.assertTrue(b.GetNumChildren() == 0, "b still has 0 children") + self.runCmd("continue") + self.assertTrue(b.GetNumChildren() != 0, "b now has 1 child") + self.runCmd("continue") + self.assertTrue( + b.GetNumChildren() == 0, + "b didn't go back to 0 children") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/pass-to-base.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/pass-to-base.cpp new file mode 100644 index 00000000000..d9dd3529821 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/pass-to-base.cpp @@ -0,0 +1,36 @@ +#include <stdio.h> +#include <memory> + +class BaseClass +{ +public: + BaseClass(); + virtual ~BaseClass() { } +}; + +class DerivedClass : public BaseClass +{ +public: + DerivedClass(); + virtual ~DerivedClass() { } +protected: + int mem; +}; + +BaseClass::BaseClass() +{ +} + +DerivedClass::DerivedClass() : BaseClass() +{ + mem = 101; +} + +int +main (int argc, char **argv) +{ + BaseClass *b = nullptr; // Break here and check b has 0 children + b = new DerivedClass(); // Break here and check b still has 0 children + b = nullptr; // Break here and check b has one child now + return 0; // Break here and check b has 0 children again +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/Makefile new file mode 100644 index 00000000000..afc520010ee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/Makefile @@ -0,0 +1,9 @@ +CXX_SOURCES := main.cpp + +all: secondprog + +include Makefile.rules + +secondprog: secondprog.cpp + $(MAKE) -f $(MAKEFILE_RULES) \ + CXX_SOURCES=secondprog.cpp EXE=secondprog diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py new file mode 100644 index 00000000000..019df217713 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py @@ -0,0 +1,113 @@ +""" +Test some lldb command abbreviations. +""" +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExecTestCase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(archs=['i386'], bugnumber="rdar://28656532") + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://problem/34559552") # this exec test has problems on ios systems + @expectedFailureNetBSD + @skipIfAsan # rdar://problem/43756823 + @skipIfWindows + def test_hitting_exec (self): + self.do_test(False) + + @expectedFailureAll(archs=['i386'], bugnumber="rdar://28656532") + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://problem/34559552") # this exec test has problems on ios systems + @expectedFailureNetBSD + @skipIfAsan # rdar://problem/43756823 + @skipIfWindows + def test_skipping_exec (self): + self.do_test(True) + + def do_test(self, skip_exec): + self.build() + exe = self.getBuildArtifact("a.out") + secondprog = self.getBuildArtifact("secondprog") + + # Create the target + target = self.dbg.CreateTarget(exe) + + # Create any breakpoints we need + breakpoint1 = target.BreakpointCreateBySourceRegex( + 'Set breakpoint 1 here', lldb.SBFileSpec("main.cpp", False)) + self.assertTrue(breakpoint1, VALID_BREAKPOINT) + breakpoint2 = target.BreakpointCreateBySourceRegex( + 'Set breakpoint 2 here', lldb.SBFileSpec("secondprog.cpp", False)) + self.assertTrue(breakpoint2, VALID_BREAKPOINT) + + # Launch the process + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + if self.TraceOn(): + self.runCmd("settings show target.process.stop-on-exec", check=False) + if skip_exec: + self.dbg.HandleCommand("settings set target.process.stop-on-exec false") + def cleanup(): + self.runCmd("settings set target.process.stop-on-exec false", + check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # The stop reason of the thread should be breakpoint. + self.assertTrue(process.GetState() == lldb.eStateStopped, + STOPPED_DUE_TO_BREAKPOINT) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint1) + self.assertTrue(len(threads) == 1) + + # We had a deadlock tearing down the TypeSystemMap on exec, but only if some + # expression had been evaluated. So make sure we do that here so the teardown + # is not trivial. + + thread = threads[0] + value = thread.frames[0].EvaluateExpression("1 + 2") + self.assertTrue( + value.IsValid(), + "Expression evaluated successfully") + int_value = value.GetValueAsSigned() + self.assertTrue(int_value == 3, "Expression got the right result.") + + # Run and we should stop due to exec + process.Continue() + + if not skip_exec: + self.assertFalse(process.GetState() == lldb.eStateExited, + "Process should not have exited!") + self.assertTrue(process.GetState() == lldb.eStateStopped, + "Process should be stopped at __dyld_start") + + threads = lldbutil.get_stopped_threads( + process, lldb.eStopReasonExec) + self.assertTrue( + len(threads) == 1, + "We got a thread stopped for exec.") + + # Run and we should stop at breakpoint in main after exec + process.Continue() + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint2) + if self.TraceOn(): + for t in process.threads: + print(t) + if t.GetStopReason() != lldb.eStopReasonBreakpoint: + self.runCmd("bt") + self.assertTrue(len(threads) == 1, + "Stopped at breakpoint in exec'ed process.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/main.cpp new file mode 100644 index 00000000000..bec470fd13e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/main.cpp @@ -0,0 +1,18 @@ +#define _POSIX_C_SOURCE 200809L + +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <libgen.h> +#include <string> +#include <unistd.h> + +int main(int argc, char const **argv) { + char *buf = strdup(argv[0]); // Set breakpoint 1 here + std::string directory_name(::dirname(buf)); + + std::string other_program = directory_name + "/secondprog"; + execve(other_program.c_str(), const_cast<char *const *>(argv), nullptr); + perror("execve"); + abort(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/secondprog.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/secondprog.cpp new file mode 100644 index 00000000000..5653471c153 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/exec/secondprog.cpp @@ -0,0 +1,5 @@ +#include <stdio.h> +int main () +{ + puts ("I am the second program."); // Set breakpoint 2 here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/Makefile new file mode 100644 index 00000000000..7fed83dc9eb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/Makefile @@ -0,0 +1,15 @@ +SRCDIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))/ +all: a.c clean + $(CC) -arch i386 -g -c $(SRCDIR)/a.c + ar -q liba-i386.a a.o + ranlib liba-i386.a + $(CC) -arch x86_64 -g -c $(SRCDIR)/a.c + ar -q liba-x86_64.a a.o + ranlib liba-x86_64.a + lipo -create -output liba.a liba-i386.a liba-x86_64.a + $(CC) -g -c $(SRCDIR)/main.c + $(CC) -o a.out main.o -L. -la + +clean: + rm -rf a.o a.out liba-i386.a liba-x86_64.a liba.a $(wildcard *un~ .*un~ main.o *.pyc) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py new file mode 100644 index 00000000000..5fa52d31885 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py @@ -0,0 +1,57 @@ +""" +Test some lldb command abbreviations. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class FatArchiveTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @skipUnlessDarwin + def test_breakpoint_resolution_dwarf(self): + if self.getArchitecture() == 'x86_64': + self.build() + self.main() + else: + self.skipTest( + "This test requires x86_64 as the architecture for the inferior") + + def main(self): + '''This test compiles a quick example by making a fat file (universal) full of + skinny .o files and makes sure we can use them to resolve breakpoints when doing + DWARF in .o file debugging. The only thing this test needs to do is to compile and + set a breakpoint in the target and verify any breakpoint locations have valid debug + info for the function, and source file and line.''' + exe = self.getBuildArtifact("a.out") + + # Create the target + target = self.dbg.CreateTarget(exe) + + # Create a breakpoint by name + breakpoint = target.BreakpointCreateByName('foo', exe) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Make sure the breakpoint resolves to a function, file and line + for bp_loc in breakpoint: + # Get a section offset address (lldb.SBAddress) from the breakpoint + # location + bp_loc_addr = bp_loc.GetAddress() + line_entry = bp_loc_addr.GetLineEntry() + function = bp_loc_addr.GetFunction() + self.assertTrue( + function.IsValid(), + "Verify breakpoint in fat BSD archive has valid function debug info") + self.assertTrue( + line_entry.GetFileSpec(), + "Verify breakpoint in fat BSD archive has source file information") + self.assertTrue( + line_entry.GetLine() != 0, + "Verify breakpoint in fat BSD archive has source line information") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/a.c new file mode 100644 index 00000000000..c100f9a2c07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/a.c @@ -0,0 +1,4 @@ +int foo () +{ + return 5; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/a.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/a.h new file mode 100644 index 00000000000..a4536647cfc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/a.h @@ -0,0 +1 @@ +int foo (); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/main.c new file mode 100644 index 00000000000..328319d4fb8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/fat_archives/main.c @@ -0,0 +1,6 @@ +#include "a.h" +#include <stdio.h> +int main() +{ + printf ("%d\n", foo()); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/float-display/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/float-display/Makefile new file mode 100644 index 00000000000..c9319d6e688 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/float-display/Makefile @@ -0,0 +1,2 @@ +C_SOURCES := main.c +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/float-display/TestFloatDisplay.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/float-display/TestFloatDisplay.py new file mode 100644 index 00000000000..48e49ed009b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/float-display/TestFloatDisplay.py @@ -0,0 +1,5 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), []) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/float-display/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/float-display/main.c new file mode 100644 index 00000000000..7e89225a4cb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/float-display/main.c @@ -0,0 +1,121 @@ +float f_neg3 = 1.234567 / 1e3; +float f_neg4 = 1.234567 / 1e4; +float f_neg5 = 1.234567 / 1e5; +float f_neg6 = 1.234567 / 1e6; +float f_neg7 = 1.234567 / 1e7; +float f_neg8 = 1.234567 / 1e8; +float f_neg20 = 1.234567 / 1e20; +float f_neg30 = 1.234567 / 1e30; + +float f_3 = 1.234567 * 1e3; +float f_4 = 1.234567 * 1e4; +float f_5 = 1.234567 * 1e5; +float f_6 = 1.234567 * 1e6; +float f_7 = 1.234567 * 1e7; +float f_8 = 1.234567 * 1e8; +float f_20 = 1.234567 * 1e20; +float f_30 = 1.234567 * 1e30; + +double d_neg3 = 1.234567 / 1e3; +double d_neg4 = 1.234567 / 1e4; +double d_neg5 = 1.234567 / 1e5; +double d_neg6 = 1.234567 / 1e6; +double d_neg7 = 1.234567 / 1e7; +double d_neg8 = 1.234567 / 1e8; +double d_neg20 = 1.234567 / 1e20; +double d_neg30 = 1.234567 / 1e30; +double d_neg50 = 1.234567 / 1e50; +double d_neg250 = 1.234567 / 1e250; + +double d_3 = 1.234567 * 1e3; +double d_4 = 1.234567 * 1e4; +double d_5 = 1.234567 * 1e5; +double d_6 = 1.234567 * 1e6; +double d_7 = 1.234567 * 1e7; +double d_8 = 1.234567 * 1e8; +double d_20 = 1.234567 * 1e20; +double d_30 = 1.234567 * 1e30; +double d_50 = 1.234567 * 1e50; +double d_250 = 1.234567 * 1e250; + +int main (int argc, char const *argv[]) { + //% # Default setting should be 6. + //% self.expect("frame variable f_neg3", substrs=["0.00123456"]) + //% self.expect("frame variable f_neg4", substrs=["0.000123456"]) + //% self.expect("frame variable f_neg5", substrs=["0.0000123456"]) + //% self.expect("frame variable f_neg6", substrs=["0.00000123456"]) + //% self.expect("frame variable f_neg7", substrs=["1.234567", "E-7"]) + //% self.expect("frame variable f_neg8", substrs=["1.23456", "E-8"]) + //% self.expect("frame variable f_neg20", substrs=["E-20"]) + //% self.expect("frame variable f_neg30", substrs=["E-30"]) + //% self.expect("frame variable f_3", substrs=["1234.56"]) + //% self.expect("frame variable f_4", substrs=["12345.6"]) + //% self.expect("frame variable f_5", substrs=["123456"]) + //% self.expect("frame variable f_6", substrs=["123456"]) + //% self.expect("frame variable f_7", substrs=["123456"]) + //% self.expect("frame variable f_8", substrs=["123456"]) + //% self.expect("frame variable f_20", substrs=["E+20"]) + //% self.expect("frame variable f_30", substrs=["E+30"]) + //% self.expect("frame variable d_neg3", substrs=["0.00123456"]) + //% self.expect("frame variable d_neg4", substrs=["0.000123456"]) + //% self.expect("frame variable d_neg5", substrs=["0.0000123456"]) + //% self.expect("frame variable d_neg6", substrs=["0.00000123456"]) + //% self.expect("frame variable d_neg7", substrs=["1.23456", "E-7"]) + //% self.expect("frame variable d_neg8", substrs=["1.23456", "E-8"]) + //% self.expect("frame variable d_neg20", substrs=["1.23456", "E-20"]) + //% self.expect("frame variable d_neg30", substrs=["1.23456", "E-30"]) + //% self.expect("frame variable d_neg50", substrs=["1.23456", "E-50"]) + //% self.expect("frame variable d_neg250", substrs=["E-250"]) + //% self.expect("frame variable d_3", substrs=["1234.56"]) + //% self.expect("frame variable d_4", substrs=["12345.6"]) + //% self.expect("frame variable d_5", substrs=["123456"]) + //% self.expect("frame variable d_6", substrs=["1234567"]) + //% self.expect("frame variable d_7", substrs=["1234567"]) + //% self.expect("frame variable d_8", substrs=["1234567"]) + //% self.expect("frame variable d_20", substrs=["1.23456", "E+20"]) + //% self.expect("frame variable d_30", substrs=["1.23456", "E+30"]) + //% self.expect("frame variable d_50", substrs=["1.23456", "E+50"]) + //% self.expect("frame variable d_250", substrs=["1.23456", "E+250"]) + //% # Now change the setting to print all the zeroes. + //% # Note that changing this setting should invalidate the data visualizer + //% # cache so that the new setting is used in the following calls. + //% self.runCmd("settings set target.max-zero-padding-in-float-format 9999") + //% self.expect("frame variable f_neg3", substrs=["0.00123456"]) + //% self.expect("frame variable f_neg4", substrs=["0.000123456"]) + //% self.expect("frame variable f_neg5", substrs=["0.0000123456"]) + //% self.expect("frame variable f_neg6", substrs=["0.00000123456"]) + //% self.expect("frame variable f_neg7", substrs=["0.000000123456"]) + //% self.expect("frame variable f_neg8", substrs=["0.0000000123456"]) + //% self.expect("frame variable f_neg20", substrs=["0.0000000000000000000123456"]) + //% self.expect("frame variable f_neg30", substrs=["0.00000000000000000000000000000123456"]) + //% self.expect("frame variable f_3", substrs=["1234.56"]) + //% self.expect("frame variable f_4", substrs=["12345.6"]) + //% self.expect("frame variable f_5", substrs=["123456"]) + //% self.expect("frame variable f_6", substrs=["1234567"]) + //% self.expect("frame variable f_7", substrs=["1234567"]) + //% self.expect("frame variable f_8", substrs=["1234567"]) + //% self.expect("frame variable f_20", substrs=["E+20"]) + //% self.expect("frame variable f_30", substrs=["E+30"]) + //% self.expect("frame variable d_neg3", substrs=["0.00123456"]) + //% self.expect("frame variable d_neg4", substrs=["0.000123456"]) + //% self.expect("frame variable d_neg5", substrs=["0.0000123456"]) + //% self.expect("frame variable d_neg6", substrs=["0.00000123456"]) + //% self.expect("frame variable d_neg7", substrs=["0.000000123456"]) + //% self.expect("frame variable d_neg8", substrs=["0.0000000123456"]) + //% self.expect("frame variable d_neg20", substrs=["0.0000000000000000000123456"]) + //% self.expect("frame variable d_neg30", substrs=["0.000000000000000000000000000001234567"]) + //% self.expect("frame variable d_neg50", substrs=["0.0000000000000000000000000000000000000000000000000123456"]) + //% self.expect("frame variable d_neg250", substrs=["0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123456"]) + //% self.expect("frame variable d_3", substrs=["1234.56"]) + //% self.expect("frame variable d_4", substrs=["12345.6"]) + //% self.expect("frame variable d_5", substrs=["123456"]) + //% self.expect("frame variable d_6", substrs=["1234567"]) + //% self.expect("frame variable d_7", substrs=["1234567"]) + //% self.expect("frame variable d_8", substrs=["1234567"]) + //% # Positive numbers are not affected by this setting. + //% self.expect("frame variable d_20", substrs=["1.23456", "E+20"]) + //% self.expect("frame variable d_30", substrs=["1.23456", "E+30"]) + //% self.expect("frame variable d_50", substrs=["1.23456", "E+50"]) + //% self.expect("frame variable d_250", substrs=["1.23456", "E+250"]) + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestArmRegisterDefinition.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestArmRegisterDefinition.py new file mode 100644 index 00000000000..28424f0f362 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestArmRegisterDefinition.py @@ -0,0 +1,131 @@ +from __future__ import print_function +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + +class TestArmRegisterDefinition(GDBRemoteTestBase): + + @skipIfXmlSupportMissing + @skipIfRemote + def test(self): + """ + Test lldb's parsing of the <architecture> tag in the target.xml register + description packet. + """ + class MyResponder(MockGDBServerResponder): + + def qXferRead(self, obj, annex, offset, length): + if annex == "target.xml": + return """<?xml version="1.0"?> + <!DOCTYPE feature SYSTEM "gdb-target.dtd"> + <target> + <architecture>arm</architecture> + <feature name="org.gnu.gdb.arm.m-profile"> + <reg name="r0" bitsize="32" type="uint32" group="general"/> + <reg name="r1" bitsize="32" type="uint32" group="general"/> + <reg name="r2" bitsize="32" type="uint32" group="general"/> + <reg name="r3" bitsize="32" type="uint32" group="general"/> + <reg name="r4" bitsize="32" type="uint32" group="general"/> + <reg name="r5" bitsize="32" type="uint32" group="general"/> + <reg name="r6" bitsize="32" type="uint32" group="general"/> + <reg name="r7" bitsize="32" type="uint32" group="general"/> + <reg name="r8" bitsize="32" type="uint32" group="general"/> + <reg name="r9" bitsize="32" type="uint32" group="general"/> + <reg name="r10" bitsize="32" type="uint32" group="general"/> + <reg name="r11" bitsize="32" type="uint32" group="general"/> + <reg name="r12" bitsize="32" type="uint32" group="general"/> + <reg name="sp" bitsize="32" type="data_ptr" group="general"/> + <reg name="lr" bitsize="32" type="uint32" group="general"/> + <reg name="pc" bitsize="32" type="code_ptr" group="general"/> + <reg name="xpsr" bitsize="32" regnum="25" type="uint32" group="general"/> + <reg name="MSP" bitsize="32" regnum="26" type="uint32" group="general"/> + <reg name="PSP" bitsize="32" regnum="27" type="uint32" group="general"/> + <reg name="PRIMASK" bitsize="32" regnum="28" type="uint32" group="general"/> + <reg name="BASEPRI" bitsize="32" regnum="29" type="uint32" group="general"/> + <reg name="FAULTMASK" bitsize="32" regnum="30" type="uint32" group="general"/> + <reg name="CONTROL" bitsize="32" regnum="31" type="uint32" group="general"/> + <reg name="FPSCR" bitsize="32" type="uint32" group="float"/> + <reg name="s0" bitsize="32" type="float" group="float"/> + <reg name="s1" bitsize="32" type="float" group="float"/> + <reg name="s2" bitsize="32" type="float" group="float"/> + <reg name="s3" bitsize="32" type="float" group="float"/> + <reg name="s4" bitsize="32" type="float" group="float"/> + <reg name="s5" bitsize="32" type="float" group="float"/> + <reg name="s6" bitsize="32" type="float" group="float"/> + <reg name="s7" bitsize="32" type="float" group="float"/> + <reg name="s8" bitsize="32" type="float" group="float"/> + <reg name="s9" bitsize="32" type="float" group="float"/> + <reg name="s10" bitsize="32" type="float" group="float"/> + <reg name="s11" bitsize="32" type="float" group="float"/> + <reg name="s12" bitsize="32" type="float" group="float"/> + <reg name="s13" bitsize="32" type="float" group="float"/> + <reg name="s14" bitsize="32" type="float" group="float"/> + <reg name="s15" bitsize="32" type="float" group="float"/> + <reg name="s16" bitsize="32" type="float" group="float"/> + <reg name="s17" bitsize="32" type="float" group="float"/> + <reg name="s18" bitsize="32" type="float" group="float"/> + <reg name="s19" bitsize="32" type="float" group="float"/> + <reg name="s20" bitsize="32" type="float" group="float"/> + <reg name="s21" bitsize="32" type="float" group="float"/> + <reg name="s22" bitsize="32" type="float" group="float"/> + <reg name="s23" bitsize="32" type="float" group="float"/> + <reg name="s24" bitsize="32" type="float" group="float"/> + <reg name="s25" bitsize="32" type="float" group="float"/> + <reg name="s26" bitsize="32" type="float" group="float"/> + <reg name="s27" bitsize="32" type="float" group="float"/> + <reg name="s28" bitsize="32" type="float" group="float"/> + <reg name="s29" bitsize="32" type="float" group="float"/> + <reg name="s30" bitsize="32" type="float" group="float"/> + <reg name="s31" bitsize="32" type="float" group="float"/> + </feature> + </target>""", False + else: + return None, False + + def readRegister(self, regnum): + return "E01" + + def readRegisters(self): + return "20000000f8360020001000002fcb0008f8360020a0360020200c0020000000000000000000000000000000000000000000000000b87f0120b7d100082ed2000800000001b87f01200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + + def haltReason(self): + return "S05" + + def qfThreadInfo(self): + return "mdead" + + def qC(self): + return "" + + def qSupported(self, client_supported): + return "PacketSize=4000;qXfer:memory-map:read-;QStartNoAckMode+;qXfer:threads:read+;hwbreak+;qXfer:features:read+" + + def QThreadSuffixSupported(self): + return "OK" + + def QListThreadsInStopReply(self): + return "OK" + + self.server.responder = MyResponder() + if self.TraceOn(): + self.runCmd("log enable gdb-remote packets") + self.addTearDownHook( + lambda: self.runCmd("log disable gdb-remote packets")) + + self.dbg.SetDefaultArchitecture("armv7em") + target = self.dbg.CreateTargetWithFileAndArch(None, None) + + process = self.connect(target) + + if self.TraceOn(): + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + interp.HandleCommand("target list", result) + print(result.GetOutput()) + + r0_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("r0") + self.assertEqual(r0_valobj.GetValueAsUnsigned(), 0x20) + + pc_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("pc") + self.assertEqual(pc_valobj.GetValueAsUnsigned(), 0x0800d22e) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestGDBRemoteClient.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestGDBRemoteClient.py new file mode 100644 index 00000000000..8f0ed9a4933 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestGDBRemoteClient.py @@ -0,0 +1,127 @@ +import lldb +import binascii +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + + +class TestGDBRemoteClient(GDBRemoteTestBase): + + class gPacketResponder(MockGDBServerResponder): + def readRegisters(self): + return '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' + + def setUp(self): + super(TestGDBRemoteClient, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(TestGDBRemoteClient, self).tearDown() + + def test_connect(self): + """Test connecting to a remote gdb server""" + target = self.createTarget("a.yaml") + process = self.connect(target) + self.assertPacketLogContains(["qProcessInfo", "qfThreadInfo"]) + + def test_attach_fail(self): + error_msg = "mock-error-msg" + + class MyResponder(MockGDBServerResponder): + # Pretend we don't have any process during the initial queries. + def qC(self): + return "E42" + + def qfThreadInfo(self): + return "OK" # No threads. + + # Then, when we are asked to attach, error out. + def vAttach(self, pid): + return "E42;" + binascii.hexlify(error_msg.encode()).decode() + + self.server.responder = MyResponder() + + target = self.dbg.CreateTarget("") + process = self.connect(target) + lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, [lldb.eStateConnected]) + + error = lldb.SBError() + target.AttachToProcessWithID(lldb.SBListener(), 47, error) + self.assertEquals(error_msg, error.GetCString()) + + def test_read_registers_using_g_packets(self): + """Test reading registers using 'g' packets (default behavior)""" + self.dbg.HandleCommand( + "settings set plugin.process.gdb-remote.use-g-packet-for-reading true") + self.addTearDownHook(lambda: + self.runCmd("settings set plugin.process.gdb-remote.use-g-packet-for-reading false")) + self.server.responder = self.gPacketResponder() + target = self.createTarget("a.yaml") + process = self.connect(target) + + self.assertEquals(1, self.server.responder.packetLog.count("g")) + self.server.responder.packetLog = [] + self.read_registers(process) + # Reading registers should not cause any 'p' packets to be exchanged. + self.assertEquals( + 0, len([p for p in self.server.responder.packetLog if p.startswith("p")])) + + def test_read_registers_using_p_packets(self): + """Test reading registers using 'p' packets""" + self.dbg.HandleCommand( + "settings set plugin.process.gdb-remote.use-g-packet-for-reading false") + target = self.createTarget("a.yaml") + process = self.connect(target) + + self.read_registers(process) + self.assertFalse("g" in self.server.responder.packetLog) + self.assertGreater( + len([p for p in self.server.responder.packetLog if p.startswith("p")]), 0) + + def test_write_registers_using_P_packets(self): + """Test writing registers using 'P' packets (default behavior)""" + self.server.responder = self.gPacketResponder() + target = self.createTarget("a.yaml") + process = self.connect(target) + + self.write_registers(process) + self.assertEquals(0, len( + [p for p in self.server.responder.packetLog if p.startswith("G")])) + self.assertGreater( + len([p for p in self.server.responder.packetLog if p.startswith("P")]), 0) + + def test_write_registers_using_G_packets(self): + """Test writing registers using 'G' packets""" + + class MyResponder(self.gPacketResponder): + def readRegister(self, register): + # empty string means unsupported + return "" + + self.server.responder = MyResponder() + target = self.createTarget("a.yaml") + process = self.connect(target) + + self.write_registers(process) + self.assertEquals(0, len( + [p for p in self.server.responder.packetLog if p.startswith("P")])) + self.assertGreater(len( + [p for p in self.server.responder.packetLog if p.startswith("G")]), 0) + + def read_registers(self, process): + self.for_each_gpr( + process, lambda r: self.assertEquals("0x00000000", r.GetValue())) + + def write_registers(self, process): + self.for_each_gpr( + process, lambda r: r.SetValueFromCString("0x00000000")) + + def for_each_gpr(self, process, operation): + registers = process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetRegisters() + self.assertGreater(registers.GetSize(), 0) + regSet = registers[0] + numChildren = regSet.GetNumChildren() + self.assertGreater(numChildren, 0) + for i in range(numChildren): + operation(regSet.GetChildAtIndex(i)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestGDBRemoteLoad.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestGDBRemoteLoad.py new file mode 100644 index 00000000000..f70c854ed6d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestGDBRemoteLoad.py @@ -0,0 +1,80 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + + +class TestGDBRemoteLoad(GDBRemoteTestBase): + + def setUp(self): + super(TestGDBRemoteLoad, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(TestGDBRemoteLoad, self).tearDown() + + def test_module_load_address(self): + """Test that setting the load address of a module uses virtual addresses""" + target = self.createTarget("a.yaml") + process = self.connect(target) + module = target.GetModuleAtIndex(0) + self.assertTrue(module.IsValid()) + self.assertTrue(target.SetModuleLoadAddress(module, 0).Success()) + address = target.ResolveLoadAddress(0x2001) + self.assertTrue(address.IsValid()) + self.assertEqual(".data", address.GetSection().GetName()) + + def test_ram_load(self): + """Test loading an object file to a target's ram""" + target = self.createTarget("a.yaml") + process = self.connect(target) + self.dbg.HandleCommand("target modules load -l -s0") + self.assertPacketLogContains([ + "M1000,4:c3c3c3c3", + "M1004,2:3232" + ]) + + @skipIfXmlSupportMissing + def test_flash_load(self): + """Test loading an object file to a target's flash memory""" + + class Responder(MockGDBServerResponder): + def qSupported(self, client_supported): + return "PacketSize=3fff;QStartNoAckMode+;qXfer:memory-map:read+" + + def qXferRead(self, obj, annex, offset, length): + if obj == "memory-map": + return (self.MEMORY_MAP[offset:offset + length], + offset + length < len(self.MEMORY_MAP)) + return None, False + + def other(self, packet): + if packet[0:11] == "vFlashErase": + return "OK" + if packet[0:11] == "vFlashWrite": + return "OK" + if packet == "vFlashDone": + return "OK" + return "" + + MEMORY_MAP = """<?xml version="1.0"?> +<memory-map> + <memory type="ram" start="0x0" length="0x1000"/> + <memory type="flash" start="0x1000" length="0x1000"> + <property name="blocksize">0x100</property> + </memory> + <memory type="ram" start="0x2000" length="0x1D400"/> +</memory-map> +""" + + self.server.responder = Responder() + target = self.createTarget("a.yaml") + process = self.connect(target) + self.dbg.HandleCommand("target modules load -l -s0") + self.assertPacketLogContains([ + "vFlashErase:1000,100", + "vFlashWrite:1000:\xc3\xc3\xc3\xc3", + "vFlashWrite:1004:\x32\x32", + "vFlashDone" + ]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestJLink6Armv7RegisterDefinition.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestJLink6Armv7RegisterDefinition.py new file mode 100644 index 00000000000..f0113fd9908 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestJLink6Armv7RegisterDefinition.py @@ -0,0 +1,196 @@ +from __future__ import print_function +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + +class TestJLink6Armv7RegisterDefinition(GDBRemoteTestBase): + + @skipIfXmlSupportMissing + @skipIfRemote + def test(self): + """ + Test lldb's parsing of SEGGER J-Link v6.54 register + definition for a Cortex M-4 dev board, and the fact + that the J-Link only supports g/G for reading/writing + register AND the J-Link v6.54 doesn't provide anything + but the general purpose registers.""" + class MyResponder(MockGDBServerResponder): + + def qXferRead(self, obj, annex, offset, length): + if annex == "target.xml": + return """<?xml version="1.0"?> +<!-- Copyright (C) 2008 Free Software Foundation, Inc. + + Copying and distribution of this file, with or without modification, + are permitted in any medium without royalty provided the copyright + notice and this notice are preserved. --> + +<!DOCTYPE feature SYSTEM "gdb-target.dtd"> +<target version="1.0"> + <architecture>arm</architecture> + <feature name="org.gnu.gdb.arm.m-profile"> + <reg name="r0" bitsize="32" regnum="0" type="uint32" group="general"/> + <reg name="r1" bitsize="32" regnum="1" type="uint32" group="general"/> + <reg name="r2" bitsize="32" regnum="2" type="uint32" group="general"/> + <reg name="r3" bitsize="32" regnum="3" type="uint32" group="general"/> + <reg name="r4" bitsize="32" regnum="4" type="uint32" group="general"/> + <reg name="r5" bitsize="32" regnum="5" type="uint32" group="general"/> + <reg name="r6" bitsize="32" regnum="6" type="uint32" group="general"/> + <reg name="r7" bitsize="32" regnum="7" type="uint32" group="general"/> + <reg name="r8" bitsize="32" regnum="8" type="uint32" group="general"/> + <reg name="r9" bitsize="32" regnum="9" type="uint32" group="general"/> + <reg name="r10" bitsize="32" regnum="10" type="uint32" group="general"/> + <reg name="r11" bitsize="32" regnum="11" type="uint32" group="general"/> + <reg name="r12" bitsize="32" regnum="12" type="uint32" group="general"/> + <reg name="sp" bitsize="32" regnum="13" type="data_ptr" group="general"/> + <reg name="lr" bitsize="32" regnum="14" type="uint32" group="general"/> + <reg name="pc" bitsize="32" regnum="15" type="code_ptr" group="general"/> + <reg name="xpsr" bitsize="32" regnum="25" type="uint32" group="general"/> + </feature> + <feature name="org.gnu.gdb.arm.m-system"> + <reg name="msp" bitsize="32" regnum="26" type="uint32" group="general"/> + <reg name="psp" bitsize="32" regnum="27" type="uint32" group="general"/> + <reg name="primask" bitsize="32" regnum="28" type="uint32" group="general"/> + <reg name="basepri" bitsize="32" regnum="29" type="uint32" group="general"/> + <reg name="faultmask" bitsize="32" regnum="30" type="uint32" group="general"/> + <reg name="control" bitsize="32" regnum="31" type="uint32" group="general"/> + </feature> + <feature name="org.gnu.gdb.arm.m-float"> + <reg name="fpscr" bitsize="32" regnum="32" type="uint32" group="float"/> + <reg name="s0" bitsize="32" regnum="33" type="float" group="float"/> + <reg name="s1" bitsize="32" regnum="34" type="float" group="float"/> + <reg name="s2" bitsize="32" regnum="35" type="float" group="float"/> + <reg name="s3" bitsize="32" regnum="36" type="float" group="float"/> + <reg name="s4" bitsize="32" regnum="37" type="float" group="float"/> + <reg name="s5" bitsize="32" regnum="38" type="float" group="float"/> + <reg name="s6" bitsize="32" regnum="39" type="float" group="float"/> + <reg name="s7" bitsize="32" regnum="40" type="float" group="float"/> + <reg name="s8" bitsize="32" regnum="41" type="float" group="float"/> + <reg name="s9" bitsize="32" regnum="42" type="float" group="float"/> + <reg name="s10" bitsize="32" regnum="43" type="float" group="float"/> + <reg name="s11" bitsize="32" regnum="44" type="float" group="float"/> + <reg name="s12" bitsize="32" regnum="45" type="float" group="float"/> + <reg name="s13" bitsize="32" regnum="46" type="float" group="float"/> + <reg name="s14" bitsize="32" regnum="47" type="float" group="float"/> + <reg name="s15" bitsize="32" regnum="48" type="float" group="float"/> + <reg name="s16" bitsize="32" regnum="49" type="float" group="float"/> + <reg name="s17" bitsize="32" regnum="50" type="float" group="float"/> + <reg name="s18" bitsize="32" regnum="51" type="float" group="float"/> + <reg name="s19" bitsize="32" regnum="52" type="float" group="float"/> + <reg name="s20" bitsize="32" regnum="53" type="float" group="float"/> + <reg name="s21" bitsize="32" regnum="54" type="float" group="float"/> + <reg name="s22" bitsize="32" regnum="55" type="float" group="float"/> + <reg name="s23" bitsize="32" regnum="56" type="float" group="float"/> + <reg name="s24" bitsize="32" regnum="57" type="float" group="float"/> + <reg name="s25" bitsize="32" regnum="58" type="float" group="float"/> + <reg name="s26" bitsize="32" regnum="59" type="float" group="float"/> + <reg name="s27" bitsize="32" regnum="60" type="float" group="float"/> + <reg name="s28" bitsize="32" regnum="61" type="float" group="float"/> + <reg name="s29" bitsize="32" regnum="62" type="float" group="float"/> + <reg name="s30" bitsize="32" regnum="63" type="float" group="float"/> + <reg name="s31" bitsize="32" regnum="64" type="float" group="float"/> + <reg name="d0" bitsize="64" regnum="65" type="ieee_double" group="float"/> + <reg name="d1" bitsize="64" regnum="66" type="ieee_double" group="float"/> + <reg name="d2" bitsize="64" regnum="67" type="ieee_double" group="float"/> + <reg name="d3" bitsize="64" regnum="68" type="ieee_double" group="float"/> + <reg name="d4" bitsize="64" regnum="69" type="ieee_double" group="float"/> + <reg name="d5" bitsize="64" regnum="70" type="ieee_double" group="float"/> + <reg name="d6" bitsize="64" regnum="71" type="ieee_double" group="float"/> + <reg name="d7" bitsize="64" regnum="72" type="ieee_double" group="float"/> + <reg name="d8" bitsize="64" regnum="73" type="ieee_double" group="float"/> + <reg name="d9" bitsize="64" regnum="74" type="ieee_double" group="float"/> + <reg name="d10" bitsize="64" regnum="75" type="ieee_double" group="float"/> + <reg name="d11" bitsize="64" regnum="76" type="ieee_double" group="float"/> + <reg name="d12" bitsize="64" regnum="77" type="ieee_double" group="float"/> + <reg name="d13" bitsize="64" regnum="78" type="ieee_double" group="float"/> + <reg name="d14" bitsize="64" regnum="79" type="ieee_double" group="float"/> + <reg name="d15" bitsize="64" regnum="80" type="ieee_double" group="float"/> + </feature> +</target>""", False + else: + return None, False + + def readRegister(self, regnum): + return "E01" + + # Initial r1 bytes, in little-endian order + r1_bytes = "01000000" + + ## readRegisters only provides reg values up through xpsr (0x61000000) + ## it doesn't send up any of the exception registers or floating point + ## registers that the above register xml describes. + def readRegisters(self): + return "00000000" + self.r1_bytes + "010000000100000001000000000000008c080020a872012000000000a0790120000000008065012041ad0008a0720120692a00089e26000800000061" + + ## the J-Link accepts a register write packet with just the GPRs + ## defined. + def writeRegisters(self, registers_hex): + # Check that lldb returns the full 704 hex-byte register context, + # or the 136 hex-byte general purpose register reg ctx. + if len(registers_hex) != 704 and len(register_hex) != 136: + return "E06" + if registers_hex.startswith("0000000044332211010000000100000001000000000000008c080020a872012000000000a0790120000000008065012041ad0008a0720120692a00089e26000800000061"): + self.r1_bytes = "44332211" + return "OK" + else: + return "E07" + + def haltReason(self): + return "S05" + + def qfThreadInfo(self): + return "mdead" + + def qC(self): + return "" + + def qSupported(self, client_supported): + return "PacketSize=4000;qXfer:memory-map:read-;QStartNoAckMode+;hwbreak+;qXfer:features:read+" + + def QThreadSuffixSupported(self): + return "OK" + + def QListThreadsInStopReply(self): + return "OK" + + self.server.responder = MyResponder() + if self.TraceOn(): + self.runCmd("log enable gdb-remote packets") + self.addTearDownHook( + lambda: self.runCmd("log disable gdb-remote packets")) + + self.dbg.SetDefaultArchitecture("armv7em") + target = self.dbg.CreateTargetWithFileAndArch(None, None) + + process = self.connect(target) + + if self.TraceOn(): + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + interp.HandleCommand("target list", result) + print(result.GetOutput()) + + r1_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("r1") + self.assertEqual(r1_valobj.GetValueAsUnsigned(), 1) + + pc_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("pc") + self.assertEqual(pc_valobj.GetValueAsUnsigned(), 0x0800269e) + + xpsr_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("xpsr") + self.assertEqual(xpsr_valobj.GetValueAsUnsigned(), 0x61000000) + + msp_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("msp") + err = msp_valobj.GetError() + self.assertTrue(err.Fail(), "lldb should not be able to fetch the msp register") + + val = b'\x11\x22\x33\x44' + error = lldb.SBError() + data = lldb.SBData() + data.SetData(error, val, lldb.eByteOrderBig, 4) + self.assertEqual(r1_valobj.SetData(data, error), True) + self.assertTrue(error.Success()) + + r1_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("r1") + self.assertEqual(r1_valobj.GetValueAsUnsigned(), 0x11223344) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestNestedRegDefinitions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestNestedRegDefinitions.py new file mode 100644 index 00000000000..4407e867e70 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestNestedRegDefinitions.py @@ -0,0 +1,238 @@ +from __future__ import print_function +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + +class TestNestedRegDefinitions(GDBRemoteTestBase): + + @skipIfXmlSupportMissing + @skipIfRemote + def test(self): + """ + Test lldb's parsing of the <architecture> tag in the target.xml register + description packet. + """ + class MyResponder(MockGDBServerResponder): + + def qXferRead(self, obj, annex, offset, length): + if annex == "target.xml": + return """<?xml version="1.0"?><!DOCTYPE target SYSTEM "gdb-target.dtd"><target><architecture>i386:x86-64</architecture><xi:include href="i386-64bit.xml"/></target>""", False + + if annex == "i386-64bit.xml": + return """<?xml version="1.0"?> +<!-- Copyright (C) 2010-2017 Free Software Foundation, Inc. + + Copying and distribution of this file, with or without modification, + are permitted in any medium without royalty provided the copyright + notice and this notice are preserved. --> + +<!-- I386 64bit --> + +<!DOCTYPE target SYSTEM "gdb-target.dtd"> +<feature name="org.gnu.gdb.i386.64bit"> + <xi:include href="i386-64bit-core.xml"/> + <xi:include href="i386-64bit-sse.xml"/> +</feature>""", False + + if annex == "i386-64bit-core.xml": + return """<?xml version="1.0"?> +<!-- Copyright (C) 2010-2015 Free Software Foundation, Inc. + + Copying and distribution of this file, with or without modification, + are permitted in any medium without royalty provided the copyright + notice and this notice are preserved. --> + +<!DOCTYPE feature SYSTEM "gdb-target.dtd"> +<feature name="org.gnu.gdb.i386.core"> + <flags id="i386_eflags" size="4"> + <field name="CF" start="0" end="0"/> + <field name="" start="1" end="1"/> + <field name="PF" start="2" end="2"/> + <field name="AF" start="4" end="4"/> + <field name="ZF" start="6" end="6"/> + <field name="SF" start="7" end="7"/> + <field name="TF" start="8" end="8"/> + <field name="IF" start="9" end="9"/> + <field name="DF" start="10" end="10"/> + <field name="OF" start="11" end="11"/> + <field name="NT" start="14" end="14"/> + <field name="RF" start="16" end="16"/> + <field name="VM" start="17" end="17"/> + <field name="AC" start="18" end="18"/> + <field name="VIF" start="19" end="19"/> + <field name="VIP" start="20" end="20"/> + <field name="ID" start="21" end="21"/> + </flags> + + <reg name="rax" bitsize="64" type="int64"/> + <reg name="rbx" bitsize="64" type="int64"/> + <reg name="rcx" bitsize="64" type="int64"/> + <reg name="rdx" bitsize="64" type="int64"/> + <reg name="rsi" bitsize="64" type="int64"/> + <reg name="rdi" bitsize="64" type="int64"/> + <reg name="rbp" bitsize="64" type="data_ptr"/> + <reg name="rsp" bitsize="64" type="data_ptr"/> + <reg name="r8" bitsize="64" type="int64"/> + <reg name="r9" bitsize="64" type="int64"/> + <reg name="r10" bitsize="64" type="int64"/> + <reg name="r11" bitsize="64" type="int64"/> + <reg name="r12" bitsize="64" type="int64"/> + <reg name="r13" bitsize="64" type="int64"/> + <reg name="r14" bitsize="64" type="int64"/> + <reg name="r15" bitsize="64" type="int64"/> + + <reg name="rip" bitsize="64" type="code_ptr"/> + <reg name="eflags" bitsize="32" type="i386_eflags"/> + <reg name="cs" bitsize="32" type="int32"/> + <reg name="ss" bitsize="32" type="int32"/> + <reg name="ds" bitsize="32" type="int32"/> + <reg name="es" bitsize="32" type="int32"/> + <reg name="fs" bitsize="32" type="int32"/> + <reg name="gs" bitsize="32" type="int32"/> + + <reg name="st0" bitsize="80" type="i387_ext"/> + <reg name="st1" bitsize="80" type="i387_ext"/> + <reg name="st2" bitsize="80" type="i387_ext"/> + <reg name="st3" bitsize="80" type="i387_ext"/> + <reg name="st4" bitsize="80" type="i387_ext"/> + <reg name="st5" bitsize="80" type="i387_ext"/> + <reg name="st6" bitsize="80" type="i387_ext"/> + <reg name="st7" bitsize="80" type="i387_ext"/> + + <reg name="fctrl" bitsize="32" type="int" group="float"/> + <reg name="fstat" bitsize="32" type="int" group="float"/> + <reg name="ftag" bitsize="32" type="int" group="float"/> + <reg name="fiseg" bitsize="32" type="int" group="float"/> + <reg name="fioff" bitsize="32" type="int" group="float"/> + <reg name="foseg" bitsize="32" type="int" group="float"/> + <reg name="fooff" bitsize="32" type="int" group="float"/> + <reg name="fop" bitsize="32" type="int" group="float"/> +</feature>""", False + + if annex == "i386-64bit-sse.xml": + return """<?xml version="1.0"?> +<!-- Copyright (C) 2010-2017 Free Software Foundation, Inc. + + Copying and distribution of this file, with or without modification, + are permitted in any medium without royalty provided the copyright + notice and this notice are preserved. --> + +<!DOCTYPE feature SYSTEM "gdb-target.dtd"> +<feature name="org.gnu.gdb.i386.64bit.sse"> + <vector id="v4f" type="ieee_single" count="4"/> + <vector id="v2d" type="ieee_double" count="2"/> + <vector id="v16i8" type="int8" count="16"/> + <vector id="v8i16" type="int16" count="8"/> + <vector id="v4i32" type="int32" count="4"/> + <vector id="v2i64" type="int64" count="2"/> + <union id="vec128"> + <field name="v4_float" type="v4f"/> + <field name="v2_double" type="v2d"/> + <field name="v16_int8" type="v16i8"/> + <field name="v8_int16" type="v8i16"/> + <field name="v4_int32" type="v4i32"/> + <field name="v2_int64" type="v2i64"/> + <field name="uint128" type="uint128"/> + </union> + <flags id="i386_mxcsr" size="4"> + <field name="IE" start="0" end="0"/> + <field name="DE" start="1" end="1"/> + <field name="ZE" start="2" end="2"/> + <field name="OE" start="3" end="3"/> + <field name="UE" start="4" end="4"/> + <field name="PE" start="5" end="5"/> + <field name="DAZ" start="6" end="6"/> + <field name="IM" start="7" end="7"/> + <field name="DM" start="8" end="8"/> + <field name="ZM" start="9" end="9"/> + <field name="OM" start="10" end="10"/> + <field name="UM" start="11" end="11"/> + <field name="PM" start="12" end="12"/> + <field name="FZ" start="15" end="15"/> + </flags> + + <reg name="xmm0" bitsize="128" type="vec128" regnum="40"/> + <reg name="xmm1" bitsize="128" type="vec128"/> + <reg name="xmm2" bitsize="128" type="vec128"/> + <reg name="xmm3" bitsize="128" type="vec128"/> + <reg name="xmm4" bitsize="128" type="vec128"/> + <reg name="xmm5" bitsize="128" type="vec128"/> + <reg name="xmm6" bitsize="128" type="vec128"/> + <reg name="xmm7" bitsize="128" type="vec128"/> + <reg name="xmm8" bitsize="128" type="vec128"/> + <reg name="xmm9" bitsize="128" type="vec128"/> + <reg name="xmm10" bitsize="128" type="vec128"/> + <reg name="xmm11" bitsize="128" type="vec128"/> + <reg name="xmm12" bitsize="128" type="vec128"/> + <reg name="xmm13" bitsize="128" type="vec128"/> + <reg name="xmm14" bitsize="128" type="vec128"/> + <reg name="xmm15" bitsize="128" type="vec128"/> + + <reg name="mxcsr" bitsize="32" type="i386_mxcsr" group="vector"/> +</feature>""", False + + return None, False + + def readRegister(self, regnum): + return "" + + def readRegisters(self): + return "0600000000000000c0b7c00080fffffff021c60080ffffff1a00000000000000020000000000000078b7c00080ffffff203f8ca090ffffff103f8ca090ffffff3025990a80ffffff809698000000000070009f0a80ffffff020000000000000000eae10080ffffff00000000000000001822d74f1a00000078b7c00080ffffff0e12410080ffff004602000008000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f0300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000801f0000" + + def haltReason(self): + return "T02thread:dead;threads:dead;" + + def qfThreadInfo(self): + return "mdead" + + def qC(self): + return "" + + def qSupported(self, client_supported): + return "PacketSize=4000;qXfer:features:read+" + + def QThreadSuffixSupported(self): + return "OK" + + def QListThreadsInStopReply(self): + return "OK" + + self.server.responder = MyResponder() + if self.TraceOn(): + self.runCmd("log enable gdb-remote packets") + self.addTearDownHook( + lambda: self.runCmd("log disable gdb-remote packets")) + + target = self.dbg.CreateTargetWithFileAndArch(None, None) + + process = self.connect(target) + + if self.TraceOn(): + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + interp.HandleCommand("target list", result) + print(result.GetOutput()) + + rip_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("rip") + self.assertEqual(rip_valobj.GetValueAsUnsigned(), 0x00ffff800041120e) + + r15_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("r15") + self.assertEqual(r15_valobj.GetValueAsUnsigned(), 0xffffff8000c0b778) + + mxcsr_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("mxcsr") + self.assertEqual(mxcsr_valobj.GetValueAsUnsigned(), 0x00001f80) + + gpr_reg_set_name = process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetRegisters().GetValueAtIndex(0).GetName() + self.assertEqual(gpr_reg_set_name, "general") + + float_reg_set_name = process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetRegisters().GetValueAtIndex(1).GetName() + self.assertEqual(float_reg_set_name, "float") + + vector_reg_set_name = process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetRegisters().GetValueAtIndex(2).GetName() + self.assertEqual(vector_reg_set_name, "vector") + + if self.TraceOn(): + print("rip is 0x%x" % rip_valobj.GetValueAsUnsigned()) + print("r15 is 0x%x" % r15_valobj.GetValueAsUnsigned()) + print("mxcsr is 0x%x" % mxcsr_valobj.GetValueAsUnsigned()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestNoGPacketSupported.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestNoGPacketSupported.py new file mode 100644 index 00000000000..6a17173cba4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestNoGPacketSupported.py @@ -0,0 +1,96 @@ +from __future__ import print_function +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + + +# This test case is testing three things: +# +# 1. three register values will be provided in the ? stop packet (T11) - +# registers 0 ("rax"), 1 ("rbx"), and 3 ("rip") +# 2. ReadRegister packet will provide the value of register 2 ("rsi") +# 3. The "g" read-all-registers packet is not supported; p must be used +# to get the value of register 2 ("rsi") +# +# Forcing lldb to use the expedited registers in the stop packet and +# marking it an error to request that register value is to prevent +# performance regressions. +# +# Some gdb RSP stubs only implement p/P, they do not support g/G. +# lldb must be able to work with either. + +class TestNoGPacketSupported(GDBRemoteTestBase): + + @skipIfXmlSupportMissing + def test(self): + class MyResponder(MockGDBServerResponder): + def haltReason(self): + return "T02thread:1ff0d;threads:1ff0d;thread-pcs:000000010001bc00;00:7882773ce0ffffff;01:1122334455667788;03:00bc010001000000;" + + def threadStopInfo(self, threadnum): + return "T02thread:1ff0d;threads:1ff0d;thread-pcs:000000010001bc00;00:7882773ce0ffffff;01:1122334455667788;03:00bc010001000000;" + + def writeRegisters(self): + return "E02" + + def readRegisters(self): + return "E01" + + def readRegister(self, regnum): + # lldb will try sending "p0" to see if the p packet is supported, + # give a bogus value; in theory lldb could use this value in the + # register context and that would be valid behavior. + + # notably, don't give values for registers 1 & 3 -- lldb should + # get those from the ? stop packet ("T11") and it is a pref regression + # if lldb is asking for these register values. + if regnum == 0: + return "5555555555555555" + if regnum == 2: + return "c04825ebfe7f0000" # 0x00007ffeeb2548c0 + + return "E03" + + def writeRegister(self, regnum): + return "OK" + + def qXferRead(self, obj, annex, offset, length): + if annex == "target.xml": + return """<?xml version="1.0"?> + <target version="1.0"> + <architecture>i386:x86-64</architecture> + <feature name="org.gnu.gdb.i386.core"> + <reg name="rax" bitsize="64" regnum="0" type="code_ptr" group="general"/> + <reg name="rbx" bitsize="64" regnum="1" type="code_ptr" group="general"/> + <reg name="rsi" bitsize="64" regnum="2" type="code_ptr" group="general"/> + <reg name="rip" bitsize="64" regnum="3" type="code_ptr" group="general" altname="pc" generic="pc"/> + </feature> + </target>""", False + else: + return None, False + + self.server.responder = MyResponder() + target = self.dbg.CreateTarget('') + if self.TraceOn(): + self.runCmd("log enable gdb-remote packets") + self.addTearDownHook( + lambda: self.runCmd("log disable gdb-remote packets")) + process = self.connect(target) + + thread = process.GetThreadAtIndex(0) + frame = thread.GetFrameAtIndex(0) + rax = frame.FindRegister("rax").GetValueAsUnsigned() + rbx = frame.FindRegister("rbx").GetValueAsUnsigned() + rsi = frame.FindRegister("rsi").GetValueAsUnsigned() + pc = frame.GetPC() + rip = frame.FindRegister("rip").GetValueAsUnsigned() + + if self.TraceOn(): + print("Register values: rax == 0x%x, rbx == 0x%x, rsi == 0x%x, pc == 0x%x, rip == 0x%x" % (rax, rbx, rsi, pc, rip)) + + self.assertEqual(rax, 0xffffffe03c778278) + self.assertEqual(rbx, 0x8877665544332211) + self.assertEqual(rsi, 0x00007ffeeb2548c0) + self.assertEqual(pc, 0x10001bc00) + self.assertEqual(rip, 0x10001bc00) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestNoWatchpointSupportInfo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestNoWatchpointSupportInfo.py new file mode 100644 index 00000000000..3bf22d376b2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestNoWatchpointSupportInfo.py @@ -0,0 +1,66 @@ +from __future__ import print_function +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + +class TestNoWatchpointSupportInfo(GDBRemoteTestBase): + + @skipIfXmlSupportMissing + @skipIfRemote + def test(self): + """ + Test lldb's parsing of the <architecture> tag in the target.xml register + description packet. + """ + class MyResponder(MockGDBServerResponder): + + def haltReason(self): + return "T02thread:1ff0d;thread-pcs:10001bc00;" + + def threadStopInfo(self, threadnum): + if threadnum == 0x1ff0d: + return "T02thread:1ff0d;thread-pcs:10001bc00;" + return "" + + def setBreakpoint(self, packet): + if packet.startswith("Z2,"): + return "OK" + + def qXferRead(self, obj, annex, offset, length): + if annex == "target.xml": + return """<?xml version="1.0"?> + <target version="1.0"> + <architecture>i386:x86-64</architecture> + <feature name="org.gnu.gdb.i386.core"> + <reg name="rip" bitsize="64" regnum="0" type="code_ptr" group="general"/> + </feature> + </target>""", False + else: + return None, False + + self.server.responder = MyResponder() + if self.TraceOn(): + self.runCmd("log enable gdb-remote packets") + self.addTearDownHook( + lambda: self.runCmd("log disable gdb-remote packets")) + self.dbg.SetDefaultArchitecture("x86_64") + target = self.dbg.CreateTargetWithFileAndArch(None, None) + + process = self.connect(target) + + if self.TraceOn(): + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + interp.HandleCommand("target list", result) + print(result.GetOutput()) + + + err = lldb.SBError() + wp = target.WatchAddress(0x100, 8, False, True, err) + if self.TraceOn() and (err.Fail() or wp.IsValid == False): + strm = lldb.SBStream() + err.GetDescription(strm) + print("watchpoint failed: %s" % strm.GetData()) + self.assertTrue(wp.IsValid()) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestPlatformClient.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestPlatformClient.py new file mode 100644 index 00000000000..2da8dd59e17 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestPlatformClient.py @@ -0,0 +1,67 @@ +import lldb +import binascii +import os +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + +def hexlify(string): + return binascii.hexlify(string.encode()).decode() + +class TestPlatformClient(GDBRemoteTestBase): + + def test_process_list_with_all_users(self): + """Test connecting to a remote linux platform""" + + class MyResponder(MockGDBServerResponder): + def __init__(self): + MockGDBServerResponder.__init__(self) + self.currentQsProc = 0 + self.all_users = False + + def qfProcessInfo(self, packet): + if "all_users:1" in packet: + self.all_users = True + name = hexlify("/a/test_process") + args = "-".join(map(hexlify, + ["/system/bin/sh", "-c", "/data/local/tmp/lldb-server"])) + return "pid:10;ppid:1;uid:2;gid:3;euid:4;egid:5;name:" + name + ";args:" + args + ";" + else: + self.all_users = False + return "E04" + + def qsProcessInfo(self): + if self.all_users: + if self.currentQsProc == 0: + self.currentQsProc = 1 + name = hexlify("/b/another_test_process") + # This intentionally has a badly encoded argument + args = "X".join(map(hexlify, + ["/system/bin/ls", "--help"])) + return "pid:11;ppid:2;uid:3;gid:4;euid:5;egid:6;name:" + name + ";args:" + args + ";" + elif self.currentQsProc == 1: + self.currentQsProc = 0 + return "E04" + else: + return "E04" + + self.server.responder = MyResponder() + + try: + self.runCmd("platform select remote-linux") + self.runCmd("platform connect connect://localhost:%d" % + self.server.port) + self.assertTrue(self.dbg.GetSelectedPlatform().IsConnected()) + self.expect("platform process list -x", + substrs=["2 matching processes were found", "test_process", "another_test_process"]) + self.expect("platform process list -xv", + substrs=[ + "PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE ARGUMENTS", + "10 1 2 3 4 5 /system/bin/sh -c /data/local/tmp/lldb-server", + "11 2 3 4 5 6"]) + self.expect("platform process list -xv", substrs=["/system/bin/ls"], matching=False) + self.expect("platform process list", + error=True, + substrs=["error: no processes were found on the \"remote-linux\" platform"]) + finally: + self.dbg.GetSelectedPlatform().DisconnectRemote() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestRecognizeBreakpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestRecognizeBreakpoint.py new file mode 100644 index 00000000000..44e2cfa891a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestRecognizeBreakpoint.py @@ -0,0 +1,139 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + + +class TestRecognizeBreakpoint(GDBRemoteTestBase): + """ This tests the case where the gdb-remote server doesn't support any + of the thread-info packets, and just tells which thread got the stop + signal with: + T05thread:01; + There was a bug in lldb that we would set the stop reason from this + packet too early - before we had updated the thread list. So when we + later updated the thread list, we would throw away this info. Normally + we would be able to reconstruct it from the thread info, but not if the + stub doesn't support it """ + + @skipIfXmlSupportMissing + def test(self): + class MyResponder(MockGDBServerResponder): + def __init__(self): + MockGDBServerResponder.__init__(self) + self.thread_info_count = 0 + self.after_cont = False + self.current_thread = 0 + + def cont(self): + # Simulate process stopping due to a breakpoint: + self.after_cont = True + return "T05thread:01;" + + def vCont(self, packet): + self.after_cont = True + return "T05thread:01;" + + def haltReason(self): + return "T02thread:01;" + + def threadStopInfo(self, num): + return "" + + def QThreadSuffixSupported(self): + return "" + + def QListThreadsInStopReply(self): + return "" + + def setBreakpoint(self, packet): + return "OK" + + def qfThreadInfo(self): + return "m1" + + def qsThreadInfo(self): + if (self.thread_info_count % 2) == 0: + str = "m2" + else: + str = "l" + self.thread_info_count += 1 + return str + + def readRegisters(self): + if self.after_cont and self.current_thread == 1: + return "c01e990080ffffff" + else: + return "badcfe10325476980" + + def readRegister(self, regno): + return "" + + def qXferRead(self, obj, annex, offset, length): + if annex == "target.xml": + return """<?xml version="1.0"?> + <target version="1.0"> + <architecture>i386:x86-64</architecture> + <feature name="org.gnu.gdb.i386.core"> + <reg name="rip" bitsize="64" regnum="0" type="code_ptr" group="general"/> + </feature> + </target>""", False + else: + return None, False + + def selectThread(self, op, thread): + if op != 'g': + return '' + + self.current_thread = thread + return "OK" + + def other (self, packet): + if packet == "vCont?": + return "vCont;c;C;s;S" + return '' + + python_os_plugin_path = os.path.join(self.getSourceDir(), + 'operating_system_2.py') + command ="settings set target.process.python-os-plugin-path '{}'".format( + python_os_plugin_path) + self.runCmd(command) + + self.server.responder = MyResponder() + target = self.dbg.CreateTarget("") + process = self.connect(target) + + bkpt = target.BreakpointCreateByAddress(0xffffff8000991ec0) + self.assertEqual(bkpt.GetNumLocations(), 1, "Fake breakpoint was resolved.") + + # Get the initial stop, and we should have two threads. + num_threads = len(process.threads) + self.assertEqual(num_threads, 2, "Got two threads") + + thread_0 = process.threads[0] + self.assertEqual(thread_0.GetStopReason(), 1, "Thread_0 stopped for no reason") + self.assertEqual(thread_0.GetName(), "one", "Thread_0 is called one") + + thread_1 = process.threads[1] + self.assertEqual(thread_1.GetStopReason(), 5, "Thread_0 stopped for SIGSTOP") + self.assertEqual(thread_1.GetName(), "two", "Thread_0 is called two") + + # Now continue and we will fake hitting a breakpoint. + process.Continue() + + self.assertEqual(process.GetState(),lldb.eStateStopped, "Process is stopped") + num_threads = len(process.threads) + + num_threads = len(process.threads) + self.assertEqual(num_threads, 2, "Got two threads") + + thread_0 = process.threads[0] + self.assertEqual(thread_0.GetStopReason(), 1, "Thread_0 stopped for no reason") + self.assertEqual(thread_0.GetName(), "one", "Thread_0 is called one") + + thread_1 = process.threads[1] + self.assertEqual(thread_1.GetStopReason(), 3, "Thread_0 stopped for SIGTRAP") + self.assertEqual(thread_1.GetName(), "three", "Thread_0 is called three") + + self.assertTrue(thread_1.IsValid(), "Thread_1 is valid") + self.assertEqual(thread_1.GetStopReason(), lldb.eStopReasonBreakpoint, "Stopped at breakpoint") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestRegDefinitionInParts.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestRegDefinitionInParts.py new file mode 100644 index 00000000000..c4ba19cc2b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestRegDefinitionInParts.py @@ -0,0 +1,160 @@ +from __future__ import print_function +import lldb +import time +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + +class TestRegDefinitionInParts(GDBRemoteTestBase): + + @skipIfXmlSupportMissing + @skipIfRemote + def test(self): + """ + Test that lldb correctly fetches the target definition file + in multiple chunks if the remote server only provides the + content in small parts, and the small parts it provides is + smaller than the maximum packet size that it declared at + the start of the debug session. qemu does this. + """ + class MyResponder(MockGDBServerResponder): + + def qXferRead(self, obj, annex, offset, length): + if annex == "target.xml": + return """<?xml version="1.0"?> + <!DOCTYPE feature SYSTEM "gdb-target.dtd"> + <target version="1.0"> + <architecture>i386:x86-64</architecture> + <xi:include href="i386-64bit-core.xml"/> + </target>""", False + + if annex == "i386-64bit-core.xml" and offset == 0: + return """<?xml version="1.0"?> +<!-- Copyright (C) 2010-2015 Free Software Foundation, Inc. + + Copying and distribution of this file, with or without modification, + are permitted in any medium without royalty provided the copyright + notice and this notice are preserved. --> + +<!DOCTYPE feature SYSTEM "gdb-target.dtd"> +<feature name="org.gnu.gdb.i386.core"> + <flags id="i386_eflags" size="4"> + <field name="CF" start="0" end="0"/> + <field name="" start="1" end="1"/> + <field name="PF" start="2" end="2"/> + <field name="AF" start="4" end="4"/> + <field name="ZF" start="6" end="6"/> + <field name="SF" start="7" end="7"/> + <field name="TF" start="8" end="8"/> + <field name="IF" start="9" end="9"/> + <field name="DF" start="10" end="10"/> + <field name="OF" start="11" end="11"/> + <field name="NT" start="14" end="14"/> + <field name="RF" start="16" end="16"/> + <field name="VM" start="17" end="17"/> + <field name="AC" start="18" end="18"/> + <field name="VIF" start="19" end="19"/> + <field name="VIP" start="20" end="20"/> + <field name="ID" start="21" end="21"/> + </flags> + + <reg name="rax" bitsize="64" type="int64"/> + <reg name="rbx" bitsize="64" type="int64"/> + <reg name="rcx" bitsize="64" type="int64"/> + <reg name="rdx" bitsize="64" type="int64"/> + <reg name="rsi" bitsize="64" type="int64"/> + <reg name="rdi" bitsize="64" type="int64"/> + <reg name="rbp" bitsize="64" type="data_ptr"/> + <reg name="rsp" bitsize="64" type="data_ptr"/> + <reg name="r8" bitsize="64" type="int64"/> + <reg name="r9" bitsize="64" type="int64"/> + <reg name="r10" bitsize="64" type="int64"/> + <reg name="r11" bitsize="64" type="int64"/> + <reg name="r12" bitsize="64" type="int64"/> + <reg name="r13" bitsize="64" type="int64"/> + <reg name="r14" bitsize="64" type="int64"/> + <reg name="r15" bitsize="64" type="int64"/> + + <reg name="rip" bitsize="64" type="code_ptr"/> + <reg name="eflags" bitsize="32" type="i386_eflags"/> + <reg name="cs" bitsize="32" type="int32"/> + <reg name="ss" bitsize="32" ty""", True + + if annex == "i386-64bit-core.xml" and offset == 2045: + return """pe="int32"/> + <reg name="ds" bitsize="32" type="int32"/> + <reg name="es" bitsize="32" type="int32"/> + <reg name="fs" bitsize="32" type="int32"/> + <reg name="gs" bitsize="32" type="int32"/> + + <reg name="st0" bitsize="80" type="i387_ext"/> + <reg name="st1" bitsize="80" type="i387_ext"/> + <reg name="st2" bitsize="80" type="i387_ext"/> + <reg name="st3" bitsize="80" type="i387_ext"/> + <reg name="st4" bitsize="80" type="i387_ext"/> + <reg name="st5" bitsize="80" type="i387_ext"/> + <reg name="st6" bitsize="80" type="i387_ext"/> + <reg name="st7" bitsize="80" type="i387_ext"/> + + <reg name="fctrl" bitsize="32" type="int" group="float"/> + <reg name="fstat" bitsize="32" type="int" group="float"/> + <reg name="ftag" bitsize="32" type="int" group="float"/> + <reg name="fiseg" bitsize="32" type="int" group="float"/> + <reg name="fioff" bitsize="32" type="int" group="float"/> + <reg name="foseg" bitsize="32" type="int" group="float"/> + <reg name="fooff" bitsize="32" type="int" group="float"/> + <reg name="fop" bitsize="32" type="int" group="float"/> +</feature>""", False + + return None, False + + def readRegister(self, regnum): + return "" + + def readRegisters(self): + return "0600000000000000c0b7c00080fffffff021c60080ffffff1a00000000000000020000000000000078b7c00080ffffff203f8ca090ffffff103f8ca090ffffff3025990a80ffffff809698000000000070009f0a80ffffff020000000000000000eae10080ffffff00000000000000001822d74f1a00000078b7c00080ffffff0e12410080ffff004602000011111111222222223333333300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007f0300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000801f0000" + + def haltReason(self): + return "T02thread:dead;threads:dead;" + + def qfThreadInfo(self): + return "mdead" + + def qC(self): + return "" + + def qSupported(self, client_supported): + return "PacketSize=1000;qXfer:features:read+" + + def QThreadSuffixSupported(self): + return "OK" + + def QListThreadsInStopReply(self): + return "OK" + + self.server.responder = MyResponder() + if self.TraceOn(): + self.runCmd("log enable gdb-remote packets") + time.sleep(10) + self.addTearDownHook( + lambda: self.runCmd("log disable gdb-remote packets")) + + target = self.dbg.CreateTargetWithFileAndArch(None, None) + + process = self.connect(target) + + if self.TraceOn(): + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + interp.HandleCommand("target list", result) + print(result.GetOutput()) + + rip_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("rip") + self.assertEqual(rip_valobj.GetValueAsUnsigned(), 0x00ffff800041120e) + + ss_valobj = process.GetThreadAtIndex(0).GetFrameAtIndex(0).FindRegister("ss") + self.assertEqual(ss_valobj.GetValueAsUnsigned(), 0x22222222) + + if self.TraceOn(): + print("rip is 0x%x" % rip_valobj.GetValueAsUnsigned()) + print("ss is 0x%x" % ss_valobj.GetValueAsUnsigned()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestRestartBug.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestRestartBug.py new file mode 100644 index 00000000000..142861a37df --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestRestartBug.py @@ -0,0 +1,62 @@ +from __future__ import print_function +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + + +class TestRestartBug(GDBRemoteTestBase): + + @expectedFailureAll(bugnumber="llvm.org/pr24530") + def test(self): + """ + Test auto-continue behavior when a process is interrupted to deliver + an "asynchronous" packet. This simulates the situation when a process + stops on its own just as lldb client is about to interrupt it. The + client should not auto-continue in this case, unless the user has + explicitly requested that we ignore signals of this type. + """ + class MyResponder(MockGDBServerResponder): + continueCount = 0 + + def setBreakpoint(self, packet): + return "OK" + + def interrupt(self): + # Simulate process stopping due to a raise(SIGINT) just as lldb + # is about to interrupt it. + return "T02reason:signal" + + def cont(self): + self.continueCount += 1 + if self.continueCount == 1: + # No response, wait for the client to interrupt us. + return None + return "W00" # Exit + + self.server.responder = MyResponder() + target = self.createTarget("a.yaml") + process = self.connect(target) + self.dbg.SetAsync(True) + process.Continue() + + # resume the process and immediately try to set another breakpoint. When using the remote + # stub, this will trigger a request to stop the process. Make sure we + # do not lose this signal. + bkpt = target.BreakpointCreateByAddress(0x1234) + self.assertTrue(bkpt.IsValid()) + self.assertEqual(bkpt.GetNumLocations(), 1) + + event = lldb.SBEvent() + while self.dbg.GetListener().WaitForEvent(2, event): + if self.TraceOn(): + print("Process changing state to:", + self.dbg.StateAsCString(process.GetStateFromEvent(event))) + if process.GetStateFromEvent(event) == lldb.eStateExited: + break + + # We should get only one continue packet as the client should not + # auto-continue after setting the breakpoint. + self.assertEqual(self.server.responder.continueCount, 1) + # And the process should end up in the stopped state. + self.assertEqual(process.GetState(), lldb.eStateStopped) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestStopPCs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestStopPCs.py new file mode 100644 index 00000000000..c86d3e75fe8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestStopPCs.py @@ -0,0 +1,47 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + + +class TestStopPCs(GDBRemoteTestBase): + + @skipIfXmlSupportMissing + def test(self): + class MyResponder(MockGDBServerResponder): + def haltReason(self): + return "T02thread:1ff0d;threads:1ff0d,2ff0d;thread-pcs:10001bc00,10002bc00;" + + def threadStopInfo(self, threadnum): + if threadnum == 0x1ff0d: + return "T02thread:1ff0d;threads:1ff0d,2ff0d;thread-pcs:10001bc00,10002bc00;" + if threadnum == 0x2ff0d: + return "T00thread:2ff0d;threads:1ff0d,2ff0d;thread-pcs:10001bc00,10002bc00;" + + def qXferRead(self, obj, annex, offset, length): + if annex == "target.xml": + return """<?xml version="1.0"?> + <target version="1.0"> + <architecture>i386:x86-64</architecture> + <feature name="org.gnu.gdb.i386.core"> + <reg name="rip" bitsize="64" regnum="0" type="code_ptr" group="general"/> + </feature> + </target>""", False + else: + return None, False + + self.server.responder = MyResponder() + target = self.dbg.CreateTarget('') + if self.TraceOn(): + self.runCmd("log enable gdb-remote packets") + self.addTearDownHook( + lambda: self.runCmd("log disable gdb-remote packets")) + process = self.connect(target) + + self.assertEqual(process.GetNumThreads(), 2) + th0 = process.GetThreadAtIndex(0) + th1 = process.GetThreadAtIndex(1) + self.assertEqual(th0.GetThreadID(), 0x1ff0d) + self.assertEqual(th1.GetThreadID(), 0x2ff0d) + self.assertEqual(th0.GetFrameAtIndex(0).GetPC(), 0x10001bc00) + self.assertEqual(th1.GetFrameAtIndex(0).GetPC(), 0x10002bc00) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestTargetXMLArch.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestTargetXMLArch.py new file mode 100644 index 00000000000..20e575ae978 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestTargetXMLArch.py @@ -0,0 +1,145 @@ +from __future__ import print_function +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + +class MyResponder(MockGDBServerResponder): + def qXferRead(self, obj, annex, offset, length): + if annex == "target.xml": + return """<?xml version="1.0"?> + <target version="1.0"> + <architecture>i386:x86-64</architecture> + <feature name="org.gnu.gdb.i386.core"> + + <flags id="i386_eflags" size="4"> + <field name="CF" start="0" end="0"/> + <field name="" start="1" end="1"/> + <field name="PF" start="2" end="2"/> + <field name="AF" start="4" end="4"/> + <field name="ZF" start="6" end="6"/> + <field name="SF" start="7" end="7"/> + <field name="TF" start="8" end="8"/> + <field name="IF" start="9" end="9"/> + <field name="DF" start="10" end="10"/> + <field name="OF" start="11" end="11"/> + <field name="NT" start="14" end="14"/> + <field name="RF" start="16" end="16"/> + <field name="VM" start="17" end="17"/> + <field name="AC" start="18" end="18"/> + <field name="VIF" start="19" end="19"/> + <field name="VIP" start="20" end="20"/> + <field name="ID" start="21" end="21"/> + </flags> + + <reg name="rax" bitsize="64" regnum="0" type="int" group="general"/> + <reg name="rbx" bitsize="64" regnum="1" type="int" group="general"/> + <reg name="rcx" bitsize="64" regnum="2" type="int" group="general"/> + <reg name="rdx" bitsize="64" regnum="3" type="int" group="general"/> + <reg name="rsi" bitsize="64" regnum="4" type="int" group="general"/> + <reg name="rdi" bitsize="64" regnum="5" type="int" group="general"/> + <reg name="rbp" bitsize="64" regnum="6" type="data_ptr" group="general"/> + <reg name="rsp" bitsize="64" regnum="7" type="data_ptr" group="general"/> + <reg name="r8" bitsize="64" regnum="8" type="int" group="general"/> + <reg name="r9" bitsize="64" regnum="9" type="int" group="general"/> + <reg name="r10" bitsize="64" regnum="10" type="int" group="general"/> + <reg name="r11" bitsize="64" regnum="11" type="int" group="general"/> + <reg name="r12" bitsize="64" regnum="12" type="int" group="general"/> + <reg name="r13" bitsize="64" regnum="13" type="int" group="general"/> + <reg name="r14" bitsize="64" regnum="14" type="int" group="general"/> + <reg name="r15" bitsize="64" regnum="15" type="int" group="general"/> + <reg name="rip" bitsize="64" regnum="16" type="code_ptr" group="general"/> + <reg name="eflags" bitsize="32" regnum="17" type="i386_eflags" group="general"/> + + <reg name="cs" bitsize="32" regnum="18" type="int" group="general"/> + <reg name="ss" bitsize="32" regnum="19" type="int" group="general"/> + <reg name="ds" bitsize="32" regnum="20" type="int" group="general"/> + <reg name="es" bitsize="32" regnum="21" type="int" group="general"/> + <reg name="fs" bitsize="32" regnum="22" type="int" group="general"/> + <reg name="gs" bitsize="32" regnum="23" type="int" group="general"/> + + <reg name="st0" bitsize="80" regnum="24" type="i387_ext" group="float"/> + <reg name="st1" bitsize="80" regnum="25" type="i387_ext" group="float"/> + <reg name="st2" bitsize="80" regnum="26" type="i387_ext" group="float"/> + <reg name="st3" bitsize="80" regnum="27" type="i387_ext" group="float"/> + <reg name="st4" bitsize="80" regnum="28" type="i387_ext" group="float"/> + <reg name="st5" bitsize="80" regnum="29" type="i387_ext" group="float"/> + <reg name="st6" bitsize="80" regnum="30" type="i387_ext" group="float"/> + <reg name="st7" bitsize="80" regnum="31" type="i387_ext" group="float"/> + + <reg name="fctrl" bitsize="32" regnum="32" type="int" group="float"/> + <reg name="fstat" bitsize="32" regnum="33" type="int" group="float"/> + <reg name="ftag" bitsize="32" regnum="34" type="int" group="float"/> + <reg name="fiseg" bitsize="32" regnum="35" type="int" group="float"/> + <reg name="fioff" bitsize="32" regnum="36" type="int" group="float"/> + <reg name="foseg" bitsize="32" regnum="37" type="int" group="float"/> + <reg name="fooff" bitsize="32" regnum="38" type="int" group="float"/> + <reg name="fop" bitsize="32" regnum="39" type="int" group="float"/> + </feature> + </target>""", False + else: + return None, False + + def qC(self): + return "QC1" + + def haltReason(self): + return "T05thread:00000001;06:9038d60f00700000;07:98b4062680ffffff;10:c0d7bf1b80ffffff;" + + def readRegister(self, register): + regs = {0x0: "00b0060000610000", + 0xa: "68fe471c80ffffff", + 0xc: "60574a1c80ffffff", + 0xd: "18f3042680ffffff", + 0xe: "be8a4d7142000000", + 0xf: "50df471c80ffffff", + 0x10: "c0d7bf1b80ffffff" } + if register in regs: + return regs[register] + else: + return "0000000000000000" + +class TestTargetXMLArch(GDBRemoteTestBase): + + @skipIfXmlSupportMissing + @expectedFailureAll(archs=["i386"]) + @skipIfRemote + def test(self): + """ + Test lldb's parsing of the <architecture> tag in the target.xml register + description packet. + """ + self.server.responder = MyResponder() + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + if self.TraceOn(): + self.runCmd("log enable gdb-remote packets") + self.addTearDownHook( + lambda: self.runCmd("log disable gdb-remote packets")) + + target = self.dbg.CreateTarget('') + self.assertEqual('', target.GetTriple()) + process = self.connect(target) + if self.TraceOn(): + interp.HandleCommand("target list", result) + print(result.GetOutput()) + self.assertTrue(target.GetTriple().startswith('x86_64-unknown-unknown')) + + @skipIfXmlSupportMissing + @skipIfRemote + def test_register_augmentation(self): + """ + Test that we correctly associate the register info with the eh_frame + register numbers. + """ + + target = self.createTarget("basic_eh_frame.yaml") + self.server.responder = MyResponder() + + process = self.connect(target) + lldbutil.expect_state_changes(self, self.dbg.GetListener(), process, + [lldb.eStateStopped]) + self.filecheck("image show-unwind -n foo", __file__, + "--check-prefix=UNWIND") +# UNWIND: eh_frame UnwindPlan: +# UNWIND: row[0]: 0: CFA=rsp+128 => rip=[CFA-8] diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestThreadSelectionBug.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestThreadSelectionBug.py new file mode 100644 index 00000000000..09022028524 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestThreadSelectionBug.py @@ -0,0 +1,49 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + + +class TestThreadSelectionBug(GDBRemoteTestBase): + def test(self): + class MyResponder(MockGDBServerResponder): + def cont(self): + # Simulate process stopping due to a raise(SIGINT) + return "T01reason:signal" + + self.server.responder = MyResponder() + target = self.createTarget("a.yaml") + process = self.connect(target) + python_os_plugin_path = os.path.join(self.getSourceDir(), + 'operating_system.py') + command = "settings set target.process.python-os-plugin-path '{}'".format( + python_os_plugin_path) + self.dbg.HandleCommand(command) + + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetNumThreads(), 3) + + # Verify our OS plug-in threads showed up + thread = process.GetThreadByID(0x1) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x1 after we load the python OS plug-in") + thread = process.GetThreadByID(0x2) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x2 after we load the python OS plug-in") + thread = process.GetThreadByID(0x3) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x3 after we load the python OS plug-in") + + # Verify that a thread other than 3 is selected. + thread = process.GetSelectedThread() + self.assertNotEqual(thread.GetThreadID(), 0x3) + + # Verify that we select the thread backed by physical thread 1, rather + # than virtual thread 1. The mapping comes from the OS plugin, where we + # specified that thread 3 is backed by real thread 1. + process.Continue() + thread = process.GetSelectedThread() + self.assertEqual(thread.GetThreadID(), 0x3) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestWriteMemory.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestWriteMemory.py new file mode 100644 index 00000000000..b7f19a16bf3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/TestWriteMemory.py @@ -0,0 +1,37 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +from gdbclientutils import * + + +class TestWriteMemory(GDBRemoteTestBase): + + def setUp(self): + super(TestWriteMemory, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(TestWriteMemory, self).tearDown() + + + def test(self): + + class MyResponder(MockGDBServerResponder): + def setBreakpoint(self, packet): + return "OK" + + self.server.responder = MyResponder() + target = self.dbg.CreateTargetWithFileAndTargetTriple('', 'x86_64-pc-linux') + process = self.connect(target) + + bp = target.BreakpointCreateByAddress(0x1000) + self.assertTrue(bp.IsValid()) + self.assertEqual(bp.GetNumLocations(), 1) + bp.SetEnabled(True) + self.assertTrue(bp.IsEnabled()) + + err = lldb.SBError() + data = str("\x01\x02\x03\x04") + result = process.WriteMemory(0x1000, data, err) + self.assertEqual(result, 4) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/a.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/a.yaml new file mode 100644 index 00000000000..f4e9ff5d872 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/a.yaml @@ -0,0 +1,34 @@ +!ELF +FileHeader: + Class: ELFCLASS32 + Data: ELFDATA2LSB + Type: ET_EXEC + Machine: EM_ARM +Sections: + - Name: .text + Type: SHT_PROGBITS + Flags: [ SHF_ALLOC, SHF_EXECINSTR ] + Address: 0x1000 + AddressAlign: 0x4 + Content: "c3c3c3c3" + - Name: .data + Type: SHT_PROGBITS + Flags: [ SHF_ALLOC ] + Address: 0x2000 + AddressAlign: 0x4 + Content: "3232" +ProgramHeaders: + - Type: PT_LOAD + Flags: [ PF_X, PF_R ] + VAddr: 0x1000 + PAddr: 0x1000 + Align: 0x4 + Sections: + - Section: .text + - Type: PT_LOAD + Flags: [ PF_R, PF_W ] + VAddr: 0x2000 + PAddr: 0x1004 + Align: 0x4 + Sections: + - Section: .data diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/basic_eh_frame.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/basic_eh_frame.yaml new file mode 100644 index 00000000000..384b9b992b4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/basic_eh_frame.yaml @@ -0,0 +1,48 @@ +--- !ELF +FileHeader: + Class: ELFCLASS64 + Data: ELFDATA2LSB + Type: ET_EXEC + Machine: EM_X86_64 + Entry: 0x0000000000401000 +Sections: + - Name: .text + Type: SHT_PROGBITS + Flags: [ SHF_ALLOC, SHF_EXECINSTR ] + Address: 0x0000000000401000 + AddressAlign: 0x0000000000000001 + Content: C3 + - Name: .eh_frame + Type: SHT_PROGBITS + Flags: [ SHF_ALLOC ] + Address: 0x0000000000402000 + AddressAlign: 0x0000000000000008 + Content: 1800000000000000017A5200017810011B0C070890010E80010000001000000020000000DCEFFFFF0100000000000000 +Symbols: + - Name: .text + Type: STT_SECTION + Section: .text + Value: 0x0000000000401000 + - Name: .eh_frame + Type: STT_SECTION + Section: .eh_frame + Value: 0x0000000000402000 + - Name: _start + Binding: STB_GLOBAL + - Name: __bss_start + Section: .eh_frame + Binding: STB_GLOBAL + Value: 0x0000000000404000 + - Name: foo + Section: .text + Binding: STB_GLOBAL + Value: 0x0000000000401000 + - Name: _edata + Section: .eh_frame + Binding: STB_GLOBAL + Value: 0x0000000000404000 + - Name: _end + Section: .eh_frame + Binding: STB_GLOBAL + Value: 0x0000000000404000 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/gdbclientutils.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/gdbclientutils.py new file mode 100644 index 00000000000..392aeba5bd6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/gdbclientutils.py @@ -0,0 +1,534 @@ +import os +import os.path +import threading +import socket +import lldb +import binascii +import traceback +from lldbsuite.support import seven +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbtest_config + + +def checksum(message): + """ + Calculate the GDB server protocol checksum of the message. + + The GDB server protocol uses a simple modulo 256 sum. + """ + check = 0 + for c in message: + check += ord(c) + return check % 256 + + +def frame_packet(message): + """ + Create a framed packet that's ready to send over the GDB connection + channel. + + Framing includes surrounding the message between $ and #, and appending + a two character hex checksum. + """ + return "$%s#%02x" % (message, checksum(message)) + + +def escape_binary(message): + """ + Escape the binary message using the process described in the GDB server + protocol documentation. + + Most bytes are sent through as-is, but $, #, and { are escaped by writing + a { followed by the original byte mod 0x20. + """ + out = "" + for c in message: + d = ord(c) + if d in (0x23, 0x24, 0x7d): + out += chr(0x7d) + out += chr(d ^ 0x20) + else: + out += c + return out + + +def hex_encode_bytes(message): + """ + Encode the binary message by converting each byte into a two-character + hex string. + """ + out = "" + for c in message: + out += "%02x" % ord(c) + return out + + +def hex_decode_bytes(hex_bytes): + """ + Decode the hex string into a binary message by converting each two-character + hex string into a single output byte. + """ + out = "" + hex_len = len(hex_bytes) + while i < hex_len - 1: + out += chr(int(hex_bytes[i:i + 2]), 16) + i += 2 + return out + + +class MockGDBServerResponder: + """ + A base class for handling client packets and issuing server responses for + GDB tests. + + This handles many typical situations, while still allowing subclasses to + completely customize their responses. + + Most subclasses will be interested in overriding the other() method, which + handles any packet not recognized in the common packet handling code. + """ + + registerCount = 40 + packetLog = None + + def __init__(self): + self.packetLog = [] + + def respond(self, packet): + """ + Return the unframed packet data that the server should issue in response + to the given packet received from the client. + """ + self.packetLog.append(packet) + if packet is MockGDBServer.PACKET_INTERRUPT: + return self.interrupt() + if packet == "c": + return self.cont() + if packet.startswith("vCont;c"): + return self.vCont(packet) + if packet[0] == "g": + return self.readRegisters() + if packet[0] == "G": + # Gxxxxxxxxxxx + # Gxxxxxxxxxxx;thread:1234; + return self.writeRegisters(packet[1:].split(';')[0]) + if packet[0] == "p": + regnum = packet[1:].split(';')[0] + return self.readRegister(int(regnum, 16)) + if packet[0] == "P": + register, value = packet[1:].split("=") + return self.writeRegister(int(register, 16), value) + if packet[0] == "m": + addr, length = [int(x, 16) for x in packet[1:].split(',')] + return self.readMemory(addr, length) + if packet[0] == "M": + location, encoded_data = packet[1:].split(":") + addr, length = [int(x, 16) for x in location.split(',')] + return self.writeMemory(addr, encoded_data) + if packet[0:7] == "qSymbol": + return self.qSymbol(packet[8:]) + if packet[0:10] == "qSupported": + return self.qSupported(packet[11:].split(";")) + if packet == "qfThreadInfo": + return self.qfThreadInfo() + if packet == "qsThreadInfo": + return self.qsThreadInfo() + if packet == "qC": + return self.qC() + if packet == "QEnableErrorStrings": + return self.QEnableErrorStrings() + if packet == "?": + return self.haltReason() + if packet == "s": + return self.haltReason() + if packet[0] == "H": + return self.selectThread(packet[1], int(packet[2:], 16)) + if packet[0:6] == "qXfer:": + obj, read, annex, location = packet[6:].split(":") + offset, length = [int(x, 16) for x in location.split(',')] + data, has_more = self.qXferRead(obj, annex, offset, length) + if data is not None: + return self._qXferResponse(data, has_more) + return "" + if packet.startswith("vAttach;"): + pid = packet.partition(';')[2] + return self.vAttach(int(pid, 16)) + if packet[0] == "Z": + return self.setBreakpoint(packet) + if packet.startswith("qThreadStopInfo"): + threadnum = int (packet[15:], 16) + return self.threadStopInfo(threadnum) + if packet == "QThreadSuffixSupported": + return self.QThreadSuffixSupported() + if packet == "QListThreadsInStopReply": + return self.QListThreadsInStopReply() + if packet.startswith("qMemoryRegionInfo:"): + return self.qMemoryRegionInfo() + if packet == "qQueryGDBServer": + return self.qQueryGDBServer() + if packet == "qHostInfo": + return self.qHostInfo() + if packet == "qGetWorkingDir": + return self.qGetWorkingDir() + if packet == "qsProcessInfo": + return self.qsProcessInfo() + if packet.startswith("qfProcessInfo"): + return self.qfProcessInfo(packet) + + return self.other(packet) + + def qsProcessInfo(self): + return "E04" + + def qfProcessInfo(self, packet): + return "E04" + + def qGetWorkingDir(self): + return "2f" + + def qHostInfo(self): + return "ptrsize:8;endian:little;" + + def qQueryGDBServer(self): + return "E04" + + def interrupt(self): + raise self.UnexpectedPacketException() + + def cont(self): + raise self.UnexpectedPacketException() + + def vCont(self, packet): + raise self.UnexpectedPacketException() + + def readRegisters(self): + return "00000000" * self.registerCount + + def readRegister(self, register): + return "00000000" + + def writeRegisters(self, registers_hex): + return "OK" + + def writeRegister(self, register, value_hex): + return "OK" + + def readMemory(self, addr, length): + return "00" * length + + def writeMemory(self, addr, data_hex): + return "OK" + + def qSymbol(self, symbol_args): + return "OK" + + def qSupported(self, client_supported): + return "qXfer:features:read+;PacketSize=3fff;QStartNoAckMode+" + + def qfThreadInfo(self): + return "l" + + def qsThreadInfo(self): + return "l" + + def qC(self): + return "QC0" + + def QEnableErrorStrings(self): + return "OK" + + def haltReason(self): + # SIGINT is 2, return type is 2 digit hex string + return "S02" + + def qXferRead(self, obj, annex, offset, length): + return None, False + + def _qXferResponse(self, data, has_more): + return "%s%s" % ("m" if has_more else "l", escape_binary(data)) + + def vAttach(self, pid): + raise self.UnexpectedPacketException() + + def selectThread(self, op, thread_id): + return "OK" + + def setBreakpoint(self, packet): + raise self.UnexpectedPacketException() + + def threadStopInfo(self, threadnum): + return "" + + def other(self, packet): + # empty string means unsupported + return "" + + def QThreadSuffixSupported(self): + return "" + + def QListThreadsInStopReply(self): + return "" + + def qMemoryRegionInfo(self): + return "" + + """ + Raised when we receive a packet for which there is no default action. + Override the responder class to implement behavior suitable for the test at + hand. + """ + class UnexpectedPacketException(Exception): + pass + + +class MockGDBServer: + """ + A simple TCP-based GDB server that can test client behavior by receiving + commands and issuing custom-tailored responses. + + Responses are generated via the .responder property, which should be an + instance of a class based on MockGDBServerResponder. + """ + + responder = None + port = 0 + _socket = None + _client = None + _thread = None + _receivedData = None + _receivedDataOffset = None + _shouldSendAck = True + + def __init__(self, port = 0): + self.responder = MockGDBServerResponder() + self.port = port + self._socket = socket.socket() + + def start(self): + # Block until the socket is up, so self.port is available immediately. + # Then start a thread that waits for a client connection. + addr = ("127.0.0.1", self.port) + self._socket.bind(addr) + self.port = self._socket.getsockname()[1] + self._socket.listen(1) + self._thread = threading.Thread(target=self._run) + self._thread.start() + + def stop(self): + self._socket.close() + self._thread.join() + self._thread = None + + def _run(self): + # For testing purposes, we only need to worry about one client + # connecting just one time. + try: + # accept() is stubborn and won't fail even when the socket is + # shutdown, so we'll use a timeout + self._socket.settimeout(20.0) + client, client_addr = self._socket.accept() + self._client = client + # The connected client inherits its timeout from self._socket, + # but we'll use a blocking socket for the client + self._client.settimeout(None) + except: + return + self._shouldSendAck = True + self._receivedData = "" + self._receivedDataOffset = 0 + data = None + while True: + try: + data = seven.bitcast_to_string(self._client.recv(4096)) + if data is None or len(data) == 0: + break + self._receive(data) + except Exception as e: + print("An exception happened when receiving the response from the gdb server. Closing the client...") + traceback.print_exc() + self._client.close() + break + + def _receive(self, data): + """ + Collects data, parses and responds to as many packets as exist. + Any leftover data is kept for parsing the next time around. + """ + self._receivedData += data + try: + packet = self._parsePacket() + while packet is not None: + self._handlePacket(packet) + packet = self._parsePacket() + except self.InvalidPacketException: + self._client.close() + + def _parsePacket(self): + """ + Reads bytes from self._receivedData, returning: + - a packet's contents if a valid packet is found + - the PACKET_ACK unique object if we got an ack + - None if we only have a partial packet + + Raises an InvalidPacketException if unexpected data is received + or if checksums fail. + + Once a complete packet is found at the front of self._receivedData, + its data is removed form self._receivedData. + """ + data = self._receivedData + i = self._receivedDataOffset + data_len = len(data) + if data_len == 0: + return None + if i == 0: + # If we're looking at the start of the received data, that means + # we're looking for the start of a new packet, denoted by a $. + # It's also possible we'll see an ACK here, denoted by a + + if data[0] == '+': + self._receivedData = data[1:] + return self.PACKET_ACK + if ord(data[0]) == 3: + self._receivedData = data[1:] + return self.PACKET_INTERRUPT + if data[0] == '$': + i += 1 + else: + raise self.InvalidPacketException( + "Unexpected leading byte: %s" % data[0]) + + # If we're looking beyond the start of the received data, then we're + # looking for the end of the packet content, denoted by a #. + # Note that we pick up searching from where we left off last time + while i < data_len and data[i] != '#': + i += 1 + + # If there isn't enough data left for a checksum, just remember where + # we left off so we can pick up there the next time around + if i > data_len - 3: + self._receivedDataOffset = i + return None + + # If we have enough data remaining for the checksum, extract it and + # compare to the packet contents + packet = data[1:i] + i += 1 + try: + check = int(data[i:i + 2], 16) + except ValueError: + raise self.InvalidPacketException("Checksum is not valid hex") + i += 2 + if check != checksum(packet): + raise self.InvalidPacketException( + "Checksum %02x does not match content %02x" % + (check, checksum(packet))) + # remove parsed bytes from _receivedData and reset offset so parsing + # can start on the next packet the next time around + self._receivedData = data[i:] + self._receivedDataOffset = 0 + return packet + + def _handlePacket(self, packet): + if packet is self.PACKET_ACK: + # Ignore ACKs from the client. For the future, we can consider + # adding validation code to make sure the client only sends ACKs + # when it's supposed to. + return + response = "" + # We'll handle the ack stuff here since it's not something any of the + # tests will be concerned about, and it'll get turned off quickly anyway. + if self._shouldSendAck: + self._client.sendall(seven.bitcast_to_bytes('+')) + if packet == "QStartNoAckMode": + self._shouldSendAck = False + response = "OK" + elif self.responder is not None: + # Delegate everything else to our responder + response = self.responder.respond(packet) + # Handle packet framing since we don't want to bother tests with it. + if response is not None: + framed = frame_packet(response) + self._client.sendall(seven.bitcast_to_bytes(framed)) + + PACKET_ACK = object() + PACKET_INTERRUPT = object() + + class InvalidPacketException(Exception): + pass + +class GDBRemoteTestBase(TestBase): + """ + Base class for GDB client tests. + + This class will setup and start a mock GDB server for the test to use. + It also provides assertPacketLogContains, which simplifies the checking + of packets sent by the client. + """ + + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + server = None + + def setUp(self): + TestBase.setUp(self) + self.server = MockGDBServer() + self.server.start() + + def tearDown(self): + # TestBase.tearDown will kill the process, but we need to kill it early + # so its client connection closes and we can stop the server before + # finally calling the base tearDown. + if self.process() is not None: + self.process().Kill() + self.server.stop() + TestBase.tearDown(self) + + def createTarget(self, yaml_path): + """ + Create a target by auto-generating the object based on the given yaml + instructions. + + This will track the generated object so it can be automatically removed + during tearDown. + """ + yaml_base, ext = os.path.splitext(yaml_path) + obj_path = self.getBuildArtifact(yaml_base) + self.yaml2obj(yaml_path, obj_path) + return self.dbg.CreateTarget(obj_path) + + def connect(self, target): + """ + Create a process by connecting to the mock GDB server. + + Includes assertions that the process was successfully created. + """ + listener = self.dbg.GetListener() + error = lldb.SBError() + url = "connect://localhost:%d" % self.server.port + process = target.ConnectRemote(listener, url, "gdb-remote", error) + self.assertTrue(error.Success(), error.description) + self.assertTrue(process, PROCESS_IS_VALID) + return process + + def assertPacketLogContains(self, packets): + """ + Assert that the mock server's packet log contains the given packets. + + The packet log includes all packets sent by the client and received + by the server. This fuction makes it easy to verify that the client + sent the expected packets to the server. + + The check does not require that the packets be consecutive, but does + require that they are ordered in the log as they ordered in the arg. + """ + i = 0 + j = 0 + log = self.server.responder.packetLog + + while i < len(packets) and j < len(log): + if log[j] == packets[i]: + i += 1 + j += 1 + if i < len(packets): + self.fail(u"Did not receive: %s\nLast 10 packets:\n\t%s" % + (packets[i], u'\n\t'.join(log))) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/operating_system.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/operating_system.py new file mode 100644 index 00000000000..83180c51492 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/operating_system.py @@ -0,0 +1,44 @@ +import lldb + + +class OperatingSystemPlugIn(object): + """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class""" + + def __init__(self, process): + '''Initialization needs a valid.SBProcess object. + + This plug-in will get created after a live process is valid and has stopped for the first time. + ''' + self.process = None + self.registers = None + self.threads = None + if isinstance(process, lldb.SBProcess) and process.IsValid(): + self.process = process + self.threads = None # Will be an dictionary containing info for each thread + + def get_target(self): + return self.process.target + + def get_thread_info(self): + if not self.threads: + self.threads = [{ + 'tid': 0x1, + 'name': 'one', + 'queue': 'queue1', + 'state': 'stopped', + 'stop_reason': 'none' + }, { + 'tid': 0x2, + 'name': 'two', + 'queue': 'queue2', + 'state': 'stopped', + 'stop_reason': 'none' + }, { + 'tid': 0x3, + 'name': 'three', + 'queue': 'queue3', + 'state': 'stopped', + 'stop_reason': 'sigstop', + 'core': 0 + }] + return self.threads diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/operating_system_2.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/operating_system_2.py new file mode 100644 index 00000000000..91b2ffeecb3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/gdb_remote_client/operating_system_2.py @@ -0,0 +1,61 @@ +import lldb + + +class OperatingSystemPlugIn(object): + """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class + This version stops once with threads 0x111 and 0x222, then stops a second time with threads + 0x111 and 0x333.""" + + def __init__(self, process): + '''Initialization needs a valid.SBProcess object. + + This plug-in will get created after a live process is valid and has stopped for the first time. + ''' + self.process = None + self.registers = None + self.threads = None + self.times_called = 0 + if isinstance(process, lldb.SBProcess) and process.IsValid(): + self.process = process + self.threads = None # Will be an dictionary containing info for each thread + + def get_target(self): + return self.process.target + + def get_thread_info(self): + self.times_called += 1 + + if self.times_called == 1: + self.threads = [{ + 'tid': 0x111, + 'name': 'one', + 'queue': 'queue1', + 'state': 'stopped', + 'stop_reason': 'none', + 'core': 1 + }, { + 'tid': 0x222, + 'name': 'two', + 'queue': 'queue2', + 'state': 'stopped', + 'stop_reason': 'none', + 'core': 0 + }] + else: + self.threads = [{ + 'tid': 0x111, + 'name': 'one', + 'queue': 'queue1', + 'state': 'stopped', + 'stop_reason': 'none', + 'core': 1 + }, { + 'tid': 0x333, + 'name': 'three', + 'queue': 'queue3', + 'state': 'stopped', + 'stop_reason': 'none', + 'core': 0 + }] + return self.threads + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/history/TestHistoryRecall.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/history/TestHistoryRecall.py new file mode 100644 index 00000000000..557b4a4c082 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/history/TestHistoryRecall.py @@ -0,0 +1,37 @@ +""" +Make sure the !N and !-N commands work properly. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class TestHistoryRecall(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def test_history_recall(self): + """Test the !N and !-N functionality of the command interpreter.""" + self.sample_test() + + def sample_test(self): + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + interp.HandleCommand("command history", result, True) + interp.HandleCommand("platform list", result, True) + + interp.HandleCommand("!0", result, False) + self.assertTrue(result.Succeeded(), "!0 command did not work: %s"%(result.GetError())) + self.assertTrue("command history" in result.GetOutput(), "!0 didn't rerun command history") + + interp.HandleCommand("!-1", result, False) + self.assertTrue(result.Succeeded(), "!-1 command did not work: %s"%(result.GetError())) + self.assertTrue("host:" in result.GetOutput(), "!-1 didn't rerun platform list.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py new file mode 100644 index 00000000000..36fdc862294 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py @@ -0,0 +1,315 @@ +"""Test that lldb functions correctly after the inferior has asserted.""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test import lldbutil +from lldbsuite.test import lldbplatformutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class AssertingInferiorTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + bugnumber="llvm.org/pr25338") + @expectedFailureAll(bugnumber="llvm.org/pr26592", triple='^mips') + @expectedFailureNetBSD + def test_inferior_asserting(self): + """Test that lldb reliably catches the inferior asserting (command).""" + self.build() + self.inferior_asserting() + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAndroid( + api_levels=list( + range( + 16 + + 1))) # b.android.com/179836 + def test_inferior_asserting_register(self): + """Test that lldb reliably reads registers from the inferior after asserting (command).""" + self.build() + self.inferior_asserting_registers() + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=[ + "aarch64", + "arm"], + triple=no_match(".*-android"), + bugnumber="llvm.org/pr25338") + @expectedFailureAll(bugnumber="llvm.org/pr26592", triple='^mips') + @expectedFailureNetBSD + def test_inferior_asserting_disassemble(self): + """Test that lldb reliably disassembles frames after asserting (command).""" + self.build() + self.inferior_asserting_disassemble() + + @add_test_categories(['pyapi']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + def test_inferior_asserting_python(self): + """Test that lldb reliably catches the inferior asserting (Python API).""" + self.build() + self.inferior_asserting_python() + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + triple=no_match(".*-android"), + bugnumber="llvm.org/pr25338") + @expectedFailureAll(bugnumber="llvm.org/pr26592", triple='^mips') + @expectedFailureNetBSD + def test_inferior_asserting_expr(self): + """Test that the lldb expression interpreter can read from the inferior after asserting (command).""" + self.build() + self.inferior_asserting_expr() + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows") + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + triple=no_match(".*-android"), + bugnumber="llvm.org/pr25338") + @expectedFailureAll(bugnumber="llvm.org/pr26592", triple='^mips') + @expectedFailureNetBSD + def test_inferior_asserting_step(self): + """Test that lldb functions correctly after stepping through a call to assert().""" + self.build() + self.inferior_asserting_step() + + def set_breakpoint(self, line): + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) + + def check_stop_reason(self): + matched = lldbplatformutil.match_android_device( + self.getArchitecture(), valid_api_levels=list(range(1, 16 + 1))) + if matched: + # On android until API-16 the abort() call ended in a sigsegv + # instead of in a sigabrt + stop_reason = 'stop reason = signal SIGSEGV' + else: + stop_reason = 'stop reason = signal SIGABRT' + + # The stop reason of the thread should be an abort signal or exception. + self.expect("thread list", STOPPED_DUE_TO_ASSERT, + substrs=['stopped', + stop_reason]) + + return stop_reason + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number of the call to assert. + self.line = line_number('main.c', '// Assert here.') + + def inferior_asserting(self): + """Inferior asserts upon launching; lldb should catch the event and stop.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + stop_reason = self.check_stop_reason() + + # And it should report a backtrace that includes the assert site. + self.expect("thread backtrace all", + substrs=[stop_reason, 'main', 'argc', 'argv']) + + # And it should report the correct line number. + self.expect("thread backtrace all", + substrs=[stop_reason, + 'main.c:%d' % self.line]) + + def inferior_asserting_python(self): + """Inferior asserts upon launching; lldb should catch the event and stop.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now launch the process, and do not stop at entry point. + # Both argv and envp are null. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal) + if not thread: + self.fail("Fail to stop the thread upon assert") + + if self.TraceOn(): + lldbutil.print_stacktrace(thread) + + def inferior_asserting_registers(self): + """Test that lldb can read registers after asserting.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + # lldb should be able to read from registers from the inferior after + # asserting. + lldbplatformutil.check_first_register_readable(self) + + def inferior_asserting_disassemble(self): + """Test that lldb can disassemble frames after asserting.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Launch the process, and do not stop at the entry point. + target.LaunchSimple(None, None, self.get_process_working_directory()) + self.check_stop_reason() + + process = target.GetProcess() + self.assertTrue(process.IsValid(), "current process is valid") + + thread = process.GetThreadAtIndex(0) + self.assertTrue(thread.IsValid(), "current thread is valid") + + lastframeID = thread.GetFrameAtIndex( + thread.GetNumFrames() - 1).GetFrameID() + + isi386Arch = False + if "i386" in self.getArchitecture(): + isi386Arch = True + + # lldb should be able to disassemble frames from the inferior after + # asserting. + for frame in thread: + self.assertTrue(frame.IsValid(), "current frame is valid") + + self.runCmd("frame select " + + str(frame.GetFrameID()), RUN_SUCCEEDED) + + # Don't expect the function name to be in the disassembly as the assert + # function might be a no-return function where the PC is past the end + # of the function and in the next function. We also can't back the PC up + # because we don't know how much to back it up by on targets with opcodes + # that have differing sizes + pc_backup_offset = 1 + if frame.GetFrameID() == 0: + pc_backup_offset = 0 + if isi386Arch: + if lastframeID == frame.GetFrameID(): + pc_backup_offset = 0 + self.expect( + "disassemble -a %s" % + (frame.GetPC() - + pc_backup_offset), + substrs=['<+0>: ']) + + def check_expr_in_main(self, thread): + depth = thread.GetNumFrames() + for i in range(depth): + frame = thread.GetFrameAtIndex(i) + self.assertTrue(frame.IsValid(), "current frame is valid") + if self.TraceOn(): + print( + "Checking if function %s is main" % + frame.GetFunctionName()) + + if 'main' == frame.GetFunctionName(): + frame_id = frame.GetFrameID() + self.runCmd("frame select " + str(frame_id), RUN_SUCCEEDED) + self.expect("p argc", substrs=['(int)', ' = 1']) + self.expect("p hello_world", substrs=['Hello']) + self.expect("p argv[0]", substrs=['a.out']) + self.expect("p null_ptr", substrs=['= 0x0']) + return True + return False + + def inferior_asserting_expr(self): + """Test that the lldb expression interpreter can read symbols after asserting.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Launch the process, and do not stop at the entry point. + target.LaunchSimple(None, None, self.get_process_working_directory()) + self.check_stop_reason() + + process = target.GetProcess() + self.assertTrue(process.IsValid(), "current process is valid") + + thread = process.GetThreadAtIndex(0) + self.assertTrue(thread.IsValid(), "current thread is valid") + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a call to assert(). + self.assertTrue( + self.check_expr_in_main(thread), + "cannot find 'main' in the backtrace") + + def inferior_asserting_step(self): + """Test that lldb functions correctly after stepping through a call to assert().""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Launch the process, and do not stop at the entry point. + self.set_breakpoint(self.line) + target.LaunchSimple(None, None, self.get_process_working_directory()) + + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['main.c:%d' % self.line, + 'stop reason = breakpoint']) + + self.runCmd("next") + stop_reason = self.check_stop_reason() + + # lldb should be able to read from registers from the inferior after + # asserting. + if "x86_64" in self.getArchitecture(): + self.expect("register read rbp", substrs=['rbp = 0x']) + if "i386" in self.getArchitecture(): + self.expect("register read ebp", substrs=['ebp = 0x']) + + process = target.GetProcess() + self.assertTrue(process.IsValid(), "current process is valid") + + thread = process.GetThreadAtIndex(0) + self.assertTrue(thread.IsValid(), "current thread is valid") + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a call to assert(). + self.assertTrue( + self.check_expr_in_main(thread), + "cannot find 'main' in the backtrace") + + # And it should report the correct line number. + self.expect("thread backtrace all", + substrs=[stop_reason, + 'main.c:%d' % self.line]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/main.c new file mode 100644 index 00000000000..ad2ca563424 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-assert/main.c @@ -0,0 +1,18 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <assert.h> + +const char *hello_world = "Hello, assertion!"; + +int main(int argc, const char* argv[]) +{ + int *null_ptr = 0; + printf("%s\n", hello_world); + assert(null_ptr); // Assert here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py new file mode 100644 index 00000000000..95cdfb5591f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py @@ -0,0 +1,82 @@ +"""Test lldb reloads the inferior after it was changed during the session.""" + + + +import time +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import configuration +from lldbsuite.test import lldbutil + + +class ChangedInferiorTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(hostoslist=["windows"]) + @no_debug_info_test + def test_inferior_crashing(self): + """Test lldb reloads the inferior after it was changed during the session.""" + self.build() + self.inferior_crashing() + self.cleanup() + # lldb needs to recognize the inferior has changed. If lldb needs to check the + # new module timestamp, make sure it is not the same as the old one, so add a + # 1 second delay. + time.sleep(1) + d = {'C_SOURCES': 'main2.c'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.inferior_not_crashing() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number of the crash. + self.line1 = line_number('main.c', '// Crash here.') + self.line2 = line_number('main2.c', '// Not crash here.') + + def inferior_crashing(self): + """Inferior crashes upon launching; lldb should catch the event and stop.""" + self.exe = self.getBuildArtifact("a.out") + self.runCmd("file " + self.exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + + # We should have one crashing thread + self.assertEqual( + len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), + 1, + STOPPED_DUE_TO_EXC_BAD_ACCESS) + + # And it should report the correct line number. + self.expect("thread backtrace all", substrs=['main.c:%d' % self.line1]) + + def inferior_not_crashing(self): + """Test lldb reloads the inferior after it was changed during the session.""" + self.runCmd("process kill") + self.runCmd("run", RUN_SUCCEEDED) + self.runCmd("process status") + + self.assertNotEqual( + len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), + 1, + "Inferior changed, but lldb did not perform a reload") + + # Break inside the main. + lldbutil.run_break_set_by_file_and_line( + self, "main2.c", self.line2, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.runCmd("frame variable int_ptr") + self.expect("frame variable *int_ptr", + substrs=['= 7']) + self.expect("expression *int_ptr", + substrs=['= 7']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/main.c new file mode 100644 index 00000000000..ec4824ad4ad --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/main.c @@ -0,0 +1,15 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int main(int argc, const char* argv[]) +{ + int *null_ptr = 0; + printf("Hello, segfault!\n"); + printf("Now crash %d\n", *null_ptr); // Crash here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/main2.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/main2.c new file mode 100644 index 00000000000..a3c68f0f03d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-changed/main2.c @@ -0,0 +1,17 @@ +//===-- main2.c -------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdlib.h> + +int main(int argc, const char* argv[]) +{ + int *int_ptr = (int *)malloc(sizeof(int)); + *int_ptr = 7; + printf("Hello, world!\n"); + printf("Now not crash %d\n", *int_ptr); // Not crash here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py new file mode 100644 index 00000000000..ee17ecc32ea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py @@ -0,0 +1,134 @@ +"""Test that lldb functions correctly after the inferior has crashed.""" + + + +import lldb +from lldbsuite.test import lldbutil +from lldbsuite.test import lldbplatformutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class CrashingInferiorTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + @expectedFailureNetBSD + def test_inferior_crashing(self): + """Test that lldb reliably catches the inferior crashing (command).""" + self.build() + self.inferior_crashing() + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_inferior_crashing_register(self): + """Test that lldb reliably reads registers from the inferior after crashing (command).""" + self.build() + self.inferior_crashing_registers() + + @add_test_categories(['pyapi']) + def test_inferior_crashing_python(self): + """Test that lldb reliably catches the inferior crashing (Python API).""" + self.build() + self.inferior_crashing_python() + + def test_inferior_crashing_expr(self): + """Test that the lldb expression interpreter can read from the inferior after crashing (command).""" + self.build() + self.inferior_crashing_expr() + + def set_breakpoint(self, line): + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) + + def check_stop_reason(self): + # We should have one crashing thread + self.assertEqual( + len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), + 1, + STOPPED_DUE_TO_EXC_BAD_ACCESS) + + def get_api_stop_reason(self): + return lldb.eStopReasonException + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number of the crash. + self.line = line_number('main.c', '// Crash here.') + + def inferior_crashing(self): + """Inferior crashes upon launching; lldb should catch the event and stop.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + # The exact stop reason depends on the platform + if self.platformIsDarwin(): + stop_reason = 'stop reason = EXC_BAD_ACCESS' + elif self.getPlatform() == "linux" or self.getPlatform() == "freebsd": + stop_reason = 'stop reason = signal SIGSEGV' + else: + stop_reason = 'stop reason = invalid address' + self.expect("thread list", STOPPED_DUE_TO_EXC_BAD_ACCESS, + substrs=['stopped', + stop_reason]) + + # And it should report the correct line number. + self.expect("thread backtrace all", + substrs=[stop_reason, + 'main.c:%d' % self.line]) + + def inferior_crashing_python(self): + """Inferior crashes upon launching; lldb should catch the event and stop.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now launch the process, and do not stop at entry point. + # Both argv and envp are null. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + threads = lldbutil.get_crashed_threads(self, process) + self.assertEqual( + len(threads), + 1, + "Failed to stop the thread upon bad access exception") + + if self.TraceOn(): + lldbutil.print_stacktrace(threads[0]) + + def inferior_crashing_registers(self): + """Test that lldb can read registers after crashing.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + # lldb should be able to read from registers from the inferior after + # crashing. + lldbplatformutil.check_first_register_readable(self) + + def inferior_crashing_expr(self): + """Test that the lldb expression interpreter can read symbols after crashing.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. + self.expect("p argc", + startstr='(int) $0 = 1') + + self.expect("p hello_world", + substrs=['Hello']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashingStep.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashingStep.py new file mode 100644 index 00000000000..afb8c2370b3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashingStep.py @@ -0,0 +1,228 @@ +"""Test that lldb steps correctly after the inferior has crashed.""" + + +import lldb +from lldbsuite.test import lldbutil +from lldbsuite.test import lldbplatformutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class CrashingInferiorStepTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + @expectedFailureNetBSD + def test_inferior_crashing(self): + """Test that lldb reliably catches the inferior crashing (command).""" + self.build() + self.inferior_crashing() + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_inferior_crashing_register(self): + """Test that lldb reliably reads registers from the inferior after crashing (command).""" + self.build() + self.inferior_crashing_registers() + + @add_test_categories(['pyapi']) + def test_inferior_crashing_python(self): + """Test that lldb reliably catches the inferior crashing (Python API).""" + self.build() + self.inferior_crashing_python() + + def test_inferior_crashing_expr(self): + """Test that the lldb expression interpreter can read from the inferior after crashing (command).""" + self.build() + self.inferior_crashing_expr() + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_inferior_crashing_step(self): + """Test that stepping after a crash behaves correctly.""" + self.build() + self.inferior_crashing_step() + + @skipIfTargetAndroid() # debuggerd interferes with this test on Android + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_inferior_crashing_step_after_break(self): + """Test that lldb functions correctly after stepping through a crash.""" + self.build() + self.inferior_crashing_step_after_break() + + # Inferior exits after stepping after a segfault. This is working as + # intended IMHO. + @skipIfLinux + @skipIfFreeBSD + @expectedFailureNetBSD + def test_inferior_crashing_expr_step_and_expr(self): + """Test that lldb expressions work before and after stepping after a crash.""" + self.build() + self.inferior_crashing_expr_step_expr() + + def set_breakpoint(self, line): + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) + + def check_stop_reason(self): + # We should have one crashing thread + self.assertEqual( + len( + lldbutil.get_crashed_threads( + self, + self.dbg.GetSelectedTarget().GetProcess())), 1, + STOPPED_DUE_TO_EXC_BAD_ACCESS) + + def get_api_stop_reason(self): + return lldb.eStopReasonException + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number of the crash. + self.line = line_number('main.c', '// Crash here.') + + def inferior_crashing(self): + """Inferior crashes upon launching; lldb should catch the event and stop.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + # The exact stop reason depends on the platform + if self.platformIsDarwin(): + stop_reason = 'stop reason = EXC_BAD_ACCESS' + elif self.getPlatform() == "linux" or self.getPlatform() == "freebsd": + stop_reason = 'stop reason = signal SIGSEGV' + else: + stop_reason = 'stop reason = invalid address' + self.expect( + "thread list", + STOPPED_DUE_TO_EXC_BAD_ACCESS, + substrs=['stopped', stop_reason]) + + # And it should report the correct line number. + self.expect( + "thread backtrace all", + substrs=[stop_reason, 'main.c:%d' % self.line]) + + def inferior_crashing_python(self): + """Inferior crashes upon launching; lldb should catch the event and stop.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now launch the process, and do not stop at entry point. + # Both argv and envp are null. + process = target.LaunchSimple(None, None, + self.get_process_working_directory()) + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + threads = lldbutil.get_crashed_threads(self, process) + self.assertEqual( + len(threads), 1, + "Failed to stop the thread upon bad access exception") + + if self.TraceOn(): + lldbutil.print_stacktrace(threads[0]) + + def inferior_crashing_registers(self): + """Test that lldb can read registers after crashing.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + # lldb should be able to read from registers from the inferior after + # crashing. + lldbplatformutil.check_first_register_readable(self) + + def inferior_crashing_expr(self): + """Test that the lldb expression interpreter can read symbols after crashing.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. + self.expect("p argc", startstr='(int) $0 = 1') + + self.expect("p hello_world", substrs=['Hello']) + + def inferior_crashing_step(self): + """Test that lldb functions correctly after stepping through a crash.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.set_breakpoint(self.line) + self.runCmd("run", RUN_SUCCEEDED) + + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['main.c:%d' % self.line, 'stop reason = breakpoint']) + + self.runCmd("next") + self.check_stop_reason() + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. + self.expect("p argv[0]", substrs=['a.out']) + self.expect("p null_ptr", substrs=['= 0x0']) + + # lldb should be able to read from registers from the inferior after + # crashing. + lldbplatformutil.check_first_register_readable(self) + + # And it should report the correct line number. + self.expect("thread backtrace all", substrs=['main.c:%d' % self.line]) + + @expectedFailureNetBSD + def inferior_crashing_step_after_break(self): + """Test that lldb behaves correctly when stepping after a crash.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + expected_state = 'exited' # Provide the exit code. + if self.platformIsDarwin(): + # TODO: Determine why 'next' and 'continue' have no effect after a + # crash. + expected_state = 'stopped' + + self.expect("next", substrs=['Process', expected_state]) + + if expected_state == 'exited': + self.expect( + "thread list", + error=True, + substrs=['Process must be launched']) + else: + self.check_stop_reason() + + def inferior_crashing_expr_step_expr(self): + """Test that lldb expressions work before and after stepping after a crash.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. + self.expect("p argv[0]", substrs=['a.out']) + + self.runCmd("next") + self.check_stop_reason() + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. + self.expect("p argv[0]", substrs=['a.out']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/main.c new file mode 100644 index 00000000000..3423ea42bee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/main.c @@ -0,0 +1,17 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +const char *hello_world = "Hello, segfault!"; + +int main(int argc, const char* argv[]) +{ + int *null_ptr = 0; + printf("%s\n", hello_world); + printf("Now crash %d\n", *null_ptr); // Crash here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/Makefile new file mode 100644 index 00000000000..eb07d2fbdf3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/Makefile @@ -0,0 +1,5 @@ +C_SOURCES := main.c + +CFLAGS_EXTRAS := -fomit-frame-pointer + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py new file mode 100644 index 00000000000..3044e5e2a76 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py @@ -0,0 +1,141 @@ +"""Test that lldb functions correctly after the inferior has crashed while in a recursive routine.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbplatformutil +from lldbsuite.test import lldbutil + + +class CrashingRecursiveInferiorTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + @expectedFailureNetBSD + def test_recursive_inferior_crashing(self): + """Test that lldb reliably catches the inferior crashing (command).""" + self.build() + self.recursive_inferior_crashing() + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_recursive_inferior_crashing_register(self): + """Test that lldb reliably reads registers from the inferior after crashing (command).""" + self.build() + self.recursive_inferior_crashing_registers() + + @add_test_categories(['pyapi']) + def test_recursive_inferior_crashing_python(self): + """Test that lldb reliably catches the inferior crashing (Python API).""" + self.build() + self.recursive_inferior_crashing_python() + + def test_recursive_inferior_crashing_expr(self): + """Test that the lldb expression interpreter can read from the inferior after crashing (command).""" + self.build() + self.recursive_inferior_crashing_expr() + + def set_breakpoint(self, line): + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) + + def check_stop_reason(self): + # We should have one crashing thread + self.assertEqual( + len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())), + 1, + STOPPED_DUE_TO_EXC_BAD_ACCESS) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number of the crash. + self.line = line_number('main.c', '// Crash here.') + + def recursive_inferior_crashing(self): + """Inferior crashes upon launching; lldb should catch the event and stop.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + + # The exact stop reason depends on the platform + if self.platformIsDarwin(): + stop_reason = 'stop reason = EXC_BAD_ACCESS' + elif self.getPlatform() == "linux" or self.getPlatform() == "freebsd": + stop_reason = 'stop reason = signal SIGSEGV' + else: + stop_reason = 'stop reason = invalid address' + self.expect("thread list", STOPPED_DUE_TO_EXC_BAD_ACCESS, + substrs=['stopped', + stop_reason]) + + # And it should report a backtrace that includes main and the crash + # site. + self.expect( + "thread backtrace all", + substrs=[ + stop_reason, + 'main', + 'argc', + 'argv', + 'recursive_function']) + + # And it should report the correct line number. + self.expect("thread backtrace all", + substrs=[stop_reason, + 'main.c:%d' % self.line]) + + def recursive_inferior_crashing_python(self): + """Inferior crashes upon launching; lldb should catch the event and stop.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now launch the process, and do not stop at entry point. + # Both argv and envp are null. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + threads = lldbutil.get_crashed_threads(self, process) + self.assertEqual( + len(threads), + 1, + "Failed to stop the thread upon bad access exception") + + if self.TraceOn(): + lldbutil.print_stacktrace(threads[0]) + + def recursive_inferior_crashing_registers(self): + """Test that lldb can read registers after crashing.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + # lldb should be able to read from registers from the inferior after + # crashing. + lldbplatformutil.check_first_register_readable(self) + + def recursive_inferior_crashing_expr(self): + """Test that the lldb expression interpreter can read symbols after crashing.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. + self.expect("p i", + startstr='(int) $0 =') + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferiorStep.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferiorStep.py new file mode 100644 index 00000000000..e63172f917b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferiorStep.py @@ -0,0 +1,126 @@ +"""Test that lldb steps correctly after the inferior has crashed while in a recursive routine.""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbplatformutil +from lldbsuite.test import lldbutil + + +class CrashingRecursiveInferiorStepTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_recursive_inferior_crashing_step(self): + """Test that stepping after a crash behaves correctly.""" + self.build() + self.recursive_inferior_crashing_step() + + @skipIfTargetAndroid() # debuggerd interferes with this test on Android + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_recursive_inferior_crashing_step_after_break(self): + """Test that lldb functions correctly after stepping through a crash.""" + self.build() + self.recursive_inferior_crashing_step_after_break() + + # Inferior exits after stepping after a segfault. This is working as + # intended IMHO. + @skipIfLinux + @skipIfFreeBSD + @expectedFailureNetBSD + def test_recursive_inferior_crashing_expr_step_and_expr(self): + """Test that lldb expressions work before and after stepping after a crash.""" + self.build() + self.recursive_inferior_crashing_expr_step_expr() + + def set_breakpoint(self, line): + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) + + def check_stop_reason(self): + # We should have one crashing thread + self.assertEqual( + len( + lldbutil.get_crashed_threads( + self, + self.dbg.GetSelectedTarget().GetProcess())), 1, + STOPPED_DUE_TO_EXC_BAD_ACCESS) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number of the crash. + self.line = line_number('main.c', '// Crash here.') + + def recursive_inferior_crashing_step(self): + """Test that lldb functions correctly after stepping through a crash.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.set_breakpoint(self.line) + self.runCmd("run", RUN_SUCCEEDED) + + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['main.c:%d' % self.line, 'stop reason = breakpoint']) + + self.runCmd("next") + self.check_stop_reason() + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. + self.expect("p i", substrs=['(int) $0 =']) + + # lldb should be able to read from registers from the inferior after + # crashing. + lldbplatformutil.check_first_register_readable(self) + + # And it should report the correct line number. + self.expect("thread backtrace all", substrs=['main.c:%d' % self.line]) + + def recursive_inferior_crashing_step_after_break(self): + """Test that lldb behaves correctly when stepping after a crash.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + expected_state = 'exited' # Provide the exit code. + if self.platformIsDarwin(): + # TODO: Determine why 'next' and 'continue' have no effect after a + # crash. + expected_state = 'stopped' + + self.expect("next", substrs=['Process', expected_state]) + + if expected_state == 'exited': + self.expect( + "thread list", + error=True, + substrs=['Process must be launched']) + else: + self.check_stop_reason() + + def recursive_inferior_crashing_expr_step_expr(self): + """Test that lldb expressions work before and after stepping after a crash.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("run", RUN_SUCCEEDED) + self.check_stop_reason() + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a crash. + self.expect("p null", startstr='(char *) $0 = 0x0') + + self.runCmd("next") + + # The lldb expression interpreter should be able to read from addresses + # of the inferior after a step. + self.expect("p null", startstr='(char *) $1 = 0x0') + + self.check_stop_reason() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/main.c new file mode 100644 index 00000000000..25e6e8df0b9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/main.c @@ -0,0 +1,19 @@ +void recursive_function(int i) +{ + if (i < 10) + { + recursive_function(i + 1); + } + else + { + char *null=0; + *null = 0; // Crash here. + } +} + +int main(int argc, char *argv[]) +{ + recursive_function(0); + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/Makefile new file mode 100644 index 00000000000..362b89d7f99 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/Makefile @@ -0,0 +1,8 @@ +CXX_SOURCES := calling.cpp + +ifneq (,$(findstring icc,$(CC))) + CXXFLAGS_EXTRAS := -debug inline-debug-info +endif + + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py new file mode 100644 index 00000000000..40e29e614ad --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py @@ -0,0 +1,330 @@ +"""Test stepping over and into inlined functions.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestInlineStepping(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + @expectedFailureAll( + compiler="icc", + bugnumber="# Not really a bug. ICC combines two inlined functions.") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr32343") + @expectedFailureAll(archs=["aarch64"], oslist=["linux"], + bugnumber="llvm.org/pr44057") + def test_with_python_api(self): + """Test stepping over and into inlined functions.""" + self.build() + self.inline_stepping() + + @add_test_categories(['pyapi']) + def test_step_over_with_python_api(self): + """Test stepping over and into inlined functions.""" + self.build() + self.inline_stepping_step_over() + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr32343") + def test_step_in_template_with_python_api(self): + """Test stepping in to templated functions.""" + self.build() + self.step_in_template() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers that we will step to in main: + self.main_source = "calling.cpp" + self.source_lines = {} + functions = [ + 'caller_ref_1', + 'caller_ref_2', + 'inline_ref_1', + 'inline_ref_2', + 'called_by_inline_ref', + 'caller_trivial_1', + 'caller_trivial_2', + 'inline_trivial_1', + 'inline_trivial_2', + 'called_by_inline_trivial'] + for name in functions: + self.source_lines[name] = line_number( + self.main_source, "// In " + name + ".") + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + def do_step(self, step_type, destination_line_entry, test_stack_depth): + expected_stack_depth = self.thread.GetNumFrames() + if step_type == "into": + expected_stack_depth += 1 + self.thread.StepInto() + elif step_type == "out": + expected_stack_depth -= 1 + self.thread.StepOut() + elif step_type == "over": + self.thread.StepOver() + else: + self.fail("Unrecognized step type: " + step_type) + + threads = lldbutil.get_stopped_threads( + self.process, lldb.eStopReasonPlanComplete) + if len(threads) != 1: + destination_description = lldb.SBStream() + destination_line_entry.GetDescription(destination_description) + self.fail( + "Failed to stop due to step " + + step_type + + " operation stepping to: " + + destination_description.GetData()) + + self.thread = threads[0] + + stop_line_entry = self.thread.GetFrameAtIndex(0).GetLineEntry() + self.assertTrue( + stop_line_entry.IsValid(), + "Stop line entry was not valid.") + + # Don't use the line entry equal operator because we don't care about + # the column number. + stop_at_right_place = (stop_line_entry.GetFileSpec() == destination_line_entry.GetFileSpec( + ) and stop_line_entry.GetLine() == destination_line_entry.GetLine()) + if not stop_at_right_place: + destination_description = lldb.SBStream() + destination_line_entry.GetDescription(destination_description) + + actual_description = lldb.SBStream() + stop_line_entry.GetDescription(actual_description) + + self.fail( + "Step " + + step_type + + " stopped at wrong place: expected: " + + destination_description.GetData() + + " got: " + + actual_description.GetData() + + ".") + + real_stack_depth = self.thread.GetNumFrames() + + if test_stack_depth and real_stack_depth != expected_stack_depth: + destination_description = lldb.SBStream() + destination_line_entry.GetDescription(destination_description) + self.fail( + "Step %s to %s got wrong number of frames, should be: %d was: %d." % + (step_type, + destination_description.GetData(), + expected_stack_depth, + real_stack_depth)) + + def run_step_sequence(self, step_sequence): + """This function takes a list of duples instructing how to run the program. The first element in each duple is + a source pattern for the target location, and the second is the operation that will take you from the current + source location to the target location. It will then run all the steps in the sequence. + It will check that you arrived at the expected source location at each step, and that the stack depth changed + correctly for the operation in the sequence.""" + + target_line_entry = lldb.SBLineEntry() + target_line_entry.SetFileSpec(self.main_source_spec) + + test_stack_depth = True + # Work around for <rdar://problem/16363195>, the darwin unwinder seems flakey about whether it duplicates the first frame + # or not, which makes counting stack depth unreliable. + if self.platformIsDarwin(): + test_stack_depth = False + + for step_pattern in step_sequence: + step_stop_line = line_number(self.main_source, step_pattern[0]) + target_line_entry.SetLine(step_stop_line) + self.do_step(step_pattern[1], target_line_entry, test_stack_depth) + + def inline_stepping(self): + """Use Python APIs to test stepping over and hitting breakpoints.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + break_1_in_main = target.BreakpointCreateBySourceRegex( + '// Stop here and step over to set up stepping over.', self.main_source_spec) + self.assertTrue(break_1_in_main, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + self.process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(self.process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, break_1_in_main) + + if len(threads) != 1: + self.fail("Failed to stop at first breakpoint in main.") + + self.thread = threads[0] + + # Step over the inline_value = 0 line to get us to inline_trivial_1 called from main. Doing it this way works + # around a bug in lldb where the breakpoint on the containing line of an inlined function with no return value + # gets set past the insertion line in the function. + # Then test stepping over a simple inlined function. Note, to test all the parts of the inlined stepping + # the calls inline_stepping_1 and inline_stepping_2 should line up at the same address, that way we will test + # the "virtual" stepping. + # FIXME: Put in a check to see if that is true and warn if it is not. + + step_sequence = [["// At inline_trivial_1 called from main.", "over"], + ["// At first call of caller_trivial_1 in main.", "over"]] + self.run_step_sequence(step_sequence) + + # Now step from caller_ref_1 all the way into called_by_inline_trivial + + step_sequence = [["// In caller_trivial_1.", "into"], + ["// In caller_trivial_2.", "into"], + ["// In inline_trivial_1.", "into"], + ["// In inline_trivial_2.", "into"], + ["// At caller_by_inline_trivial in inline_trivial_2.", "over"], + ["// In called_by_inline_trivial.", "into"]] + self.run_step_sequence(step_sequence) + + # Now run to the inline_trivial_1 just before the immediate step into + # inline_trivial_2: + + break_2_in_main = target.BreakpointCreateBySourceRegex( + '// At second call of caller_trivial_1 in main.', self.main_source_spec) + self.assertTrue(break_2_in_main, VALID_BREAKPOINT) + + threads = lldbutil.continue_to_breakpoint( + self.process, break_2_in_main) + self.assertTrue( + len(threads) == 1, + "Successfully ran to call site of second caller_trivial_1 call.") + self.thread = threads[0] + + step_sequence = [["// In caller_trivial_1.", "into"], + ["// In caller_trivial_2.", "into"], + ["// In inline_trivial_1.", "into"]] + self.run_step_sequence(step_sequence) + + # Then call some trivial function, and make sure we end up back where + # we were in the inlined call stack: + + frame = self.thread.GetFrameAtIndex(0) + before_line_entry = frame.GetLineEntry() + value = frame.EvaluateExpression("function_to_call()") + after_line_entry = frame.GetLineEntry() + + self.assertTrue( + before_line_entry.GetLine() == after_line_entry.GetLine(), + "Line entry before and after function calls are the same.") + + # Now make sure stepping OVER in the middle of the stack works, and + # then check finish from the inlined frame: + + step_sequence = [["// At increment in inline_trivial_1.", "over"], + ["// At increment in caller_trivial_2.", "out"]] + self.run_step_sequence(step_sequence) + + # Now run to the place in main just before the first call to + # caller_ref_1: + + break_3_in_main = target.BreakpointCreateBySourceRegex( + '// At first call of caller_ref_1 in main.', self.main_source_spec) + self.assertTrue(break_3_in_main, VALID_BREAKPOINT) + + threads = lldbutil.continue_to_breakpoint( + self.process, break_3_in_main) + self.assertTrue( + len(threads) == 1, + "Successfully ran to call site of first caller_ref_1 call.") + self.thread = threads[0] + + step_sequence = [["// In caller_ref_1.", "into"], + ["// In caller_ref_2.", "into"], + ["// In inline_ref_1.", "into"], + ["// In inline_ref_2.", "into"], + ["// In called_by_inline_ref.", "into"], + ["// In inline_ref_2.", "out"], + ["// In inline_ref_1.", "out"], + ["// At increment in inline_ref_1.", "over"], + ["// In caller_ref_2.", "out"], + ["// At increment in caller_ref_2.", "over"]] + self.run_step_sequence(step_sequence) + + def inline_stepping_step_over(self): + """Use Python APIs to test stepping over and hitting breakpoints.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + break_1_in_main = target.BreakpointCreateBySourceRegex( + '// At second call of caller_ref_1 in main.', self.main_source_spec) + self.assertTrue(break_1_in_main, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + self.process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(self.process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, break_1_in_main) + + if len(threads) != 1: + self.fail("Failed to stop at first breakpoint in main.") + + self.thread = threads[0] + + step_sequence = [["// In caller_ref_1.", "into"], + ["// In caller_ref_2.", "into"], + ["// At increment in caller_ref_2.", "over"]] + self.run_step_sequence(step_sequence) + + def step_in_template(self): + """Use Python APIs to test stepping in to templated functions.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + break_1_in_main = target.BreakpointCreateBySourceRegex( + '// Call max_value template', self.main_source_spec) + self.assertTrue(break_1_in_main, VALID_BREAKPOINT) + + break_2_in_main = target.BreakpointCreateBySourceRegex( + '// Call max_value specialized', self.main_source_spec) + self.assertTrue(break_2_in_main, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + self.process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(self.process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, break_1_in_main) + + if len(threads) != 1: + self.fail("Failed to stop at first breakpoint in main.") + + self.thread = threads[0] + + step_sequence = [["// In max_value template", "into"]] + self.run_step_sequence(step_sequence) + + threads = lldbutil.continue_to_breakpoint( + self.process, break_2_in_main) + self.assertEqual( + len(threads), + 1, + "Successfully ran to call site of second caller_trivial_1 call.") + self.thread = threads[0] + + step_sequence = [["// In max_value specialized", "into"]] + self.run_step_sequence(step_sequence) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/calling.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/calling.cpp new file mode 100644 index 00000000000..9982fbf4273 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/inline-stepping/calling.cpp @@ -0,0 +1,136 @@ +#include <algorithm> +#include <cstdio> +#include <string> + +inline int inline_ref_1 (int &value) __attribute__((always_inline)); +inline int inline_ref_2 (int &value) __attribute__((always_inline)); + +int caller_ref_1 (int &value); +int caller_ref_2 (int &value); + +int called_by_inline_ref (int &value); + +inline void inline_trivial_1 () __attribute__((always_inline)); +inline void inline_trivial_2 () __attribute__((always_inline)); + +void caller_trivial_1 (); +void caller_trivial_2 (); + +void called_by_inline_trivial (); + +static int inline_value; + +int +function_to_call () +{ + return inline_value; +} + +int +caller_ref_1 (int &value) +{ + int increment = caller_ref_2(value); // In caller_ref_1. + value += increment; // At increment in caller_ref_1. + return value; +} + +int +caller_ref_2 (int &value) +{ + int increment = inline_ref_1 (value); // In caller_ref_2. + value += increment; // At increment in caller_ref_2. + return value; +} + +int +called_by_inline_ref (int &value) +{ + value += 1; // In called_by_inline_ref. + return value; +} + +int +inline_ref_1 (int &value) +{ + int increment = inline_ref_2(value); // In inline_ref_1. + value += increment; // At increment in inline_ref_1. + return value; +} + +int +inline_ref_2 (int &value) +{ + int increment = called_by_inline_ref (value); // In inline_ref_2. + value += 1; // At increment in inline_ref_2. + return value; +} + +void +caller_trivial_1 () +{ + caller_trivial_2(); // In caller_trivial_1. + inline_value += 1; +} + +void +caller_trivial_2 () +{ + inline_trivial_1 (); // In caller_trivial_2. + inline_value += 1; // At increment in caller_trivial_2. +} + +void +called_by_inline_trivial () +{ + inline_value += 1; // In called_by_inline_trivial. +} + +void +inline_trivial_1 () +{ + inline_trivial_2(); // In inline_trivial_1. + inline_value += 1; // At increment in inline_trivial_1. +} + +void +inline_trivial_2 () +{ + inline_value += 1; // In inline_trivial_2. + called_by_inline_trivial (); // At caller_by_inline_trivial in inline_trivial_2. +} + +template<typename T> T +max_value(const T& lhs, const T& rhs) +{ + return std::max(lhs, rhs); // In max_value template +} + +template<> std::string +max_value(const std::string& lhs, const std::string& rhs) +{ + return (lhs.size() > rhs.size()) ? lhs : rhs; // In max_value specialized +} + +int +main (int argc, char **argv) +{ + + inline_value = 0; // Stop here and step over to set up stepping over. + + inline_trivial_1 (); // At inline_trivial_1 called from main. + + caller_trivial_1(); // At first call of caller_trivial_1 in main. + + caller_trivial_1(); // At second call of caller_trivial_1 in main. + + caller_ref_1 (argc); // At first call of caller_ref_1 in main. + + caller_ref_1 (argc); // At second call of caller_ref_1 in main. + + function_to_call (); // Make sure debug info for this function gets generated. + + max_value(123, 456); // Call max_value template + max_value(std::string("abc"), std::string("0022")); // Call max_value specialized + + return 0; // About to return from main. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/Makefile new file mode 100644 index 00000000000..357b1f83684 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/Makefile @@ -0,0 +1,9 @@ +C_SOURCES := main.c + +all: a.out simple + +include Makefile.rules + +simple: + $(MAKE) -f $(MAKEFILE_RULES) \ + C_SOURCES=simple.c EXE=simple diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py new file mode 100644 index 00000000000..4bd4150185c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py @@ -0,0 +1,118 @@ +"""Test for the JITLoaderGDB interface""" + + +import unittest2 +import os +import lldb +from lldbsuite.test import lldbutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + +file_index = 0 + +class JITLoaderGDBTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipTestIfFn( + lambda: "Skipped because the test crashes the test runner", + bugnumber="llvm.org/pr24702") + @unittest2.expectedFailure("llvm.org/pr24702") + def test_bogus_values(self): + """Test that we handle inferior misusing the GDB JIT interface""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # launch the process, do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The inferior will now pass bogus values over the interface. Make sure + # we don't crash. + + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), 0) + + def gen_log_file(self): + global file_index + ++file_index + logfile = os.path.join( + self.getBuildDir(), + "jitintgdb-" + self.getArchitecture() + "-" + + str(file_index) + ".txt") + + def cleanup(): + if os.path.exists(logfile): + os.unlink(logfile) + self.addTearDownHook(cleanup) + return logfile + + def test_jit_int_default(self): + self.expect("settings show plugin.jit-loader.gdb.enable", + substrs=["plugin.jit-loader.gdb.enable (enum) = default"]) + + @skipIfWindows # This test fails on Windows during C code build + def test_jit_int_on(self): + """Tests interface with 'enable' settings 'on'""" + self.build() + exe = self.getBuildArtifact("simple") + + logfile = self.gen_log_file() + self.runCmd("log enable -f %s lldb jit" % (logfile)) + self.runCmd("settings set plugin.jit-loader.gdb.enable on") + def cleanup(): + self.runCmd("log disable lldb") + self.runCmd("settings set plugin.jit-loader.gdb.enable default") + self.addTearDownHook(cleanup) + + # launch the process + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), 0) + + logcontent = "" + if os.path.exists(logfile): + logcontent = open(logfile).read() + self.assertIn( + "SetJITBreakpoint setting JIT breakpoint", logcontent) + + @skipIfWindows # This test fails on Windows during C code build + def test_jit_int_off(self): + """Tests interface with 'enable' settings 'off'""" + self.build() + exe = self.getBuildArtifact("simple") + + logfile = self.gen_log_file() + self.runCmd("log enable -f %s lldb jit" % (logfile)) + self.runCmd("settings set plugin.jit-loader.gdb.enable off") + def cleanup(): + self.runCmd("log disable lldb") + self.runCmd("settings set plugin.jit-loader.gdb.enable default") + self.addTearDownHook(cleanup) + + # launch the process + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), 0) + + if os.path.exists(logfile): + logcontent = open(logfile).read() + self.assertNotIn( + "SetJITBreakpoint setting JIT breakpoint", logcontent) + else: + self.assertTrue(false) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/main.c new file mode 100644 index 00000000000..6a8ec50e663 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/main.c @@ -0,0 +1,44 @@ +#include <inttypes.h> + +// GDB JIT interface +enum JITAction { JIT_NOACTION, JIT_REGISTER_FN, JIT_UNREGISTER_FN }; + +struct JITCodeEntry +{ + struct JITCodeEntry* next; + struct JITCodeEntry* prev; + const char *symfile_addr; + uint64_t symfile_size; +}; + +struct JITDescriptor +{ + uint32_t version; + uint32_t action_flag; + struct JITCodeEntry* relevant_entry; + struct JITCodeEntry* first_entry; +}; + +struct JITDescriptor __jit_debug_descriptor = { 1, JIT_NOACTION, 0, 0 }; + +void __jit_debug_register_code() +{ +} +// end GDB JIT interface + +struct JITCodeEntry entry; + +int main() +{ + // Create a code entry with a bogus size + entry.next = entry.prev = 0; + entry.symfile_addr = (char *)&entry; + entry.symfile_size = (uint64_t)47<<32; + + __jit_debug_descriptor.relevant_entry = __jit_debug_descriptor.first_entry = &entry; + __jit_debug_descriptor.action_flag = JIT_REGISTER_FN; + + __jit_debug_register_code(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/simple.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/simple.c new file mode 100644 index 00000000000..77b1a2ad812 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/simple.c @@ -0,0 +1,20 @@ +#include <inttypes.h> + +// GDB JIT interface stub +struct +{ + uint32_t version; + uint32_t action_flag; + void* relevant_entry; + void* first_entry; +} __jit_debug_descriptor = { 1, 0, 0, 0 }; + +void __jit_debug_register_code() +{ +} +// end GDB JIT interface stub + +int main() +{ + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/lazy-loading/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/lazy-loading/Makefile new file mode 100644 index 00000000000..3d0b98f13f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/lazy-loading/Makefile @@ -0,0 +1,2 @@ +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/lazy-loading/TestLazyLoading.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/lazy-loading/TestLazyLoading.py new file mode 100644 index 00000000000..dddd4dceb37 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/lazy-loading/TestLazyLoading.py @@ -0,0 +1,236 @@ +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +""" +This test ensures that we only create Clang AST nodes in our module AST +when we actually need them. + +All tests in this file behave like this: + 1. Use LLDB to do something (expression evaluation, breakpoint setting, etc.). + 2. Check that certain Clang AST nodes were not loaded during the previous + step. +""" + +class TestCase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + # Only build this test once. + self.build() + + # Clang declaration kind we are looking for. + class_decl_kind = "CXXRecordDecl" + # FIXME: This shouldn't be a CXXRecordDecl, but that's how we model + # structs in Clang. + struct_decl_kind = "CXXRecordDecl" + + # The decls we use in this program in the format that + # decl_in_line and decl_completed_in_line expect (which is a pair of + # node type and the unqualified declaration name. + struct_first_member_decl = [struct_decl_kind, "StructFirstMember"] + struct_behind_ptr_decl = [struct_decl_kind, "StructBehindPointer"] + struct_behind_ref_decl = [struct_decl_kind, "StructBehindRef"] + struct_member_decl = [struct_decl_kind, "StructMember"] + some_struct_decl = [struct_decl_kind, "SomeStruct"] + other_struct_decl = [struct_decl_kind, "OtherStruct"] + class_in_namespace_decl = [class_decl_kind, "ClassInNamespace"] + class_we_enter_decl = [class_decl_kind, "ClassWeEnter"] + class_member_decl = [struct_decl_kind, "ClassMember"] + unused_class_member_decl = [struct_decl_kind, "UnusedClassMember"] + unused_class_member_ptr_decl = [struct_decl_kind, "UnusedClassMemberPtr"] + + def assert_no_decls_loaded(self): + """ + Asserts that no known declarations in this test are loaded + into the module's AST. + """ + self.assert_decl_not_loaded(self.struct_first_member_decl) + self.assert_decl_not_loaded(self.struct_behind_ptr_decl) + self.assert_decl_not_loaded(self.struct_behind_ref_decl) + self.assert_decl_not_loaded(self.struct_member_decl) + self.assert_decl_not_loaded(self.some_struct_decl) + self.assert_decl_not_loaded(self.other_struct_decl) + self.assert_decl_not_loaded(self.class_in_namespace_decl) + self.assert_decl_not_loaded(self.class_member_decl) + self.assert_decl_not_loaded(self.unused_class_member_decl) + + def get_ast_dump(self): + """Returns the dumped Clang AST of the module as a string""" + res = lldb.SBCommandReturnObject() + ci = self.dbg.GetCommandInterpreter() + ci.HandleCommand('target modules dump ast a.out', res) + self.assertTrue(res.Succeeded()) + return res.GetOutput() + + def decl_in_line(self, line, decl): + """ + Returns true iff the given line declares the given Clang decl. + The line is expected to be in the form of Clang's AST dump. + """ + line = line.rstrip() + "\n" + decl_kind = "-" + decl[0] + " " + # Either the decl is somewhere in the line or at the end of + # the line. + decl_name = " " + decl[1] + " " + decl_name_eol = " " + decl[1] + "\n" + if not decl_kind in line: + return False + return decl_name in line or decl_name_eol in line + + def decl_completed_in_line(self, line, decl): + """ + Returns true iff the given line declares the given Clang decl and + the decl was completed (i.e., it has no undeserialized declarations + in it). + """ + return self.decl_in_line(line, decl) and not "<undeserialized declarations>" in line + + # The following asserts are used for checking if certain Clang declarations + # were loaded or not since the target was created. + + def assert_decl_loaded(self, decl): + """ + Asserts the given decl is currently loaded. + Note: This test is about checking that types/declarations are not + loaded. If this assert fails it is usually fine to turn it into a + assert_decl_not_loaded or assert_decl_not_completed assuming LLDB's + functionality has not suffered by not loading this declaration. + """ + ast = self.get_ast_dump() + found = False + for line in ast.splitlines(): + if self.decl_in_line(line, decl): + found = True + self.assertTrue(self.decl_completed_in_line(line, decl), + "Should have called assert_decl_not_completed") + self.assertTrue(found, "Declaration no longer loaded " + str(decl) + + ".\nAST:\n" + ast) + + def assert_decl_not_completed(self, decl): + """ + Asserts that the given decl is currently not completed in the module's + AST. It may be loaded but then can can only contain undeserialized + declarations. + """ + ast = self.get_ast_dump() + found = False + for line in ast.splitlines(): + error_msg = "Unexpected completed decl: '" + line + "'.\nAST:\n" + ast + self.assertFalse(self.decl_completed_in_line(line, decl), error_msg) + + def assert_decl_not_loaded(self, decl): + """ + Asserts that the given decl is currently not loaded in the module's + AST. + """ + ast = self.get_ast_dump() + found = False + for line in ast.splitlines(): + error_msg = "Unexpected loaded decl: '" + line + "'\nAST:\n" + ast + self.assertFalse(self.decl_in_line(line, decl), error_msg) + + + def clean_setup(self, location): + """ + Runs to the line with the source line with the given location string + and ensures that our module AST is empty. + """ + lldbutil.run_to_source_breakpoint(self, + "// Location: " + location, lldb.SBFileSpec("main.cpp")) + # Make sure no declarations are loaded initially. + self.assert_no_decls_loaded() + + @add_test_categories(["dwarf"]) + def test_arithmetic_expression_in_main(self): + """ Runs a simple arithmetic expression which should load nothing. """ + self.clean_setup(location="multiple locals function") + + self.expect("expr 1 + (int)2.0", substrs=['(int) $0']) + + # This should not have loaded any decls. + self.assert_no_decls_loaded() + + @add_test_categories(["dwarf"]) + def test_printing_local_variable_in_other_struct_func(self): + """ + Prints a local variable and makes sure no unrelated types are loaded. + """ + self.clean_setup(location="other struct function") + + self.expect("expr other_struct_var", substrs=['(OtherStruct) $0']) + # The decl we run on was loaded. + self.assert_decl_loaded(self.other_struct_decl) + + # This should not have loaded anything else. + self.assert_decl_not_loaded(self.some_struct_decl) + self.assert_decl_not_loaded(self.class_in_namespace_decl) + + @add_test_categories(["dwarf"]) + def test_printing_struct_with_multiple_locals(self): + """ + Prints a local variable and checks that we don't load other local + variables. + """ + self.clean_setup(location="multiple locals function") + + self.expect("expr struct_var", substrs=['(SomeStruct) $0']) + + # We loaded SomeStruct and its member types for printing. + self.assert_decl_loaded(self.some_struct_decl) + self.assert_decl_loaded(self.struct_behind_ptr_decl) + self.assert_decl_loaded(self.struct_behind_ref_decl) + + # FIXME: We don't use these variables, but we seem to load all local + # local variables. + self.assert_decl_not_completed(self.other_struct_decl) + self.assert_decl_not_completed(self.class_in_namespace_decl) + + @add_test_categories(["dwarf"]) + def test_addr_of_struct(self): + """ + Prints the address of a local variable (which is a struct). + """ + self.clean_setup(location="multiple locals function") + + self.expect("expr &struct_var", substrs=['(SomeStruct *) $0']) + + # We loaded SomeStruct. + self.assert_decl_loaded(self.some_struct_decl) + + # The member declarations should not be completed. + self.assert_decl_not_completed(self.struct_behind_ptr_decl) + self.assert_decl_not_completed(self.struct_behind_ref_decl) + + # FIXME: The first member was behind a pointer so it shouldn't be + # completed. Somehow LLDB really wants to load the first member, so + # that is why have it defined here. + self.assert_decl_loaded(self.struct_first_member_decl) + + # FIXME: We don't use these variables, but we seem to load all local + # local variables. + self.assert_decl_not_completed(self.other_struct_decl) + self.assert_decl_not_completed(self.class_in_namespace_decl) + + @add_test_categories(["dwarf"]) + def test_class_function_access_member(self): + self.clean_setup(location="class function") + + self.expect("expr member", substrs=['(ClassMember) $0']) + + # We loaded the current class we touched. + self.assert_decl_loaded(self.class_we_enter_decl) + # We loaded the unused members of this class. + self.assert_decl_loaded(self.unused_class_member_decl) + self.assert_decl_not_completed(self.unused_class_member_ptr_decl) + # We loaded the member we used. + self.assert_decl_loaded(self.class_member_decl) + + # This should not have loaded anything else. + self.assert_decl_not_loaded(self.other_struct_decl) + self.assert_decl_not_loaded(self.some_struct_decl) + self.assert_decl_not_loaded(self.class_in_namespace_decl) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/lazy-loading/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/lazy-loading/main.cpp new file mode 100644 index 00000000000..34d62b483b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/lazy-loading/main.cpp @@ -0,0 +1,69 @@ +//----------------------------------------------------------------------------// +// Struct loading declarations. + +struct StructFirstMember { int i; }; +struct StructBehindPointer { int i; }; +struct StructBehindRef { int i; }; +struct StructMember { int i; }; + +StructBehindRef struct_instance; + +struct SomeStruct { + StructFirstMember *first; + StructBehindPointer *ptr; + StructMember member; + StructBehindRef &ref = struct_instance; +}; + +struct OtherStruct { + int member_int; +}; + +//----------------------------------------------------------------------------// +// Class loading declarations. + +struct ClassMember { int i; }; +struct UnusedClassMember { int i; }; +struct UnusedClassMemberPtr { int i; }; + +namespace NS { +class ClassInNamespace { + int i; +}; +class ClassWeEnter { +public: + int dummy; // Prevent bug where LLDB always completes first member. + ClassMember member; + UnusedClassMember unused_member; + UnusedClassMemberPtr *unused_member_ptr; + int enteredFunction() { + return member.i; // Location: class function + } +}; +}; + +//----------------------------------------------------------------------------// +// Function we can stop in. + +int functionWithOtherStruct() { + OtherStruct other_struct_var; + other_struct_var.member_int++; // Location: other struct function + return other_struct_var.member_int; +} + +int functionWithMultipleLocals() { + SomeStruct struct_var; + OtherStruct other_struct_var; + NS::ClassInNamespace namespace_class; + other_struct_var.member_int++; // Location: multiple locals function + return other_struct_var.member_int; +} + +int main(int argc, char **argv) { + NS::ClassWeEnter c; + c.enteredFunction(); + + functionWithOtherStruct(); + functionWithMultipleLocals(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/.categories new file mode 100644 index 00000000000..c00c25822e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/.categories @@ -0,0 +1 @@ +basic_process diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/Makefile new file mode 100644 index 00000000000..00054aabd4a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/Makefile @@ -0,0 +1,32 @@ +LD_EXTRAS := -L. -lloadunload_d +CXX_SOURCES := main.cpp +USE_LIBDL := 1 + +a.out: lib_b lib_a lib_c lib_d hidden_lib_d + +include Makefile.rules + +lib_a: lib_b + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_CXX_SOURCES=a.cpp DYLIB_NAME=loadunload_a \ + LD_EXTRAS="-L. -lloadunload_b" + +lib_b: + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_CXX_SOURCES=b.cpp DYLIB_NAME=loadunload_b + +lib_c: + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_CXX_SOURCES=c.cpp DYLIB_NAME=loadunload_c + +lib_d: + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_CXX_SOURCES=d.cpp DYLIB_NAME=loadunload_d +ifeq ($(OS),Darwin) + install_name_tool -id @executable_path/libloadunload_d.dylib libloadunload_d.dylib +endif + +hidden_lib_d: + mkdir -p hidden + $(MAKE) VPATH=$(SRCDIR)/hidden -C hidden -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_CXX_SOURCES=d.cpp DYLIB_NAME=loadunload_d diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py new file mode 100644 index 00000000000..ae0934c7461 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py @@ -0,0 +1,452 @@ +""" +Test that breakpoint by symbol name works correctly with dynamic libs. +""" + +from __future__ import print_function + + +import os +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently +class LoadUnloadTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.setup_test() + # Invoke the default build rule. + self.build() + # Find the line number to break for main.cpp. + self.line = line_number( + 'main.cpp', + '// Set break point at this line for test_lldb_process_load_and_unload_commands().') + self.line_d_function = line_number( + 'd.cpp', '// Find this line number within d_dunction().') + + def setup_test(self): + lldbutil.mkdir_p(self.getBuildArtifact("hidden")) + if not self.platformIsDarwin(): + if not lldb.remote_platform and "LD_LIBRARY_PATH" in os.environ: + self.runCmd( + "settings set target.env-vars " + + self.dylibPath + + "=" + + os.environ["LD_LIBRARY_PATH"] + + ":" + + self.getBuildDir()) + else: + if lldb.remote_platform: + wd = lldb.remote_platform.GetWorkingDirectory() + else: + wd = self.getBuildDir() + self.runCmd( + "settings set target.env-vars " + + self.dylibPath + + "=" + + wd) + + def copy_shlibs_to_remote(self, hidden_dir=False): + """ Copies the shared libs required by this test suite to remote. + Does nothing in case of non-remote platforms. + """ + if lldb.remote_platform: + ext = 'so' + if self.platformIsDarwin(): + ext = 'dylib' + + shlibs = ['libloadunload_a.' + ext, 'libloadunload_b.' + ext, + 'libloadunload_c.' + ext, 'libloadunload_d.' + ext] + wd = lldb.remote_platform.GetWorkingDirectory() + cwd = os.getcwd() + for f in shlibs: + err = lldb.remote_platform.Put( + lldb.SBFileSpec(self.getBuildArtifact(f)), + lldb.SBFileSpec(os.path.join(wd, f))) + if err.Fail(): + raise RuntimeError( + "Unable copy '%s' to '%s'.\n>>> %s" % + (f, wd, err.GetCString())) + if hidden_dir: + shlib = 'libloadunload_d.' + ext + hidden_dir = os.path.join(wd, 'hidden') + hidden_file = os.path.join(hidden_dir, shlib) + err = lldb.remote_platform.MakeDirectory(hidden_dir) + if err.Fail(): + raise RuntimeError( + "Unable to create a directory '%s'." % hidden_dir) + err = lldb.remote_platform.Put( + lldb.SBFileSpec(os.path.join('hidden', shlib)), + lldb.SBFileSpec(hidden_file)) + if err.Fail(): + raise RuntimeError( + "Unable copy 'libloadunload_d.so' to '%s'.\n>>> %s" % + (wd, err.GetCString())) + + def setSvr4Support(self, enabled): + self.runCmd( + "settings set plugin.process.gdb-remote.use-libraries-svr4 {enabled}".format( + enabled="true" if enabled else "false" + ) + ) + + # libloadunload_d.so does not appear in the image list because executable + # dependencies are resolved relative to the debuggers PWD. Bug? + @expectedFailureAll(oslist=["linux"]) + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @not_remote_testsuite_ready + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @expectedFailureNetBSD + def test_modules_search_paths(self): + """Test target modules list after loading a different copy of the library libd.dylib, and verifies that it works with 'target modules search-paths add'.""" + if self.platformIsDarwin(): + dylibName = 'libloadunload_d.dylib' + else: + dylibName = 'libloadunload_d.so' + + # The directory with the dynamic library we did not link to. + new_dir = os.path.join(self.getBuildDir(), "hidden") + + old_dylib = os.path.join(self.getBuildDir(), dylibName) + new_dylib = os.path.join(new_dir, dylibName) + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.expect("target modules list", + substrs=[old_dylib]) + # self.expect("target modules list -t 3", + # patterns = ["%s-[^-]*-[^-]*" % self.getArchitecture()]) + # Add an image search path substitution pair. + self.runCmd( + "target modules search-paths add %s %s" % + (self.getBuildDir(), new_dir)) + + self.expect("target modules search-paths list", + substrs=[self.getBuildDir(), new_dir]) + + self.expect( + "target modules search-paths query %s" % + self.getBuildDir(), + "Image search path successfully transformed", + substrs=[new_dir]) + + # Obliterate traces of libd from the old location. + os.remove(old_dylib) + # Inform (DY)LD_LIBRARY_PATH of the new path, too. + env_cmd_string = "settings set target.env-vars " + self.dylibPath + "=" + new_dir + if self.TraceOn(): + print("Set environment to: ", env_cmd_string) + self.runCmd(env_cmd_string) + self.runCmd("settings show target.env-vars") + + remove_dyld_path_cmd = "settings remove target.env-vars " + self.dylibPath + self.addTearDownHook( + lambda: self.dbg.HandleCommand(remove_dyld_path_cmd)) + + self.runCmd("run") + + self.expect( + "target modules list", + "LLDB successfully locates the relocated dynamic library", + substrs=[new_dylib]) + + # libloadunload_d.so does not appear in the image list because executable + # dependencies are resolved relative to the debuggers PWD. Bug? + @expectedFailureAll(oslist=["linux"]) + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @expectedFailureAndroid # wrong source file shows up for hidden library + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @skipIfDarwinEmbedded + @expectedFailureNetBSD + def test_dyld_library_path(self): + """Test (DY)LD_LIBRARY_PATH after moving libd.dylib, which defines d_function, somewhere else.""" + self.copy_shlibs_to_remote(hidden_dir=True) + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Shut off ANSI color usage so we don't get ANSI escape sequences + # mixed in with stop locations. + self.dbg.SetUseColor(False) + + if self.platformIsDarwin(): + dylibName = 'libloadunload_d.dylib' + dsymName = 'libloadunload_d.dylib.dSYM' + else: + dylibName = 'libloadunload_d.so' + + # The directory to relocate the dynamic library and its debugging info. + special_dir = "hidden" + if lldb.remote_platform: + wd = lldb.remote_platform.GetWorkingDirectory() + else: + wd = self.getBuildDir() + + old_dir = wd + new_dir = os.path.join(wd, special_dir) + old_dylib = os.path.join(old_dir, dylibName) + + remove_dyld_path_cmd = "settings remove target.env-vars " \ + + self.dylibPath + self.addTearDownHook( + lambda: self.dbg.HandleCommand(remove_dyld_path_cmd)) + + # For now we don't track (DY)LD_LIBRARY_PATH, so the old + # library will be in the modules list. + self.expect("target modules list", + substrs=[os.path.basename(old_dylib)], + matching=True) + + lldbutil.run_break_set_by_file_and_line( + self, "d.cpp", self.line_d_function, num_expected_locations=1) + # After run, make sure the non-hidden library is picked up. + self.expect("run", substrs=["return", "700"]) + + self.runCmd("continue") + + # Add the hidden directory first in the search path. + env_cmd_string = ("settings set target.env-vars %s=%s" % + (self.dylibPath, new_dir)) + if not self.platformIsDarwin(): + env_cmd_string += ":" + wd + self.runCmd(env_cmd_string) + + # This time, the hidden library should be picked up. + self.expect("run", substrs=["return", "12345"]) + + @expectedFailureAll( + bugnumber="llvm.org/pr25805", + hostoslist=["windows"], + triple='.*-android') + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + def test_lldb_process_load_and_unload_commands(self): + self.setSvr4Support(False) + self.run_lldb_process_load_and_unload_commands() + + @expectedFailureAll( + bugnumber="llvm.org/pr25805", + hostoslist=["windows"], + triple='.*-android') + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + def test_lldb_process_load_and_unload_commands_with_svr4(self): + self.setSvr4Support(True) + self.run_lldb_process_load_and_unload_commands() + + def run_lldb_process_load_and_unload_commands(self): + """Test that lldb process load/unload command work correctly.""" + self.copy_shlibs_to_remote() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break at main.cpp before the call to dlopen(). + # Use lldb's process load command to load the dylib, instead. + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + ctx = self.platformContext + dylibName = ctx.shlib_prefix + 'loadunload_a.' + ctx.shlib_extension + localDylibPath = self.getBuildArtifact(dylibName) + if lldb.remote_platform: + wd = lldb.remote_platform.GetWorkingDirectory() + remoteDylibPath = lldbutil.join_remote_paths(wd, dylibName) + else: + remoteDylibPath = localDylibPath + + # Make sure that a_function does not exist at this point. + self.expect( + "image lookup -n a_function", + "a_function should not exist yet", + error=True, + matching=False, + patterns=["1 match found"]) + + # Use lldb 'process load' to load the dylib. + self.expect( + "process load %s --install=%s" % (localDylibPath, remoteDylibPath), + "%s loaded correctly" % dylibName, + patterns=[ + 'Loading "%s".*ok' % re.escape(localDylibPath), + 'Image [0-9]+ loaded']) + + # Search for and match the "Image ([0-9]+) loaded" pattern. + output = self.res.GetOutput() + pattern = re.compile("Image ([0-9]+) loaded") + for l in output.split(os.linesep): + #print("l:", l) + match = pattern.search(l) + if match: + break + index = match.group(1) + + # Now we should have an entry for a_function. + self.expect( + "image lookup -n a_function", + "a_function should now exist", + patterns=[ + "1 match found .*%s" % + dylibName]) + + # Use lldb 'process unload' to unload the dylib. + self.expect( + "process unload %s" % + index, + "%s unloaded correctly" % + dylibName, + patterns=[ + "Unloading .* with index %s.*ok" % + index]) + + self.runCmd("process continue") + + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + def test_load_unload(self): + self.setSvr4Support(False) + self.run_load_unload() + + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + def test_load_unload_with_svr4(self): + self.setSvr4Support(True) + self.run_load_unload() + + def run_load_unload(self): + """Test breakpoint by name works correctly with dlopen'ing.""" + self.copy_shlibs_to_remote() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break by function name a_function (not yet loaded). + lldbutil.run_break_set_by_symbol( + self, "a_function", num_expected_locations=0) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint and at a_function. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'a_function', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Issue the 'contnue' command. We should stop agaian at a_function. + # The stop reason of the thread should be breakpoint and at a_function. + self.runCmd("continue") + + # rdar://problem/8508987 + # The a_function breakpoint should be encountered twice. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'a_function', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 2. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 2']) + + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @expectedFailureAll(archs="aarch64", oslist="linux", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=27806") + def test_step_over_load(self): + self.setSvr4Support(False) + self.run_step_over_load() + + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @expectedFailureAll(archs="aarch64", oslist="linux", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=27806") + def test_step_over_load_with_svr4(self): + self.setSvr4Support(True) + self.run_step_over_load() + + def run_step_over_load(self): + """Test stepping over code that loads a shared library works correctly.""" + self.copy_shlibs_to_remote() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break by function name a_function (not yet loaded). + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint and at a_function. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.runCmd( + "thread step-over", + "Stepping over function that loads library") + + # The stop reason should be step end. + self.expect("thread list", "step over succeeded.", + substrs=['stopped', + 'stop reason = step over']) + + # We can't find a breakpoint location for d_init before launching because + # executable dependencies are resolved relative to the debuggers PWD. Bug? + @expectedFailureAll(oslist=["linux"], triple=no_match('aarch64-.*-android')) + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @expectedFailureNetBSD + def test_static_init_during_load(self): + """Test that we can set breakpoints correctly in static initializers""" + self.copy_shlibs_to_remote() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + a_init_bp_num = lldbutil.run_break_set_by_symbol( + self, "a_init", num_expected_locations=0) + b_init_bp_num = lldbutil.run_break_set_by_symbol( + self, "b_init", num_expected_locations=0) + d_init_bp_num = lldbutil.run_break_set_by_symbol( + self, "d_init", num_expected_locations=1) + + self.runCmd("run", RUN_SUCCEEDED) + + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'd_init', + 'stop reason = breakpoint %d' % d_init_bp_num]) + + self.runCmd("continue") + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'b_init', + 'stop reason = breakpoint %d' % b_init_bp_num]) + self.expect("thread backtrace", + substrs=['b_init', + 'dlopen', + 'main']) + + self.runCmd("continue") + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'a_init', + 'stop reason = breakpoint %d' % a_init_bp_num]) + self.expect("thread backtrace", + substrs=['a_init', + 'dlopen', + 'main']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/a.cpp new file mode 100644 index 00000000000..ec34f9b974d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/a.cpp @@ -0,0 +1,21 @@ +//===-- a.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +extern int b_function (); + +int a_init() +{ + return 234; +} + +int a_global = a_init(); + +extern "C" int +a_function () +{ + return b_function (); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/b.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/b.cpp new file mode 100644 index 00000000000..9db93841ab7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/b.cpp @@ -0,0 +1,20 @@ +//===-- b.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int b_init() +{ + return 345; +} + +int b_global = b_init(); + +int +b_function () +{ + return 500; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/c.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/c.cpp new file mode 100644 index 00000000000..cf0c146621e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/c.cpp @@ -0,0 +1,12 @@ +//===-- c.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +extern "C" int +c_function () +{ + return 600; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/cmds.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/cmds.txt new file mode 100644 index 00000000000..1e4b198dc0d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/cmds.txt @@ -0,0 +1,2 @@ +breakpoint set -n a_function +run diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/d.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/d.cpp new file mode 100644 index 00000000000..a2135c50713 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/d.cpp @@ -0,0 +1,20 @@ +//===-- c.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int d_init() +{ + return 123; +} + +int d_global = d_init(); + +int +d_function () +{ // Find this line number within d_dunction(). + return 700; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/Makefile new file mode 100644 index 00000000000..17fe6582a9e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/Makefile @@ -0,0 +1,7 @@ +LIB_PREFIX := loadunload_ + +DYLIB_NAME := $(LIB_PREFIX)d +DYLIB_CXX_SOURCES := d.cpp +DYLIB_ONLY := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/d.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/d.cpp new file mode 100644 index 00000000000..d03d3c9f8c7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/d.cpp @@ -0,0 +1,20 @@ +//===-- c.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int d_init() +{ + return 456; +} + +int d_global = d_init(); + +int +d_function () +{ // Find this line number within d_dunction(). + return 12345; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/main.cpp new file mode 100644 index 00000000000..815f030d857 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_unload/main.cpp @@ -0,0 +1,79 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <dlfcn.h> +#include <limits.h> +#include <string.h> +#include <unistd.h> +#include <libgen.h> +#include <stdlib.h> + +int +main (int argc, char const *argv[]) +{ +#if defined (__APPLE__) + const char *a_name = "@executable_path/libloadunload_a.dylib"; + const char *c_name = "@executable_path/libloadunload_c.dylib"; +#else + const char *a_name = "libloadunload_a.so"; + const char *c_name = "libloadunload_c.so"; +#endif + void *a_dylib_handle = NULL; + void *c_dylib_handle = NULL; + int (*a_function) (void); + + a_dylib_handle = dlopen (a_name, RTLD_NOW); // Set break point at this line for test_lldb_process_load_and_unload_commands(). + if (a_dylib_handle == NULL) + { + fprintf (stderr, "%s\n", dlerror()); + exit (1); + } + + a_function = (int (*) ()) dlsym (a_dylib_handle, "a_function"); + if (a_function == NULL) + { + fprintf (stderr, "%s\n", dlerror()); + exit (2); + } + printf ("First time around, got: %d\n", a_function ()); + dlclose (a_dylib_handle); + + c_dylib_handle = dlopen (c_name, RTLD_NOW); + if (c_dylib_handle == NULL) + { + fprintf (stderr, "%s\n", dlerror()); + exit (3); + } + a_function = (int (*) ()) dlsym (c_dylib_handle, "c_function"); + if (a_function == NULL) + { + fprintf (stderr, "%s\n", dlerror()); + exit (4); + } + + a_dylib_handle = dlopen (a_name, RTLD_NOW); + if (a_dylib_handle == NULL) + { + fprintf (stderr, "%s\n", dlerror()); + exit (5); + } + + a_function = (int (*) ()) dlsym (a_dylib_handle, "a_function"); + if (a_function == NULL) + { + fprintf (stderr, "%s\n", dlerror()); + exit (6); + } + printf ("Second time around, got: %d\n", a_function ()); + dlclose (a_dylib_handle); + + int d_function(void); + printf ("d_function returns: %d\n", d_function()); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/.categories new file mode 100644 index 00000000000..c00c25822e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/.categories @@ -0,0 +1 @@ +basic_process diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/Makefile new file mode 100644 index 00000000000..814a9601375 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/Makefile @@ -0,0 +1,11 @@ +CXX_SOURCES := main.cpp +USE_LIBDL := 1 + +all: hidden_lib a.out + +include Makefile.rules + +hidden_lib: + $(MAKE) VPATH=$(SRCDIR)/hidden -C hidden -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_CXX_SOURCES=d.cpp DYLIB_NAME=loadunload + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/TestLoadUsingPaths.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/TestLoadUsingPaths.py new file mode 100644 index 00000000000..0adb3d09b60 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/TestLoadUsingPaths.py @@ -0,0 +1,141 @@ +""" +Test that SBProcess.LoadImageUsingPaths works correctly. +""" + + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipIfWindows # The Windows platform doesn't implement DoLoadImage. +class LoadUsingPathsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Make the hidden directory in the build hierarchy: + lldbutil.mkdir_p(self.getBuildArtifact("hidden")) + + # Invoke the default build rule. + self.build() + + ext = 'so' + if self.platformIsDarwin(): + ext = 'dylib' + self.lib_name = 'libloadunload.' + ext + + self.wd = os.path.realpath(self.getBuildDir()) + self.hidden_dir = os.path.join(self.wd, 'hidden') + self.hidden_lib = os.path.join(self.hidden_dir, self.lib_name) + + @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support + @not_remote_testsuite_ready + @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently + @expectedFlakeyNetBSD + def test_load_using_paths(self): + """Test that we can load a module by providing a set of search paths.""" + if self.platformIsDarwin(): + dylibName = 'libloadunload_d.dylib' + else: + dylibName = 'libloadunload_d.so' + + # The directory with the dynamic library we did not link to. + path_dir = os.path.join(self.getBuildDir(), "hidden") + + (target, process, thread, + _) = lldbutil.run_to_source_breakpoint(self, + "Break here to do the load using paths", + lldb.SBFileSpec("main.cpp")) + error = lldb.SBError() + lib_spec = lldb.SBFileSpec(self.lib_name) + paths = lldb.SBStringList() + paths.AppendString(self.wd) + paths.AppendString(os.path.join(self.wd, "no_such_dir")) + + out_spec = lldb.SBFileSpec() + + # First try with no correct directories on the path, and make sure that doesn't blow up: + token = process.LoadImageUsingPaths(lib_spec, paths, out_spec, error) + self.assertEqual(token, lldb.LLDB_INVALID_IMAGE_TOKEN, "Only looked on the provided path.") + + # Now add the correct dir to the paths list and try again: + paths.AppendString(self.hidden_dir) + token = process.LoadImageUsingPaths(lib_spec, paths, out_spec, error) + + self.assertNotEqual(token, lldb.LLDB_INVALID_IMAGE_TOKEN, "Got a valid token") + self.assertEqual(out_spec, lldb.SBFileSpec(self.hidden_lib), "Found the expected library") + + # Make sure this really is in the image list: + loaded_module = target.FindModule(out_spec) + + self.assertTrue(loaded_module.IsValid(), "The loaded module is in the image list.") + + # Now see that we can call a function in the loaded module. + value = thread.frames[0].EvaluateExpression("d_function()", lldb.SBExpressionOptions()) + self.assertTrue(value.GetError().Success(), "Got a value from the expression") + ret_val = value.GetValueAsSigned() + self.assertEqual(ret_val, 12345, "Got the right value") + + # Make sure the token works to unload it: + process.UnloadImage(token) + + # Make sure this really is no longer in the image list: + loaded_module = target.FindModule(out_spec) + + self.assertFalse(loaded_module.IsValid(), "The unloaded module is no longer in the image list.") + + # Make sure a relative path also works: + paths.Clear() + paths.AppendString(os.path.join(self.wd, "no_such_dir")) + paths.AppendString(self.wd) + relative_spec = lldb.SBFileSpec(os.path.join("hidden", self.lib_name)) + + out_spec = lldb.SBFileSpec() + token = process.LoadImageUsingPaths(relative_spec, paths, out_spec, error) + + self.assertNotEqual(token, lldb.LLDB_INVALID_IMAGE_TOKEN, "Got a valid token with relative path") + self.assertEqual(out_spec, lldb.SBFileSpec(self.hidden_lib), "Found the expected library with relative path") + + process.UnloadImage(token) + + # Make sure the presence of an empty path doesn't mess anything up: + paths.Clear() + paths.AppendString("") + paths.AppendString(os.path.join(self.wd, "no_such_dir")) + paths.AppendString(self.wd) + relative_spec = lldb.SBFileSpec(os.path.join("hidden", self.lib_name)) + + out_spec = lldb.SBFileSpec() + token = process.LoadImageUsingPaths(relative_spec, paths, out_spec, error) + + self.assertNotEqual(token, lldb.LLDB_INVALID_IMAGE_TOKEN, "Got a valid token with included empty path") + self.assertEqual(out_spec, lldb.SBFileSpec(self.hidden_lib), "Found the expected library with included empty path") + + process.UnloadImage(token) + + + + # Finally, passing in an absolute path should work like the basename: + # This should NOT work because we've taken hidden_dir off the paths: + abs_spec = lldb.SBFileSpec(os.path.join(self.hidden_dir, self.lib_name)) + + token = process.LoadImageUsingPaths(lib_spec, paths, out_spec, error) + self.assertEqual(token, lldb.LLDB_INVALID_IMAGE_TOKEN, "Only looked on the provided path.") + + # But it should work when we add the dir: + # Now add the correct dir to the paths list and try again: + paths.AppendString(self.hidden_dir) + token = process.LoadImageUsingPaths(lib_spec, paths, out_spec, error) + + self.assertNotEqual(token, lldb.LLDB_INVALID_IMAGE_TOKEN, "Got a valid token") + self.assertEqual(out_spec, lldb.SBFileSpec(self.hidden_lib), "Found the expected library") + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/hidden/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/hidden/Makefile new file mode 100644 index 00000000000..5e22c8a8ea7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/hidden/Makefile @@ -0,0 +1,5 @@ +DYLIB_NAME := loadunload +DYLIB_CXX_SOURCES := d.cpp +DYLIB_ONLY := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/hidden/d.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/hidden/d.cpp new file mode 100644 index 00000000000..d03d3c9f8c7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/hidden/d.cpp @@ -0,0 +1,20 @@ +//===-- c.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int d_init() +{ + return 456; +} + +int d_global = d_init(); + +int +d_function () +{ // Find this line number within d_dunction(). + return 12345; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/main.cpp new file mode 100644 index 00000000000..432774d36b5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/load_using_paths/main.cpp @@ -0,0 +1,15 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int +main (int argc, char const *argv[]) +{ + printf("Break here to do the load using paths."); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py new file mode 100644 index 00000000000..fa7ffa64432 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py @@ -0,0 +1,85 @@ +""" +Test the use of setjmp/longjmp for non-local goto operations in a single-threaded inferior. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LongjmpTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp + @skipIfFreeBSD # llvm.org/pr17214 + @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr20231") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + @expectedFlakeyNetBSD + def test_step_out(self): + """Test stepping when the inferior calls setjmp/longjmp, in particular, thread step-out.""" + self.build() + self.step_out() + + @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp + @skipIfFreeBSD # llvm.org/pr17214 + @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr20231") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + @skipIfNetBSD + def test_step_over(self): + """Test stepping when the inferior calls setjmp/longjmp, in particular, thread step-over a longjmp.""" + self.build() + self.step_over() + + @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp + @skipIfFreeBSD # llvm.org/pr17214 + @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr20231") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + @expectedFlakeyNetBSD + def test_step_back_out(self): + """Test stepping when the inferior calls setjmp/longjmp, in particular, thread step-out after thread step-in.""" + self.build() + self.step_back_out() + + def start_test(self, symbol): + exe = self.getBuildArtifact("a.out") + + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break in main(). + lldbutil.run_break_set_by_symbol( + self, symbol, num_expected_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=['stopped', 'stop reason = breakpoint']) + + def check_status(self): + # Note: Depending on the generated mapping of DWARF to assembly, + # the process may have stopped or exited. + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* exited with status = 0']) + + def step_out(self): + self.start_test("do_jump") + self.runCmd("thread step-out", RUN_SUCCEEDED) + self.check_status() + + def step_over(self): + self.start_test("do_jump") + self.runCmd("thread step-over", RUN_SUCCEEDED) + self.runCmd("thread step-over", RUN_SUCCEEDED) + self.check_status() + + def step_back_out(self): + self.start_test("main") + + self.runCmd("thread step-over", RUN_SUCCEEDED) + self.runCmd("thread step-in", RUN_SUCCEEDED) + self.runCmd("thread step-out", RUN_SUCCEEDED) + self.check_status() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/main.c new file mode 100644 index 00000000000..ce1af7038c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/longjmp/main.c @@ -0,0 +1,30 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <setjmp.h> +#include <stdio.h> +#include <time.h> + +jmp_buf j; + +void do_jump(void) +{ + // We can't let the compiler know this will always happen or it might make + // optimizations that break our test. + if (!clock()) + longjmp(j, 1); // non-local goto +} + +int main (void) +{ + if (setjmp(j) == 0) + do_jump(); + else + return 0; // destination of longjmp + + return 1; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory-region/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory-region/Makefile new file mode 100644 index 00000000000..31f2d5e8fc2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory-region/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules + +clean:: + rm -rf $(wildcard *.o *.d *.dSYM) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory-region/TestMemoryRegion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory-region/TestMemoryRegion.py new file mode 100644 index 00000000000..283cc945ed0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory-region/TestMemoryRegion.py @@ -0,0 +1,58 @@ +""" +Test the 'memory region' command. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class MemoryCommandRegion(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number( + 'main.cpp', + '// Run here before printing memory regions') + + def test(self): + self.build() + + # Set breakpoint in main and run + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + + # Test that the first 'memory region' command prints the usage. + interp.HandleCommand("memory region", result) + self.assertFalse(result.Succeeded()) + self.assertRegexpMatches(result.GetError(), "Usage: memory region ADDR") + + # Now let's print the memory region starting at 0 which should always work. + interp.HandleCommand("memory region 0x0", result) + self.assertTrue(result.Succeeded()) + self.assertRegexpMatches(result.GetOutput(), "\\[0x0+-") + + # Keep printing memory regions until we printed all of them. + while True: + interp.HandleCommand("memory region", result) + if not result.Succeeded(): + break + + # Now that we reached the end, 'memory region' should again print the usage. + interp.HandleCommand("memory region", result) + self.assertFalse(result.Succeeded()) + self.assertRegexpMatches(result.GetError(), "Usage: memory region ADDR") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory-region/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory-region/main.cpp new file mode 100644 index 00000000000..116c10a6c3e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory-region/main.cpp @@ -0,0 +1,6 @@ +#include <iostream> + +int main (int argc, char const **argv) { + std::cout << "Program with sections" << std::endl; + return 0; // Run here before printing memory regions +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/TestMemoryCache.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/TestMemoryCache.py new file mode 100644 index 00000000000..8a1523495b4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/TestMemoryCache.py @@ -0,0 +1,62 @@ +""" +Test the MemoryCache L1 flush. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class MemoryCacheTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + + @skipIfWindows # This is flakey on Windows: llvm.org/pr38373 + def test_memory_cache(self): + """Test the MemoryCache class with a sequence of 'memory read' and 'memory write' operations.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break in main() after the variables are assigned values. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Read a chunk of memory containing &my_ints[0]. The number of bytes read + # must be greater than m_L2_cache_line_byte_size to make sure the L1 + # cache is used. + self.runCmd('memory read -f d -c 201 `&my_ints - 100`') + + # Check the value of my_ints[0] is the same as set in main.cpp. + line = self.res.GetOutput().splitlines()[100] + self.assertTrue(0x00000042 == int(line.split(':')[1], 0)) + + # Change the value of my_ints[0] in memory. + self.runCmd("memory write -s 4 `&my_ints` AA") + + # Re-read the chunk of memory. The cache line should have been + # flushed because of the 'memory write'. + self.runCmd('memory read -f d -c 201 `&my_ints - 100`') + + # Check the value of my_ints[0] have been updated correctly. + line = self.res.GetOutput().splitlines()[100] + self.assertTrue(0x000000AA == int(line.split(':')[1], 0)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/main.cpp new file mode 100644 index 00000000000..d47107cef87 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/cache/main.cpp @@ -0,0 +1,13 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main () +{ + int my_ints[] = {0x42}; + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/TestMemoryFind.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/TestMemoryFind.py new file mode 100644 index 00000000000..66d43665dc7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/TestMemoryFind.py @@ -0,0 +1,66 @@ +""" +Test the 'memory find' command. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * + + +class MemoryFindTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// break here') + + def test_memory_find(self): + """Test the 'memory find' command.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break in main() after the variables are assigned values. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Test the memory find commands. + + self.expect( + 'memory find -s "in const" `stringdata` `stringdata+(int)strlen(stringdata)`', + substrs=[ + 'data found at location: 0x', + '69 6e 20 63', + 'in const']) + + self.expect( + 'memory find -e "(uint8_t)0x22" `&bytedata[0]` `&bytedata[15]`', + substrs=[ + 'data found at location: 0x', + '22 33 44 55 66']) + + self.expect( + 'memory find -e "(uint8_t)0x22" `&bytedata[0]` `&bytedata[2]`', + substrs=['data not found within the range.']) + + self.expect('memory find -s "nothere" `stringdata` `stringdata+5`', + substrs=['data not found within the range.']) + + self.expect('memory find -s "nothere" `stringdata` `stringdata+10`', + substrs=['data not found within the range.']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/main.cpp new file mode 100644 index 00000000000..5f4545daabd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/find/main.cpp @@ -0,0 +1,16 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +int main (int argc, char const *argv[]) +{ + const char* stringdata = "hello world; I like to write text in const char pointers"; + uint8_t bytedata[] = {0xAA,0xBB,0xCC,0xDD,0xEE,0xFF,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99}; + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py new file mode 100644 index 00000000000..72d55dfa51f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py @@ -0,0 +1,133 @@ +""" +Test the 'memory read' command. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class MemoryReadTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_memory_read(self): + """Test the 'memory read' command with plain and vector formats.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break in main() after the variables are assigned values. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Test the memory read commands. + + # (lldb) memory read -f d -c 1 `&argc` + # 0x7fff5fbff9a0: 1 + self.runCmd("memory read -f d -c 1 `&argc`") + + # Find the starting address for variable 'argc' to verify later that the + # '--format uint32_t[] --size 4 --count 4' option increments the address + # correctly. + line = self.res.GetOutput().splitlines()[0] + items = line.split(':') + address = int(items[0], 0) + argc = int(items[1], 0) + self.assertTrue(address > 0 and argc == 1) + + # (lldb) memory read --format uint32_t[] --size 4 --count 4 `&argc` + # 0x7fff5fbff9a0: {0x00000001} + # 0x7fff5fbff9a4: {0x00000000} + # 0x7fff5fbff9a8: {0x0ec0bf27} + # 0x7fff5fbff9ac: {0x215db505} + self.runCmd( + "memory read --format uint32_t[] --size 4 --count 4 `&argc`") + lines = self.res.GetOutput().splitlines() + for i in range(4): + if i == 0: + # Verify that the printout for argc is correct. + self.assertTrue( + argc == int( + lines[i].split(':')[1].strip(' {}'), 0)) + addr = int(lines[i].split(':')[0], 0) + # Verify that the printout for addr is incremented correctly. + self.assertTrue(addr == (address + i * 4)) + + # (lldb) memory read --format char[] --size 7 --count 1 `&my_string` + # 0x7fff5fbff990: {abcdefg} + self.expect( + "memory read --format char[] --size 7 --count 1 `&my_string`", + substrs=['abcdefg']) + + # (lldb) memory read --format 'hex float' --size 16 `&argc` + # 0x7fff5fbff5b0: error: unsupported byte size (16) for hex float + # format + self.expect( + "memory read --format 'hex float' --size 16 `&argc`", + substrs=['unsupported byte size (16) for hex float format']) + + self.expect( + "memory read --format 'float' --count 1 --size 8 `&my_double`", + substrs=['1234.']) + + # (lldb) memory read --format 'float' --count 1 --size 20 `&my_double` + # 0x7fff5fbff598: error: unsupported byte size (20) for float format + self.expect( + "memory read --format 'float' --count 1 --size 20 `&my_double`", + substrs=['unsupported byte size (20) for float format']) + + self.expect('memory read --type int --count 5 `&my_ints[0]`', + substrs=['(int) 0x', '2', '4', '6', '8', '10']) + + self.expect( + 'memory read --type int --count 5 --format hex `&my_ints[0]`', + substrs=[ + '(int) 0x', + '0x', + '0a']) + + self.expect( + 'memory read --type int --count 5 --offset 5 `&my_ints[0]`', + substrs=[ + '(int) 0x', + '12', + '14', + '16', + '18', + '20']) + + # the gdb format specifier and the size in characters for + # the returned values including the 0x prefix. + variations = [['b', 4], ['h', 6], ['w', 10], ['g', 18]] + for v in variations: + formatter = v[0] + expected_object_length = v[1] + self.runCmd( + "memory read --gdb-format 4%s &my_uint64s" % formatter) + lines = self.res.GetOutput().splitlines() + objects_read = [] + for l in lines: + objects_read.extend(l.split(':')[1].split()) + # Check that we got back 4 0x0000 etc bytes + for o in objects_read: + self.assertTrue (len(o) == expected_object_length) + self.assertTrue(len(objects_read) == 4) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/main.cpp new file mode 100644 index 00000000000..3c1ab5e3f33 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/memory/read/main.cpp @@ -0,0 +1,20 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +int main (int argc, char const *argv[]) +{ + char my_string[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 0}; + double my_double = 1234.5678; + int my_ints[] = {2,4,6,8,10,12,14,16,18,20,22}; + uint64_t my_uint64s[] = {0, 1, 2, 3, 4, 5, 6, 7}; + printf("my_string=%s\n", my_string); // Set break point at this line. + printf("my_double=%g\n", my_double); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/mtc/simple/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/mtc/simple/Makefile new file mode 100644 index 00000000000..f27f57aeebf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/mtc/simple/Makefile @@ -0,0 +1,14 @@ +OBJC_SOURCES := main.m +UI_FRAMEWORK = AppKit + +ifneq ("$(SDKROOT)", "") + ifeq (,$(findstring macOS,$(SDKROOT))) + ifeq (,$(findstring MacOS,$(SDKROOT))) + UI_FRAMEWORK = UIKit + endif + endif +endif + +LD_EXTRAS = -lobjc -framework Foundation -framework $(UI_FRAMEWORK) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/mtc/simple/TestMTCSimple.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/mtc/simple/TestMTCSimple.py new file mode 100644 index 00000000000..e3751e02c45 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/mtc/simple/TestMTCSimple.py @@ -0,0 +1,58 @@ +""" +Tests basic Main Thread Checker support (detecting a main-thread-only violation). +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbplatformutil import * +import json + + +class MTCSimpleTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test(self): + self.mtc_dylib_path = findMainThreadCheckerDylib() + if self.mtc_dylib_path == "": + self.skipTest("This test requires libMainThreadChecker.dylib") + + self.build() + self.mtc_tests() + + @skipIf(archs=['i386']) + def mtc_tests(self): + self.assertTrue(self.mtc_dylib_path != "") + + # Load the test + exe = self.getBuildArtifact("a.out") + self.expect("file " + exe, patterns=["Current executable set to .*a.out"]) + + self.runCmd("env DYLD_INSERT_LIBRARIES=%s" % self.mtc_dylib_path) + self.runCmd("run") + + process = self.dbg.GetSelectedTarget().process + thread = process.GetSelectedThread() + frame = thread.GetSelectedFrame() + + view = "NSView" if lldbplatformutil.getPlatform() == "macosx" else "UIView" + + self.expect("thread info", + substrs=['stop reason = -[' + view + + ' superview] must be used from main thread only']) + + self.expect( + "thread info -s", + substrs=["instrumentation_class", "api_name", "class_name", "selector", "description"]) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonInstrumentation) + output_lines = self.res.GetOutput().split('\n') + json_line = '\n'.join(output_lines[2:]) + data = json.loads(json_line) + self.assertEqual(data["instrumentation_class"], "MainThreadChecker") + self.assertEqual(data["api_name"], "-[" + view + " superview]") + self.assertEqual(data["class_name"], view) + self.assertEqual(data["selector"], "superview") + self.assertEqual(data["description"], "-[" + view + " superview] must be used from main thread only") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/mtc/simple/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/mtc/simple/main.m new file mode 100644 index 00000000000..a967dee4692 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/mtc/simple/main.m @@ -0,0 +1,21 @@ +#import <Foundation/Foundation.h> +#if __has_include(<AppKit/AppKit.h>) +#import <AppKit/AppKit.h> +#define XXView NSView +#else +#import <UIKit/UIKit.h> +#define XXView UIView +#endif + +int main() { + XXView *view = [[XXView alloc] init]; + dispatch_group_t g = dispatch_group_create(); + dispatch_group_enter(g); + [NSThread detachNewThreadWithBlock:^{ + @autoreleasepool { + [view superview]; + } + dispatch_group_leave(g); + }]; + dispatch_group_wait(g, DISPATCH_TIME_FOREVER); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/multidebugger_commands/TestMultipleDebuggersCommands.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/multidebugger_commands/TestMultipleDebuggersCommands.py new file mode 100644 index 00000000000..845950758f8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/multidebugger_commands/TestMultipleDebuggersCommands.py @@ -0,0 +1,52 @@ +""" +Test that commands do not try and hold on to stale CommandInterpreters in a multiple debuggers scenario +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class MultipleDebuggersCommandsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_multipledebuggers_commands(self): + """Test that commands do not try and hold on to stale CommandInterpreters in a multiple debuggers scenario""" + source_init_files = False + magic_text = "The following commands may relate to 'env'" + + debugger_1 = lldb.SBDebugger.Create(source_init_files) + interpreter_1 = debugger_1.GetCommandInterpreter() + + retobj = lldb.SBCommandReturnObject() + interpreter_1.HandleCommand("apropos env", retobj) + self.assertTrue( + magic_text in str(retobj), + "[interpreter_1]: the output does not contain the correct words") + + if self.TraceOn(): + print(str(retobj)) + + lldb.SBDebugger.Destroy(debugger_1) + + # now do this again with a different debugger - we shouldn't crash + + debugger_2 = lldb.SBDebugger.Create(source_init_files) + interpreter_2 = debugger_2.GetCommandInterpreter() + + retobj = lldb.SBCommandReturnObject() + interpreter_2.HandleCommand("apropos env", retobj) + self.assertTrue( + magic_text in str(retobj), + "[interpreter_2]: the output does not contain the correct words") + + if self.TraceOn(): + print(str(retobj)) + + lldb.SBDebugger.Destroy(debugger_2) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/multiword-commands/TestMultiWordCommands.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/multiword-commands/TestMultiWordCommands.py new file mode 100644 index 00000000000..80b144f58d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/multiword-commands/TestMultiWordCommands.py @@ -0,0 +1,33 @@ +""" +Test multiword commands ('platform' in this case). +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + +class MultiwordCommandsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_ambiguous_subcommand(self): + self.expect("platform s", error=True, + substrs=["ambiguous command 'platform s'. Possible completions:", + "\tselect\n", + "\tshell\n", + "\tsettings\n"]) + + @no_debug_info_test + def test_empty_subcommand(self): + self.expect("platform \"\"", error=True, substrs=["Need to specify a non-empty subcommand."]) + + @no_debug_info_test + def test_help(self): + # <multiword> help brings up help. + self.expect("platform help", + substrs=["Commands to manage and create platforms.", + "Syntax: platform [", + "The following subcommands are supported:", + "connect", + "Select the current platform"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py new file mode 100644 index 00000000000..d5424c0bb40 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py @@ -0,0 +1,47 @@ +"""Test evaluating expressions which ref. index variable 'i' which just goes +from out of scope to in scope when stopped at the breakpoint.""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class NonOverlappingIndexVariableCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.source = 'main.cpp' + self.line_to_break = line_number( + self.source, '// Set breakpoint here.') + + # rdar://problem/9890530 + def test_eval_index_variable(self): + """Test expressions of variable 'i' which appears in two for loops.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + self.source, + self.line_to_break, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.runCmd('frame variable i') + self.runCmd('expr i') + self.runCmd('expr ptr[0]->point.x') + self.runCmd('expr ptr[0]->point.y') + self.runCmd('expr ptr[i]->point.x') + self.runCmd('expr ptr[i]->point.y') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/main.cpp new file mode 100644 index 00000000000..2b8406a631b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/main.cpp @@ -0,0 +1,45 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +class Point { +public: + int x; + int y; + Point(int a, int b): + x(a), + y(b) + {} +}; + +class Data { +public: + int id; + Point point; + Data(int i): + id(i), + point(0, 0) + {} +}; + +int main(int argc, char const *argv[]) { + Data *data[1000]; + Data **ptr = data; + for (int i = 0; i < 1000; ++i) { + ptr[i] = new Data(i); + ptr[i]->point.x = i; + ptr[i]->point.y = i+1; + } + + for (int i = 0; i < 1000; ++i) { + bool dump = argc > 1; // Set breakpoint here. + // Evaluate a couple of expressions (2*1000 = 2000 exprs): + // expr ptr[i]->point.x + // expr ptr[i]->point.y + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py new file mode 100644 index 00000000000..1ad90e4fce5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py @@ -0,0 +1,45 @@ +""" +Test lldb 'image list' on object files across multiple architectures. +This exercises classes like ObjectFileELF and their support for opening +foreign-architecture object files. +""" + + + +import os.path +import re + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestImageListMultiArchitecture(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + @skipIfRemote + def test_image_list_shows_multiple_architectures(self): + """Test that image list properly shows the correct architecture for a set of different architecture object files.""" + images = { + "hello-freebsd-10.0-x86_64-clang-3.3": re.compile(r"x86_64-(\*)?-freebsd10.0(-unknown)? x86_64"), + "hello-freebsd-10.0-x86_64-gcc-4.7.3": re.compile(r"x86_64-(\*)?-freebsd10.0(-unknown)? x86_64"), + "hello-netbsd-6.1-x86_64-gcc-4.5.3": re.compile(r"x86_64-(\*)?-netbsd6.1.4(-unknown)? x86_64"), + "hello-ubuntu-14.04-x86_64-gcc-4.8.2": re.compile(r"x86_64-(\*)?-linux(-unknown)? x86_64"), + "hello-ubuntu-14.04-x86_64-clang-3.5pre": re.compile(r"x86_64-(\*)?-linux(-unknown)? x86_64"), + } + + for image_name in images: + file_name = os.path.abspath( + os.path.join( + os.path.dirname(__file__), + "bin", + image_name)) + expected_triple_and_arch_regex = images[image_name] + + self.runCmd("file {}".format(file_name)) + self.match("image list -t -A", [expected_triple_and_arch_regex]) + # Revert to the host platform after all of this is done + self.runCmd("platform select host") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-clang-3.3 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-clang-3.3 Binary files differnew file mode 100644 index 00000000000..cea323639b4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-clang-3.3 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-gcc-4.7.3 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-gcc-4.7.3 Binary files differnew file mode 100644 index 00000000000..38f43f8acb9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-gcc-4.7.3 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-netbsd-6.1-x86_64-gcc-4.5.3 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-netbsd-6.1-x86_64-gcc-4.5.3 Binary files differnew file mode 100644 index 00000000000..6d531320ae9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-netbsd-6.1-x86_64-gcc-4.5.3 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-clang-3.5pre b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-clang-3.5pre Binary files differnew file mode 100644 index 00000000000..8bdcf4d5b59 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-clang-3.5pre diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-gcc-4.8.2 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-gcc-4.8.2 Binary files differnew file mode 100644 index 00000000000..01efbb061b7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-gcc-4.8.2 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch4-kcc-36 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch4-kcc-36 Binary files differnew file mode 100644 index 00000000000..8e4dd8c883c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch4-kcc-36 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch5-kcc-39 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch5-kcc-39 Binary files differnew file mode 100644 index 00000000000..f80268a08e5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch5-kcc-39 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.c new file mode 100644 index 00000000000..8c804005afe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.c @@ -0,0 +1,8 @@ +#include <stdio.h> + +int main(int argc, char **argv) +{ + printf("Hello, world\n"); + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.cpp new file mode 100644 index 00000000000..8c804005afe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.cpp @@ -0,0 +1,8 @@ +#include <stdio.h> + +int main(int argc, char **argv) +{ + printf("Hello, world\n"); + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/param_entry_vals/basic_entry_values_x86_64/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/param_entry_vals/basic_entry_values_x86_64/Makefile new file mode 100644 index 00000000000..db8fa57abb9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/param_entry_vals/basic_entry_values_x86_64/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +CXXFLAGS_EXTRAS := -O2 -glldb -Xclang -femit-debug-entry-values +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/param_entry_vals/basic_entry_values_x86_64/TestBasicEntryValuesX86_64.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/param_entry_vals/basic_entry_values_x86_64/TestBasicEntryValuesX86_64.py new file mode 100644 index 00000000000..e0285e6d626 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/param_entry_vals/basic_entry_values_x86_64/TestBasicEntryValuesX86_64.py @@ -0,0 +1,13 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators +from lldbsuite.test import lldbplatformutil + +supported_platforms = ["linux"] +supported_platforms.extend(lldbplatformutil.getDarwinOSTriples()) + +lldbinline.MakeInlineTest(__file__, globals(), + [decorators.skipUnlessPlatform(supported_platforms), + decorators.skipIf(compiler="clang", compiler_version=['<', '10.0']), + decorators.skipUnlessArch('x86_64'), + decorators.skipUnlessHasCallSiteInfo, + decorators.skipIf(dwarf_version=['<', '4'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/param_entry_vals/basic_entry_values_x86_64/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/param_entry_vals/basic_entry_values_x86_64/main.cpp new file mode 100644 index 00000000000..9aac6e94783 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/param_entry_vals/basic_entry_values_x86_64/main.cpp @@ -0,0 +1,248 @@ +// Note: This test requires the SysV AMD64 ABI to be in use, and requires +// compiler support for DWARF entry values. + +// Inhibit dead-arg-elim by using 'x'. +template<typename T> __attribute__((noinline)) void use(T x) { + asm volatile ("" + /* Outputs */ : + /* Inputs */ : "g"(x) + /* Clobbers */ : + ); +} + +// Destroy %rsi in the current frame. +#define DESTROY_RSI \ + asm volatile ("xorq %%rsi, %%rsi" \ + /* Outputs */ : \ + /* Inputs */ : \ + /* Clobbers */ : "rsi" \ + ); + +// Destroy %rbx in the current frame. +#define DESTROY_RBX \ + asm volatile ("xorq %%rbx, %%rbx" \ + /* Outputs */ : \ + /* Inputs */ : \ + /* Clobbers */ : "rbx" \ + ); + +struct S1 { + int field1 = 123; + int *field2 = &field1; +}; + +__attribute__((noinline)) +void func1(int &sink, int x) { + use(x); + + // Destroy 'x' in the current frame. + DESTROY_RSI; + + // NOTE: Currently, we do not generate DW_OP_entry_value for the 'x', + // since it gets copied into a register that is not callee saved, + // and we can not guarantee that its value has not changed. + + ++sink; + + // Destroy 'sink' in the current frame. + DESTROY_RBX; + + //% self.filecheck("image lookup -va $pc", "main.cpp", "-check-prefix=FUNC1-DESC") + // FUNC1-DESC: name = "sink", type = "int &", location = DW_OP_entry_value(DW_OP_reg5 RDI) +} + +__attribute__((noinline)) +void func2(int &sink, int x) { + use(x); + + // Destroy 'x' in the current frame. + DESTROY_RSI; + + //% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC2-EXPR-FAIL", expect_cmd_failure=True) + // FUNC2-EXPR-FAIL: couldn't get the value of variable x: variable not available + + ++sink; + + // Destroy 'sink' in the current frame. + DESTROY_RBX; + + //% self.filecheck("expr sink", "main.cpp", "-check-prefix=FUNC2-EXPR") + // FUNC2-EXPR: ${{.*}} = 2 +} + +__attribute__((noinline)) +void func3(int &sink, int *p) { + use(p); + + // Destroy 'p' in the current frame. + DESTROY_RSI; + + //% self.filecheck("expr *p", "main.cpp", "-check-prefix=FUNC3-EXPR") + // FUNC3-EXPR: (int) ${{.*}} = 123 + + ++sink; +} + +__attribute__((noinline)) +void func4_amb(int &sink, int x) { + use(x); + + // Destroy 'x' in the current frame. + DESTROY_RSI; + + //% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC4-EXPR-FAIL", expect_cmd_failure=True) + // FUNC4-EXPR-FAIL: couldn't get the value of variable x: variable not available + + ++sink; + + // Destroy 'sink' in the current frame. + DESTROY_RBX; + + //% self.filecheck("expr sink", "main.cpp", "-check-prefix=FUNC4-EXPR", expect_cmd_failure=True) + // FUNC4-EXPR: couldn't get the value of variable sink: Could not evaluate DW_OP_entry_value. +} + +__attribute__((noinline)) +void func5_amb() {} + +__attribute__((noinline)) +void func6(int &sink, int x) { + if (sink > 0) + func4_amb(sink, x); /* tail (taken) */ + else + func5_amb(); /* tail */ +} + +__attribute__((noinline)) +void func7(int &sink, int x) { + //% self.filecheck("bt", "main.cpp", "-check-prefix=FUNC7-BT") + // FUNC7-BT: func7 + // FUNC7-BT-NEXT: [inlined] func8_inlined + // FUNC7-BT-NEXT: [inlined] func9_inlined + // FUNC7-BT-NEXT: func10 + use(x); + + // Destroy 'x' in the current frame. + DESTROY_RSI; + + //% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC7-EXPR-FAIL", expect_cmd_failure=True) + // FUNC7-EXPR-FAIL: couldn't get the value of variable x: variable not available + + ++sink; + + // Destroy 'sink' in the current frame. + DESTROY_RBX; + + //% self.filecheck("expr sink", "main.cpp", "-check-prefix=FUNC7-EXPR") + // FUNC7-EXPR: ${{.*}} = 4 +} + +__attribute__((always_inline)) +void func8_inlined(int &sink, int x) { + func7(sink, x); +} + +__attribute__((always_inline)) +void func9_inlined(int &sink, int x) { + func8_inlined(sink, x); +} + +__attribute__((noinline, disable_tail_calls)) +void func10(int &sink, int x) { + func9_inlined(sink, x); +} + +__attribute__((noinline)) +void func11_tailcalled(int &sink, int x) { + //% self.filecheck("bt", "main.cpp", "-check-prefix=FUNC11-BT") + // FUNC11-BT: func11_tailcalled{{.*}} + // FUNC11-BT-NEXT: func12{{.*}} [artificial] + use(x); + + // Destroy 'x' in the current frame. + DESTROY_RSI; + + //% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC11-EXPR-FAIL", expect_cmd_failure=True) + // FUNC11-EXPR-FAIL: couldn't get the value of variable x: variable not available + + ++sink; + + // Destroy 'sink' in the current frame. + DESTROY_RBX; + + //% self.filecheck("expr sink", "main.cpp", "-check-prefix=FUNC11-EXPR") + // FUNC11-EXPR: ${{.*}} = 5 +} + +__attribute__((noinline)) +void func12(int &sink, int x) { + func11_tailcalled(sink, x); +} + +__attribute__((noinline)) +void func13(int &sink, int x) { + //% self.filecheck("bt", "main.cpp", "-check-prefix=FUNC13-BT") + // FUNC13-BT: func13{{.*}} + // FUNC13-BT-NEXT: func14{{.*}} + use(x); + + // Destroy 'x' in the current frame. + DESTROY_RSI; + + //% self.filecheck("expr x", "main.cpp", "-check-prefix=FUNC13-EXPR-FAIL", expect_cmd_failure=True) + // FUNC13-EXPR-FAIL: couldn't get the value of variable x: variable not available + + use(sink); + + // Destroy 'sink' in the current frame. + DESTROY_RBX; + + //% self.filecheck("expr sink", "main.cpp", "-check-prefix=FUNC13-EXPR") + // FUNC13-EXPR: ${{.*}} = 5 +} + +__attribute__((noinline, disable_tail_calls)) +void func14(int &sink, void (*target_no_tailcall)(int &, int)) { + // Move the call target into a register that won't get clobbered. Do this + // by calling the same indirect target twice, and hoping that regalloc is + // 'smart' enough to stash the call target in a non-clobbered register. + // + // llvm.org/PR43926 tracks work in the compiler to emit call targets which + // describe non-clobbered values. + target_no_tailcall(sink, 123); + target_no_tailcall(sink, 123); +} + +__attribute__((disable_tail_calls)) +int main() { + int sink = 0; + S1 s1; + + // Test location dumping for DW_OP_entry_value. + func1(sink, 123); + + // Test evaluation of "DW_OP_constu" in the parent frame. + func2(sink, 123); + + // Test evaluation of "DW_OP_fbreg -24, DW_OP_deref" in the parent frame. + // Disabled for now, see: llvm.org/PR43343 +#if 0 + func3(sink, s1.field2); +#endif + + // The sequences `main -> func4 -> func{5,6}_amb -> sink` are both plausible. + // Test that lldb doesn't attempt to guess which one occurred: entry value + // evaluation should fail. + func6(sink, 123); + + // Test that evaluation can "see through" inlining. + func10(sink, 123); + + // Test that evaluation can "see through" tail calls. + func12(sink, 123); + + // Test that evaluation can "see through" an indirect tail call. + func14(sink, func13); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py new file mode 100644 index 00000000000..5c21622d03d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py @@ -0,0 +1,50 @@ +""" +Test some lldb command abbreviations. +""" + + +import lldb +import os +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestPaths(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_paths(self): + '''Test to make sure no file names are set in the lldb.SBFileSpec objects returned by lldb.SBHostOS.GetLLDBPath() for paths that are directories''' + dir_path_types = [lldb.ePathTypeLLDBShlibDir, + lldb.ePathTypeSupportExecutableDir, + lldb.ePathTypeHeaderDir, + lldb.ePathTypePythonDir, + lldb.ePathTypeLLDBSystemPlugins, + lldb.ePathTypeLLDBUserPlugins, + lldb.ePathTypeLLDBTempSystemDir, + lldb.ePathTypeClangDir] + + for path_type in dir_path_types: + f = lldb.SBHostOS.GetLLDBPath(path_type) + # No directory path types should have the filename set + self.assertTrue(f.GetFilename() is None) + + @no_debug_info_test + def test_directory_doesnt_end_with_slash(self): + current_directory_spec = lldb.SBFileSpec(os.path.curdir) + current_directory_string = current_directory_spec.GetDirectory() + self.assertNotEqual(current_directory_string[-1:], '/') + + @skipUnlessPlatform(["windows"]) + @no_debug_info_test + def test_windows_double_slash(self): + '''Test to check the path with double slash is handled correctly ''' + # Create a path and see if lldb gets the directory and file right + fspec = lldb.SBFileSpec("C:\\dummy1\\dummy2//unknown_file", True) + self.assertEqual( + os.path.normpath( + fspec.GetDirectory()), + os.path.normpath("C:/dummy1/dummy2")) + self.assertEqual(fspec.GetFilename(), "unknown_file") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/command_plugin/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/command_plugin/Makefile new file mode 100644 index 00000000000..3119c370784 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/command_plugin/Makefile @@ -0,0 +1,6 @@ +DYLIB_CXX_SOURCES := plugin.cpp +DYLIB_NAME := plugin +DYLIB_ONLY := YES +MAKE_DSYM := NO + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/command_plugin/TestPluginCommands.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/command_plugin/TestPluginCommands.py new file mode 100644 index 00000000000..e81d4076574 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/command_plugin/TestPluginCommands.py @@ -0,0 +1,78 @@ +""" +Test that plugins that load commands work correctly. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class PluginCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.generateSource('plugin.cpp') + + @skipIfNoSBHeaders + # Requires a compatible arch and platform to link against the host's built + # lldb lib. + @skipIfHostIncompatibleWithRemote + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + @no_debug_info_test + def test_load_plugin(self): + """Test that plugins that load commands work correctly.""" + + plugin_name = "plugin" + if sys.platform.startswith("darwin"): + plugin_lib_name = "lib%s.dylib" % plugin_name + else: + plugin_lib_name = "lib%s.so" % plugin_name + + # Invoke the library build rule. + self.buildLibrary("plugin.cpp", plugin_name) + + debugger = lldb.SBDebugger.Create() + + retobj = lldb.SBCommandReturnObject() + + retval = debugger.GetCommandInterpreter().HandleCommand( + "plugin load %s" % self.getBuildArtifact(plugin_lib_name), retobj) + + retobj.Clear() + + retval = debugger.GetCommandInterpreter().HandleCommand( + "plugin_loaded_command child abc def ghi", retobj) + + if self.TraceOn(): + print(retobj.GetOutput()) + + self.expect(retobj, substrs=['abc def ghi'], exe=False) + + retobj.Clear() + + # check that abbreviations work correctly in plugin commands. + retval = debugger.GetCommandInterpreter().HandleCommand( + "plugin_loaded_ ch abc def ghi", retobj) + + if self.TraceOn(): + print(retobj.GetOutput()) + + self.expect(retobj, substrs=['abc def ghi'], exe=False) + + @no_debug_info_test + def test_invalid_plugin_invocation(self): + self.expect("plugin load a b", + error=True, startstr="error: 'plugin load' requires one argument") + self.expect("plugin load", + error=True, startstr="error: 'plugin load' requires one argument") + + @no_debug_info_test + def test_invalid_plugin_target(self): + self.expect("plugin load ThisIsNotAValidPluginName", + error=True, startstr="error: no such file") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/command_plugin/plugin.cpp.template b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/command_plugin/plugin.cpp.template new file mode 100644 index 00000000000..1667c0d721e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/command_plugin/plugin.cpp.template @@ -0,0 +1,53 @@ +//===-- plugin.cpp -------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +/* +An example plugin for LLDB that provides a new foo command with a child subcommand +Compile this into a dylib foo.dylib and load by placing in appropriate locations on disk or +by typing plugin load foo.dylib at the LLDB command line +*/ + +%include_SB_APIs% + +namespace lldb { + bool + PluginInitialize (lldb::SBDebugger debugger); +} + +class ChildCommand : public lldb::SBCommandPluginInterface +{ +public: + virtual bool + DoExecute (lldb::SBDebugger debugger, + char** command, + lldb::SBCommandReturnObject &result) + { + if (command) + { + const char* arg = *command; + while (arg) + { + result.Printf("%s ",arg); + arg = *(++command); + } + result.Printf("\n"); + return true; + } + return false; + } + +}; + +bool +lldb::PluginInitialize (lldb::SBDebugger debugger) +{ + lldb::SBCommandInterpreter interpreter = debugger.GetCommandInterpreter(); + lldb::SBCommand foo = interpreter.AddMultiwordCommand("plugin_loaded_command",NULL); + foo.AddCommand("child",new ChildCommand(),"a child of plugin_loaded_command"); + return true; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/Makefile new file mode 100644 index 00000000000..c9319d6e688 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/Makefile @@ -0,0 +1,2 @@ +C_SOURCES := main.c +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py new file mode 100644 index 00000000000..5c4b42084c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py @@ -0,0 +1,195 @@ +""" +Test that the Python operating system plugin works correctly +""" + + + +import os +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class PluginPythonOSPlugin(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_python_os_plugin(self): + """Test that the Python operating system plugin works correctly""" + self.build() + self.run_python_os_funcionality() + + def run_python_os_step(self): + """Test that the Python operating system plugin works correctly when single stepping a virtual thread""" + self.build() + self.run_python_os_step() + + def verify_os_thread_registers(self, thread): + frame = thread.GetFrameAtIndex(0) + registers = frame.GetRegisters().GetValueAtIndex(0) + reg_value = thread.GetThreadID() + 1 + for reg in registers: + self.assertTrue( + reg.GetValueAsUnsigned() == reg_value, + "Verify the registers contains the correct value") + reg_value = reg_value + 1 + + def run_python_os_funcionality(self): + """Test that the Python operating system plugin works correctly""" + + # Set debugger into synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + python_os_plugin_path = os.path.join(self.getSourceDir(), + "operating_system.py") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set breakpoints inside and outside methods that take pointers to the + # containing struct. + lldbutil.run_break_set_by_source_regexp(self, "// Set breakpoint here") + + # Register our shared libraries for remote targets so they get + # automatically uploaded + arguments = None + environment = None + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + arguments, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Make sure there are no OS plug-in created thread when we first stop + # at our breakpoint in main + thread = process.GetThreadByID(0x111111111) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x111111111 before we load the python OS plug-in") + thread = process.GetThreadByID(0x222222222) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x222222222 before we load the python OS plug-in") + thread = process.GetThreadByID(0x333333333) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x333333333 before we load the python OS plug-in") + + # Now load the python OS plug-in which should update the thread list and we should have + # OS plug-in created threads with the IDs: 0x111111111, 0x222222222, + # 0x333333333 + command = "settings set target.process.python-os-plugin-path '%s'" % python_os_plugin_path + self.dbg.HandleCommand(command) + + # Verify our OS plug-in threads showed up + thread = process.GetThreadByID(0x111111111) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x111111111 after we load the python OS plug-in") + self.verify_os_thread_registers(thread) + thread = process.GetThreadByID(0x222222222) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x222222222 after we load the python OS plug-in") + self.verify_os_thread_registers(thread) + thread = process.GetThreadByID(0x333333333) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x333333333 after we load the python OS plug-in") + self.verify_os_thread_registers(thread) + + # Now clear the OS plug-in path to make the OS plug-in created threads + # dissappear + self.dbg.HandleCommand( + "settings clear target.process.python-os-plugin-path") + + # Verify the threads are gone after unloading the python OS plug-in + thread = process.GetThreadByID(0x111111111) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x111111111 after we unload the python OS plug-in") + thread = process.GetThreadByID(0x222222222) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x222222222 after we unload the python OS plug-in") + thread = process.GetThreadByID(0x333333333) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x333333333 after we unload the python OS plug-in") + + def run_python_os_step(self): + """Test that the Python operating system plugin works correctly and allows single stepping of a virtual thread that is backed by a real thread""" + + # Set debugger into synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + python_os_plugin_path = os.path.join(self.getSourceDir(), + "operating_system2.py") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set breakpoints inside and outside methods that take pointers to the + # containing struct. + lldbutil.run_break_set_by_source_regexp(self, "// Set breakpoint here") + + # Register our shared libraries for remote targets so they get + # automatically uploaded + arguments = None + environment = None + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + arguments, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Make sure there are no OS plug-in created thread when we first stop + # at our breakpoint in main + thread = process.GetThreadByID(0x111111111) + self.assertFalse( + thread.IsValid(), + "Make sure there is no thread 0x111111111 before we load the python OS plug-in") + + # Now load the python OS plug-in which should update the thread list and we should have + # OS plug-in created threads with the IDs: 0x111111111, 0x222222222, + # 0x333333333 + command = "settings set target.process.python-os-plugin-path '%s'" % python_os_plugin_path + self.dbg.HandleCommand(command) + + # Verify our OS plug-in threads showed up + thread = process.GetThreadByID(0x111111111) + self.assertTrue( + thread.IsValid(), + "Make sure there is a thread 0x111111111 after we load the python OS plug-in") + + frame = thread.GetFrameAtIndex(0) + self.assertTrue( + frame.IsValid(), + "Make sure we get a frame from thread 0x111111111") + line_entry = frame.GetLineEntry() + + self.assertTrue( + line_entry.GetFileSpec().GetFilename() == 'main.c', + "Make sure we stopped on line 5 in main.c") + self.assertTrue( + line_entry.GetLine() == 5, + "Make sure we stopped on line 5 in main.c") + + # Now single step thread 0x111111111 and make sure it does what we need + # it to + thread.StepOver() + + frame = thread.GetFrameAtIndex(0) + self.assertTrue( + frame.IsValid(), + "Make sure we get a frame from thread 0x111111111") + line_entry = frame.GetLineEntry() + + self.assertTrue( + line_entry.GetFileSpec().GetFilename() == 'main.c', + "Make sure we stepped from line 5 to line 6 in main.c") + self.assertTrue(line_entry.GetLine() == 6, + "Make sure we stepped from line 5 to line 6 in main.c") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/main.c new file mode 100644 index 00000000000..faa6dd58ecd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/main.c @@ -0,0 +1,7 @@ +#include <stdio.h> + +int main (int argc, char const *argv[], char const *envp[]) +{ + puts("stop here"); // Set breakpoint here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py new file mode 100644 index 00000000000..394c24b4a88 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py @@ -0,0 +1,128 @@ +#!/usr/bin/python + +import lldb +import struct + + +class OperatingSystemPlugIn(object): + """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class""" + + def __init__(self, process): + '''Initialization needs a valid.SBProcess object. + + This plug-in will get created after a live process is valid and has stopped for the + first time.''' + self.process = None + self.registers = None + self.threads = None + if isinstance(process, lldb.SBProcess) and process.IsValid(): + self.process = process + self.threads = None # Will be an dictionary containing info for each thread + + def get_target(self): + # NOTE: Don't use "lldb.target" when trying to get your target as the "lldb.target" + # tracks the current target in the LLDB command interpreter which isn't the + # correct thing to use for this plug-in. + return self.process.target + + def create_thread(self, tid, context): + if tid == 0x444444444: + thread_info = { + 'tid': tid, + 'name': 'four', + 'queue': 'queue4', + 'state': 'stopped', + 'stop_reason': 'none'} + self.threads.append(thread_info) + return thread_info + return None + + def get_thread_info(self): + if not self.threads: + # The sample dictionary below shows the values that can be returned for a thread + # tid => thread ID (mandatory) + # name => thread name (optional key/value pair) + # queue => thread dispatch queue name (optional key/value pair) + # state => thred state (mandatory, set to 'stopped' for now) + # stop_reason => thread stop reason. (mandatory, usually set to 'none') + # Possible values include: + # 'breakpoint' if the thread is stopped at a breakpoint + # 'none' thread is just stopped because the process is stopped + # 'trace' the thread just single stepped + # The usual value for this while threads are in memory is 'none' + # register_data_addr => the address of the register data in memory (optional key/value pair) + # Specifying this key/value pair for a thread will avoid a call to get_register_data() + # and can be used when your registers are in a thread context structure that is contiguous + # in memory. Don't specify this if your register layout in memory doesn't match the layout + # described by the dictionary returned from a call to the + # get_register_info() method. + self.threads = [{'tid': 0x111111111, + 'name': 'one', + 'queue': 'queue1', + 'state': 'stopped', + 'stop_reason': 'breakpoint'}, + {'tid': 0x222222222, + 'name': 'two', + 'queue': 'queue2', + 'state': 'stopped', + 'stop_reason': 'none'}, + {'tid': 0x333333333, + 'name': 'three', + 'queue': 'queue3', + 'state': 'stopped', + 'stop_reason': 'trace'}] + return self.threads + + def get_register_info(self): + if self.registers is None: + self.registers = dict() + self.registers['sets'] = ['GPR'] + self.registers['registers'] = [ + {'name': 'rax', 'bitsize': 64, 'offset': 0, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 0, 'dwarf': 0}, + {'name': 'rbx', 'bitsize': 64, 'offset': 8, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 3, 'dwarf': 3}, + {'name': 'rcx', 'bitsize': 64, 'offset': 16, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 2, 'dwarf': 2, 'generic': 'arg4', 'alt-name': 'arg4', }, + {'name': 'rdx', 'bitsize': 64, 'offset': 24, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 1, 'dwarf': 1, 'generic': 'arg3', 'alt-name': 'arg3', }, + {'name': 'rdi', 'bitsize': 64, 'offset': 32, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 5, 'dwarf': 5, 'generic': 'arg1', 'alt-name': 'arg1', }, + {'name': 'rsi', 'bitsize': 64, 'offset': 40, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 4, 'dwarf': 4, 'generic': 'arg2', 'alt-name': 'arg2', }, + {'name': 'rbp', 'bitsize': 64, 'offset': 48, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 6, 'dwarf': 6, 'generic': 'fp', 'alt-name': 'fp', }, + {'name': 'rsp', 'bitsize': 64, 'offset': 56, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 7, 'dwarf': 7, 'generic': 'sp', 'alt-name': 'sp', }, + {'name': 'r8', 'bitsize': 64, 'offset': 64, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 8, 'dwarf': 8, 'generic': 'arg5', 'alt-name': 'arg5', }, + {'name': 'r9', 'bitsize': 64, 'offset': 72, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 9, 'dwarf': 9, 'generic': 'arg6', 'alt-name': 'arg6', }, + {'name': 'r10', 'bitsize': 64, 'offset': 80, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 10, 'dwarf': 10}, + {'name': 'r11', 'bitsize': 64, 'offset': 88, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 11, 'dwarf': 11}, + {'name': 'r12', 'bitsize': 64, 'offset': 96, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 12, 'dwarf': 12}, + {'name': 'r13', 'bitsize': 64, 'offset': 104, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 13, 'dwarf': 13}, + {'name': 'r14', 'bitsize': 64, 'offset': 112, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 14, 'dwarf': 14}, + {'name': 'r15', 'bitsize': 64, 'offset': 120, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 15, 'dwarf': 15}, + {'name': 'rip', 'bitsize': 64, 'offset': 128, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 16, 'dwarf': 16, 'generic': 'pc', 'alt-name': 'pc'}, + {'name': 'rflags', 'bitsize': 64, 'offset': 136, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'generic': 'flags', 'alt-name': 'flags'}, + {'name': 'cs', 'bitsize': 64, 'offset': 144, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + {'name': 'fs', 'bitsize': 64, 'offset': 152, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + {'name': 'gs', 'bitsize': 64, 'offset': 160, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + ] + return self.registers + + def get_register_data(self, tid): + return struct.pack( + '21Q', + tid + 1, + tid + 2, + tid + 3, + tid + 4, + tid + 5, + tid + 6, + tid + 7, + tid + 8, + tid + 9, + tid + 10, + tid + 11, + tid + 12, + tid + 13, + tid + 14, + tid + 15, + tid + 16, + tid + 17, + tid + 18, + tid + 19, + tid + 20, + tid + 21) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py new file mode 100644 index 00000000000..438538ca922 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py @@ -0,0 +1,116 @@ +#!/usr/bin/python + +import lldb +import struct + + +class OperatingSystemPlugIn(object): + """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class""" + + def __init__(self, process): + '''Initialization needs a valid.SBProcess object. + + This plug-in will get created after a live process is valid and has stopped for the + first time.''' + self.process = None + self.registers = None + self.threads = None + if isinstance(process, lldb.SBProcess) and process.IsValid(): + self.process = process + self.threads = None # Will be an dictionary containing info for each thread + + def get_target(self): + # NOTE: Don't use "lldb.target" when trying to get your target as the "lldb.target" + # tracks the current target in the LLDB command interpreter which isn't the + # correct thing to use for this plug-in. + return self.process.target + + def create_thread(self, tid, context): + if tid == 0x444444444: + thread_info = { + 'tid': tid, + 'name': 'four', + 'queue': 'queue4', + 'state': 'stopped', + 'stop_reason': 'none'} + self.threads.append(thread_info) + return thread_info + return None + + def get_thread_info(self): + if not self.threads: + # The sample dictionary below shows the values that can be returned for a thread + # tid => thread ID (mandatory) + # name => thread name (optional key/value pair) + # queue => thread dispatch queue name (optional key/value pair) + # state => thred state (mandatory, set to 'stopped' for now) + # stop_reason => thread stop reason. (mandatory, usually set to 'none') + # Possible values include: + # 'breakpoint' if the thread is stopped at a breakpoint + # 'none' thread is just stopped because the process is stopped + # 'trace' the thread just single stepped + # The usual value for this while threads are in memory is 'none' + # register_data_addr => the address of the register data in memory (optional key/value pair) + # Specifying this key/value pair for a thread will avoid a call to get_register_data() + # and can be used when your registers are in a thread context structure that is contiguous + # in memory. Don't specify this if your register layout in memory doesn't match the layout + # described by the dictionary returned from a call to the + # get_register_info() method. + self.threads = [ + {'tid': 0x111111111, 'core': 0} + ] + return self.threads + + def get_register_info(self): + if self.registers is None: + self.registers = dict() + self.registers['sets'] = ['GPR'] + self.registers['registers'] = [ + {'name': 'rax', 'bitsize': 64, 'offset': 0, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 0, 'dwarf': 0}, + {'name': 'rbx', 'bitsize': 64, 'offset': 8, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 3, 'dwarf': 3}, + {'name': 'rcx', 'bitsize': 64, 'offset': 16, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 2, 'dwarf': 2, 'generic': 'arg4', 'alt-name': 'arg4', }, + {'name': 'rdx', 'bitsize': 64, 'offset': 24, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 1, 'dwarf': 1, 'generic': 'arg3', 'alt-name': 'arg3', }, + {'name': 'rdi', 'bitsize': 64, 'offset': 32, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 5, 'dwarf': 5, 'generic': 'arg1', 'alt-name': 'arg1', }, + {'name': 'rsi', 'bitsize': 64, 'offset': 40, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 4, 'dwarf': 4, 'generic': 'arg2', 'alt-name': 'arg2', }, + {'name': 'rbp', 'bitsize': 64, 'offset': 48, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 6, 'dwarf': 6, 'generic': 'fp', 'alt-name': 'fp', }, + {'name': 'rsp', 'bitsize': 64, 'offset': 56, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 7, 'dwarf': 7, 'generic': 'sp', 'alt-name': 'sp', }, + {'name': 'r8', 'bitsize': 64, 'offset': 64, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 8, 'dwarf': 8, 'generic': 'arg5', 'alt-name': 'arg5', }, + {'name': 'r9', 'bitsize': 64, 'offset': 72, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 9, 'dwarf': 9, 'generic': 'arg6', 'alt-name': 'arg6', }, + {'name': 'r10', 'bitsize': 64, 'offset': 80, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 10, 'dwarf': 10}, + {'name': 'r11', 'bitsize': 64, 'offset': 88, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 11, 'dwarf': 11}, + {'name': 'r12', 'bitsize': 64, 'offset': 96, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 12, 'dwarf': 12}, + {'name': 'r13', 'bitsize': 64, 'offset': 104, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 13, 'dwarf': 13}, + {'name': 'r14', 'bitsize': 64, 'offset': 112, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 14, 'dwarf': 14}, + {'name': 'r15', 'bitsize': 64, 'offset': 120, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 15, 'dwarf': 15}, + {'name': 'rip', 'bitsize': 64, 'offset': 128, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 16, 'dwarf': 16, 'generic': 'pc', 'alt-name': 'pc'}, + {'name': 'rflags', 'bitsize': 64, 'offset': 136, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'generic': 'flags', 'alt-name': 'flags'}, + {'name': 'cs', 'bitsize': 64, 'offset': 144, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + {'name': 'fs', 'bitsize': 64, 'offset': 152, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + {'name': 'gs', 'bitsize': 64, 'offset': 160, 'encoding': 'uint', 'format': 'hex', 'set': 0}, + ] + return self.registers + + def get_register_data(self, tid): + return struct.pack( + '21Q', + tid + 1, + tid + 2, + tid + 3, + tid + 4, + tid + 5, + tid + 6, + tid + 7, + tid + 8, + tid + 9, + tid + 10, + tid + 11, + tid + 12, + tid + 13, + tid + 14, + tid + 15, + tid + 16, + tid + 17, + tid + 18, + tid + 19, + tid + 20, + tid + 21) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/TestLinuxCore.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/TestLinuxCore.py new file mode 100644 index 00000000000..c2746bf1a80 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/TestLinuxCore.py @@ -0,0 +1,379 @@ +""" +Test basics of linux core file debugging. +""" + +from __future__ import division, print_function + +import shutil +import struct +import os + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LinuxCoreTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + _i386_pid = 32306 + _x86_64_pid = 32259 + _s390x_pid = 1045 + _mips64_n64_pid = 25619 + _mips64_n32_pid = 3670 + _mips_o32_pid = 3532 + _ppc64le_pid = 28147 + + _i386_regions = 4 + _x86_64_regions = 5 + _s390x_regions = 2 + _mips_regions = 5 + _ppc64le_regions = 2 + + def setUp(self): + super(LinuxCoreTestCase, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(LinuxCoreTestCase, self).tearDown() + + @skipIf(triple='^mips') + @skipIfLLVMTargetMissing("X86") + def test_i386(self): + """Test that lldb can read the process information from an i386 linux core file.""" + self.do_test("linux-i386", self._i386_pid, self._i386_regions, "a.out") + + @skipIfLLVMTargetMissing("Mips") + def test_mips_o32(self): + """Test that lldb can read the process information from an MIPS O32 linux core file.""" + self.do_test("linux-mipsel-gnuabio32", self._mips_o32_pid, + self._mips_regions, "linux-mipsel-gn") + + @skipIfLLVMTargetMissing("Mips") + def test_mips_n32(self): + """Test that lldb can read the process information from an MIPS N32 linux core file """ + self.do_test("linux-mips64el-gnuabin32", self._mips64_n32_pid, + self._mips_regions, "linux-mips64el-") + + @skipIfLLVMTargetMissing("Mips") + def test_mips_n64(self): + """Test that lldb can read the process information from an MIPS N64 linux core file """ + self.do_test("linux-mips64el-gnuabi64", self._mips64_n64_pid, + self._mips_regions, "linux-mips64el-") + + @skipIf(triple='^mips') + @skipIfLLVMTargetMissing("PowerPC") + def test_ppc64le(self): + """Test that lldb can read the process information from an ppc64le linux core file.""" + self.do_test("linux-ppc64le", self._ppc64le_pid, self._ppc64le_regions, + "linux-ppc64le.ou") + + @skipIf(triple='^mips') + @skipIfLLVMTargetMissing("X86") + def test_x86_64(self): + """Test that lldb can read the process information from an x86_64 linux core file.""" + self.do_test("linux-x86_64", self._x86_64_pid, self._x86_64_regions, + "a.out") + + @skipIf(triple='^mips') + @skipIfLLVMTargetMissing("SystemZ") + def test_s390x(self): + """Test that lldb can read the process information from an s390x linux core file.""" + self.do_test("linux-s390x", self._s390x_pid, self._s390x_regions, + "a.out") + + @skipIf(triple='^mips') + @skipIfLLVMTargetMissing("X86") + def test_same_pid_running(self): + """Test that we read the information from the core correctly even if we have a running + process with the same PID around""" + exe_file = self.getBuildArtifact("linux-x86_64-pid.out") + core_file = self.getBuildArtifact("linux-x86_64-pid.core") + shutil.copyfile("linux-x86_64.out", exe_file) + shutil.copyfile("linux-x86_64.core", core_file) + with open(core_file, "r+b") as f: + # These are offsets into the NT_PRSTATUS and NT_PRPSINFO structures in the note + # segment of the core file. If you update the file, these offsets may need updating + # as well. (Notes can be viewed with readelf --notes.) + for pid_offset in [0x1c4, 0x320]: + f.seek(pid_offset) + self.assertEqual( + struct.unpack( + "<I", + f.read(4))[0], + self._x86_64_pid) + + # We insert our own pid, and make sure the test still + # works. + f.seek(pid_offset) + f.write(struct.pack("<I", os.getpid())) + self.do_test(self.getBuildArtifact("linux-x86_64-pid"), os.getpid(), + self._x86_64_regions, "a.out") + + @skipIf(triple='^mips') + @skipIfLLVMTargetMissing("X86") + def test_two_cores_same_pid(self): + """Test that we handle the situation if we have two core files with the same PID + around""" + alttarget = self.dbg.CreateTarget("altmain.out") + altprocess = alttarget.LoadCore("altmain.core") + self.assertTrue(altprocess, PROCESS_IS_VALID) + self.assertEqual(altprocess.GetNumThreads(), 1) + self.assertEqual(altprocess.GetProcessID(), self._x86_64_pid) + + altframe = altprocess.GetSelectedThread().GetFrameAtIndex(0) + self.assertEqual(altframe.GetFunctionName(), "_start") + self.assertEqual( + altframe.GetLineEntry().GetLine(), + line_number( + "altmain.c", + "Frame _start")) + + error = lldb.SBError() + F = altprocess.ReadCStringFromMemory( + altframe.FindVariable("F").GetValueAsUnsigned(), 256, error) + self.assertTrue(error.Success()) + self.assertEqual(F, "_start") + + # without destroying this process, run the test which opens another core file with the + # same pid + self.do_test("linux-x86_64", self._x86_64_pid, self._x86_64_regions, + "a.out") + + @skipIf(triple='^mips') + @skipIfLLVMTargetMissing("X86") + def test_FPR_SSE(self): + # check x86_64 core file + target = self.dbg.CreateTarget(None) + self.assertTrue(target, VALID_TARGET) + process = target.LoadCore("linux-fpr_sse_x86_64.core") + + values = {} + values["fctrl"] = "0x037f" + values["fstat"] = "0x0000" + values["ftag"] = "0x00ff" + values["fop"] = "0x0000" + values["fiseg"] = "0x00000000" + values["fioff"] = "0x0040011e" + values["foseg"] = "0x00000000" + values["fooff"] = "0x00000000" + values["mxcsr"] = "0x00001f80" + values["mxcsrmask"] = "0x0000ffff" + values["st0"] = "{0x99 0xf7 0xcf 0xfb 0x84 0x9a 0x20 0x9a 0xfd 0x3f}" + values["st1"] = "{0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x80 0xff 0x3f}" + values["st2"] = "{0xfe 0x8a 0x1b 0xcd 0x4b 0x78 0x9a 0xd4 0x00 0x40}" + values["st3"] = "{0xac 0x79 0xcf 0xd1 0xf7 0x17 0x72 0xb1 0xfe 0x3f}" + values["st4"] = "{0xbc 0xf0 0x17 0x5c 0x29 0x3b 0xaa 0xb8 0xff 0x3f}" + values["st5"] = "{0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x80 0xff 0x3f}" + values["st6"] = "{0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00}" + values["st7"] = "{0x35 0xc2 0x68 0x21 0xa2 0xda 0x0f 0xc9 0x00 0x40}" + values["xmm0"] = "{0x29 0x31 0x64 0x46 0x29 0x31 0x64 0x46 0x29 0x31 0x64 0x46 0x29 0x31 0x64 0x46}" + values["xmm1"] = "{0x9c 0xed 0x86 0x64 0x9c 0xed 0x86 0x64 0x9c 0xed 0x86 0x64 0x9c 0xed 0x86 0x64}" + values["xmm2"] = "{0x07 0xc2 0x1f 0xd7 0x07 0xc2 0x1f 0xd7 0x07 0xc2 0x1f 0xd7 0x07 0xc2 0x1f 0xd7}" + values["xmm3"] = "{0xa2 0x20 0x48 0x25 0xa2 0x20 0x48 0x25 0xa2 0x20 0x48 0x25 0xa2 0x20 0x48 0x25}" + values["xmm4"] = "{0xeb 0x5a 0xa8 0xc4 0xeb 0x5a 0xa8 0xc4 0xeb 0x5a 0xa8 0xc4 0xeb 0x5a 0xa8 0xc4}" + values["xmm5"] = "{0x49 0x41 0x20 0x0b 0x49 0x41 0x20 0x0b 0x49 0x41 0x20 0x0b 0x49 0x41 0x20 0x0b}" + values["xmm6"] = "{0xf8 0xf1 0x8b 0x4f 0xf8 0xf1 0x8b 0x4f 0xf8 0xf1 0x8b 0x4f 0xf8 0xf1 0x8b 0x4f}" + values["xmm7"] = "{0x13 0xf1 0x30 0xcd 0x13 0xf1 0x30 0xcd 0x13 0xf1 0x30 0xcd 0x13 0xf1 0x30 0xcd}" + + for regname, value in values.items(): + self.expect("register read {}".format(regname), substrs=["{} = {}".format(regname, value)]) + + + # now check i386 core file + target = self.dbg.CreateTarget(None) + self.assertTrue(target, VALID_TARGET) + process = target.LoadCore("linux-fpr_sse_i386.core") + + values["fioff"] = "0x080480cc" + + for regname, value in values.items(): + self.expect("register read {}".format(regname), substrs=["{} = {}".format(regname, value)]) + + @skipIf(triple='^mips') + @skipIfLLVMTargetMissing("X86") + def test_i386_sysroot(self): + """Test that lldb can find the exe for an i386 linux core file using the sysroot.""" + + # Copy linux-i386.out to tmp_sysroot/home/labath/test/a.out (since it was compiled as + # /home/labath/test/a.out) + tmp_sysroot = os.path.join(self.getBuildDir(), "lldb_i386_mock_sysroot") + executable = os.path.join(tmp_sysroot, "home", "labath", "test", "a.out") + lldbutil.mkdir_p(os.path.dirname(executable)) + shutil.copyfile("linux-i386.out", executable) + + # Set sysroot and load core + self.runCmd("platform select remote-linux --sysroot '%s'" % tmp_sysroot) + target = self.dbg.CreateTarget(None) + self.assertTrue(target, VALID_TARGET) + process = target.LoadCore("linux-i386.core") + + # Check that we found a.out from the sysroot + self.check_all(process, self._i386_pid, self._i386_regions, "a.out") + + self.dbg.DeleteTarget(target) + + @skipIf(triple='^mips') + @skipIfLLVMTargetMissing("ARM") + def test_arm_core(self): + # check 32 bit ARM core file + target = self.dbg.CreateTarget(None) + self.assertTrue(target, VALID_TARGET) + process = target.LoadCore("linux-arm.core") + + values = {} + values["r0"] = "0x00000000" + values["r1"] = "0x00000001" + values["r2"] = "0x00000002" + values["r3"] = "0x00000003" + values["r4"] = "0x00000004" + values["r5"] = "0x00000005" + values["r6"] = "0x00000006" + values["r7"] = "0x00000007" + values["r8"] = "0x00000008" + values["r9"] = "0x00000009" + values["r10"] = "0x0000000a" + values["r11"] = "0x0000000b" + values["r12"] = "0x0000000c" + values["sp"] = "0x0000000d" + values["lr"] = "0x0000000e" + values["pc"] = "0x0000000f" + values["cpsr"] = "0x00000010" + for regname, value in values.items(): + self.expect("register read {}".format(regname), substrs=["{} = {}".format(regname, value)]) + + def check_memory_regions(self, process, region_count): + region_list = process.GetMemoryRegions() + self.assertEqual(region_list.GetSize(), region_count) + + region = lldb.SBMemoryRegionInfo() + + # Check we have the right number of regions. + self.assertEqual(region_list.GetSize(), region_count) + + # Check that getting a region beyond the last in the list fails. + self.assertFalse( + region_list.GetMemoryRegionAtIndex( + region_count, region)) + + # Check each region is valid. + for i in range(region_list.GetSize()): + # Check we can actually get this region. + self.assertTrue(region_list.GetMemoryRegionAtIndex(i, region)) + + # Every region in the list should be mapped. + self.assertTrue(region.IsMapped()) + + # Test the address at the start of a region returns it's enclosing + # region. + begin_address = region.GetRegionBase() + region_at_begin = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo(begin_address, region_at_begin) + self.assertEqual(region, region_at_begin) + + # Test an address in the middle of a region returns it's enclosing + # region. + middle_address = (region.GetRegionBase() + + region.GetRegionEnd()) // 2 + region_at_middle = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo( + middle_address, region_at_middle) + self.assertEqual(region, region_at_middle) + + # Test the address at the end of a region returns it's enclosing + # region. + end_address = region.GetRegionEnd() - 1 + region_at_end = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo(end_address, region_at_end) + self.assertEqual(region, region_at_end) + + # Check that quering the end address does not return this region but + # the next one. + next_region = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo( + region.GetRegionEnd(), next_region) + self.assertNotEqual(region, next_region) + self.assertEqual( + region.GetRegionEnd(), + next_region.GetRegionBase()) + + # Check that query beyond the last region returns an unmapped region + # that ends at LLDB_INVALID_ADDRESS + last_region = lldb.SBMemoryRegionInfo() + region_list.GetMemoryRegionAtIndex(region_count - 1, last_region) + end_region = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo( + last_region.GetRegionEnd(), end_region) + self.assertFalse(end_region.IsMapped()) + self.assertEqual( + last_region.GetRegionEnd(), + end_region.GetRegionBase()) + self.assertEqual(end_region.GetRegionEnd(), lldb.LLDB_INVALID_ADDRESS) + + def check_state(self, process): + with open(os.devnull) as devnul: + # sanitize test output + self.dbg.SetOutputFileHandle(devnul, False) + self.dbg.SetErrorFileHandle(devnul, False) + + self.assertTrue(process.is_stopped) + + # Process.Continue + error = process.Continue() + self.assertFalse(error.Success()) + self.assertTrue(process.is_stopped) + + # Thread.StepOut + thread = process.GetSelectedThread() + thread.StepOut() + self.assertTrue(process.is_stopped) + + # command line + self.dbg.HandleCommand('s') + self.assertTrue(process.is_stopped) + self.dbg.HandleCommand('c') + self.assertTrue(process.is_stopped) + + # restore file handles + self.dbg.SetOutputFileHandle(None, False) + self.dbg.SetErrorFileHandle(None, False) + + def check_stack(self, process, pid, thread_name): + thread = process.GetSelectedThread() + self.assertTrue(thread) + self.assertEqual(thread.GetThreadID(), pid) + self.assertEqual(thread.GetName(), thread_name) + backtrace = ["bar", "foo", "_start"] + self.assertEqual(thread.GetNumFrames(), len(backtrace)) + for i in range(len(backtrace)): + frame = thread.GetFrameAtIndex(i) + self.assertTrue(frame) + self.assertEqual(frame.GetFunctionName(), backtrace[i]) + self.assertEqual(frame.GetLineEntry().GetLine(), + line_number("main.c", "Frame " + backtrace[i])) + self.assertEqual( + frame.FindVariable("F").GetValueAsUnsigned(), ord( + backtrace[i][0])) + + def check_all(self, process, pid, region_count, thread_name): + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetNumThreads(), 1) + self.assertEqual(process.GetProcessID(), pid) + + self.check_state(process) + + self.check_stack(process, pid, thread_name) + + self.check_memory_regions(process, region_count) + + def do_test(self, filename, pid, region_count, thread_name): + target = self.dbg.CreateTarget(filename + ".out") + process = target.LoadCore(filename + ".core") + + self.check_all(process, pid, region_count, thread_name) + + self.dbg.DeleteTarget(target) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/altmain.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/altmain.c new file mode 100644 index 00000000000..da49a00996e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/altmain.c @@ -0,0 +1,6 @@ +void _start(void) +{ + const char *F = "_start"; + char *boom = (char *)0; + *boom = 47; // Frame _start +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/altmain.out b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/altmain.out Binary files differnew file mode 100755 index 00000000000..2fddf3e8f80 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/altmain.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/fpr_sse.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/fpr_sse.cpp new file mode 100644 index 00000000000..e6826fc7a09 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/fpr_sse.cpp @@ -0,0 +1,38 @@ +// fpr_sse_x86_64.core was generated with: +// ./make-core.sh fpr_sse.cpp +// +// fpr_sse_i386.core was generated with: +// export CFLAGS=-m32 +// ./make-core.sh fpr_sse.cpp + +void _start(void) { + __asm__("fldpi;" + "fldz;" + "fld1;" + "fldl2e;" + "fldln2;" + "fldl2t;" + "fld1;" + "fldlg2;"); + + unsigned int values[8] = { + 0x46643129, 0x6486ed9c, 0xd71fc207, 0x254820a2, + 0xc4a85aeb, 0x0b204149, 0x4f8bf1f8, 0xcd30f113, + }; + + __asm__("vbroadcastss %0, %%xmm0;" + "vbroadcastss %1, %%xmm1;" + "vbroadcastss %2, %%xmm2;" + "vbroadcastss %3, %%xmm3;" + "vbroadcastss %4, %%xmm4;" + "vbroadcastss %5, %%xmm5;" + "vbroadcastss %6, %%xmm6;" + "vbroadcastss %7, %%xmm7;" + + ::"m"(values[0]), + "m"(values[1]), "m"(values[2]), "m"(values[3]), "m"(values[4]), + "m"(values[5]), "m"(values[6]), "m"(values[7])); + + volatile int *a = 0; + *a = 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/TestGCore.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/TestGCore.py new file mode 100644 index 00000000000..ca863d25048 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/TestGCore.py @@ -0,0 +1,54 @@ +""" +Test signal reporting when debugging with linux core files. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class GCoreTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + def setUp(self): + super(GCoreTestCase, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(GCoreTestCase, self).tearDown() + + _i386_pid = 5586 + _x86_64_pid = 5669 + + @skipIf(oslist=['windows']) + @skipIf(triple='^mips') + def test_i386(self): + """Test that lldb can read the process information from an i386 linux core file.""" + self.do_test("linux-i386", self._i386_pid) + + @skipIf(oslist=['windows']) + @skipIf(triple='^mips') + def test_x86_64(self): + """Test that lldb can read the process information from an x86_64 linux core file.""" + self.do_test("linux-x86_64", self._x86_64_pid) + + def do_test(self, filename, pid): + target = self.dbg.CreateTarget("") + process = target.LoadCore(filename + ".core") + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetNumThreads(), 3) + self.assertEqual(process.GetProcessID(), pid) + + for thread in process: + reason = thread.GetStopReason() + self.assertEqual(reason, lldb.eStopReasonSignal) + signal = thread.GetStopReasonDataAtIndex(1) + # Check we got signal 19 (SIGSTOP) + self.assertEqual(signal, 19) + + self.dbg.DeleteTarget(target) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/main.cpp new file mode 100644 index 00000000000..a8e5f34d14e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/main.cpp @@ -0,0 +1,62 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test verifies the correct handling of child thread exits. + +#include "pseudo_barrier.h" +#include <thread> +#include <csignal> + +pseudo_barrier_t g_barrier1; +pseudo_barrier_t g_barrier2; + +void * +thread1 () +{ + // Synchronize with the main thread. + pseudo_barrier_wait(g_barrier1); + + // Synchronize with the main thread and thread2. + pseudo_barrier_wait(g_barrier2); + + // Return + return NULL; +} + +void * +thread2 () +{ + + // Synchronize with thread1 and the main thread. + pseudo_barrier_wait(g_barrier2); // Should not reach here. + + // Return + return NULL; +} + +int main () +{ + + pseudo_barrier_init(g_barrier1, 2); + pseudo_barrier_init(g_barrier2, 3); + + // Create a thread. + std::thread thread_1(thread1); + + // Wait for thread1 to start. + pseudo_barrier_wait(g_barrier1); + + // Wait for thread1 to start. + std::thread thread_2(thread2); + + // Thread 2 is waiting for another thread to reach the barrier. + // This should have for ever. (So we can run gcore against this process.) + thread_2.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/main.mk b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/main.mk new file mode 100755 index 00000000000..566938ca0cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/main.mk @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/make-core.sh b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/make-core.sh new file mode 100755 index 00000000000..b6979c7790d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/make-core.sh @@ -0,0 +1,56 @@ +#! /bin/sh + +linux_check_ptrace_scope() +{ + if grep -q '1' </proc/sys/kernel/yama/ptrace_scope; then + cat <<EOF +Your system prevents the use of PTRACE to attach to non-child processes. The core file +cannot be generated. Please reset /proc/sys/kernel/yama/ptrace_scope to 0 (requires root +privileges) to enable core generation via gcore. +EOF + exit 1 + fi +} + +set -e -x + +OS=$(uname -s) +if [ "$OS" = Linux ]; then + linux_check_ptrace_scope +fi + +rm -f a.out +make -f main.mk + +cat <<EOF +Executable file is in a.out. +Core file will be saved as core.<pid>. +EOF + +stack_size=`ulimit -s` + +# Decrease stack size to 16k => smaller core files. +# gcore won't run with the smaller stack +ulimit -Ss 16 + +core_dump_filter=`cat /proc/self/coredump_filter` +echo 0 > /proc/self/coredump_filter + +./a.out & + +pid=$! + +echo $core_dump_filter > /proc/self/coredump_filter + +# Reset stack size as so there's enough space to run gcore. +ulimit -s $stack_size + +echo "Sleeping for 5 seconds to wait for $pid" + +sleep 5 +echo "Taking core from process $pid" + +gcore -o core $pid + +echo "Killing process $pid" +kill -9 $pid diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-i386.out b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-i386.out Binary files differnew file mode 100755 index 00000000000..3cdd4eeca10 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-i386.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-mips64el-gnuabi64.out b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-mips64el-gnuabi64.out Binary files differnew file mode 100755 index 00000000000..a230aa4251a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-mips64el-gnuabi64.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-mips64el-gnuabin32.out b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-mips64el-gnuabin32.out Binary files differnew file mode 100755 index 00000000000..d1293a71a85 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-mips64el-gnuabin32.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-mipsel-gnuabio32.out b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-mipsel-gnuabio32.out Binary files differnew file mode 100755 index 00000000000..dc809c8da48 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-mipsel-gnuabio32.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-ppc64le.out b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-ppc64le.out Binary files differnew file mode 100755 index 00000000000..05c69fd291b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-ppc64le.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-s390x.out b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-s390x.out Binary files differnew file mode 100755 index 00000000000..640fbdc257d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-s390x.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-x86_64.out b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-x86_64.out Binary files differnew file mode 100755 index 00000000000..842402fd519 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/linux-x86_64.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/main.c new file mode 100644 index 00000000000..f5bde4171ca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/main.c @@ -0,0 +1,17 @@ +static void bar(char *boom) +{ + char F = 'b'; + *boom = 47; // Frame bar +} + +static void foo(char *boom, void (*boomer)(char *)) +{ + char F = 'f'; + boomer(boom); // Frame foo +} + +void _start(void) +{ + char F = '_'; + foo(0, bar); // Frame _start +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/make-core.sh b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/make-core.sh new file mode 100755 index 00000000000..9dd83f19c76 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/make-core.sh @@ -0,0 +1,61 @@ +#! /bin/sh + +linux_check_core_pattern() +{ + if grep -q '^|' </proc/sys/kernel/core_pattern; then + cat <<EOF +Your system uses a crash report tool ($(cat /proc/sys/kernel/core_pattern)). Core files +will not be generated. Please reset /proc/sys/kernel/core_pattern (requires root +privileges) to enable core generation. +EOF + exit 1 + fi +} + +OS=$(uname -s) +case "$OS" in +FreeBSD) + core_pattern=$(sysctl -n kern.corefile) + ;; +Linux) + core_pattern=$(cat /proc/sys/kernel/core_pattern) + ;; +*) + echo "OS $OS not supported" >&2 + exit 1 + ;; +esac + +set -e -x + +file=$1 +if [ -z "$file" ]; then + cat <<EOF +Please supply the main source file as the first argument. +EOF + exit 1 +fi + +if [ "$OS" = Linux ]; then + linux_check_core_pattern +fi + +ulimit -c 1000 +real_limit=$(ulimit -c) +if [ $real_limit -lt 100 ]; then + cat <<EOF +Unable to increase the core file limit. Core file may be truncated! +To fix this, increase HARD core file limit (ulimit -H -c 1000). This may require root +privileges. +EOF +fi + +${CC:-cc} -nostdlib -static -g $CFLAGS "$file" -o a.out + +cat <<EOF +Executable file is in a.out. +Core file will be saved according to pattern $core_pattern. +EOF + +ulimit -s 8 # Decrease stack size to 8k => smaller core files. +exec ./a.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/TestLinuxCoreThreads.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/TestLinuxCoreThreads.py new file mode 100644 index 00000000000..4be7ebe3122 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/TestLinuxCoreThreads.py @@ -0,0 +1,75 @@ +""" +Test signal reporting when debugging with linux core files. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LinuxCoreThreadsTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + super(LinuxCoreThreadsTestCase, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(LinuxCoreThreadsTestCase, self).tearDown() + + _i386_pid = 5193 + _x86_64_pid = 5222 + + # Thread id for the failing thread. + _i386_tid = 5195 + _x86_64_tid = 5250 + + @skipIf(oslist=['windows']) + @skipIf(triple='^mips') + def test_i386(self): + """Test that lldb can read the process information from an i386 linux core file.""" + self.do_test("linux-i386", self._i386_pid, self._i386_tid) + + @skipIf(oslist=['windows']) + @skipIf(triple='^mips') + def test_x86_64(self): + """Test that lldb can read the process information from an x86_64 linux core file.""" + self.do_test("linux-x86_64", self._x86_64_pid, self._x86_64_tid) + + def do_test(self, filename, pid, tid): + target = self.dbg.CreateTarget("") + process = target.LoadCore(filename + ".core") + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetNumThreads(), 3) + self.assertEqual(process.GetProcessID(), pid) + + for thread in process: + # Verify that if we try to read memory from a PT_LOAD that has + # p_filesz of zero that we don't get bytes from the next section + # that actually did have bytes. The addresses below were found by + # dumping the program headers of linux-i386.core and + # linux-x86_64.core and verifying that they had a p_filesz of zero. + mem_err = lldb.SBError() + if process.GetAddressByteSize() == 4: + bytes_read = process.ReadMemory(0x8048000, 4, mem_err) + else: + bytes_read = process.ReadMemory(0x400000, 4, mem_err) + self.assertEqual(bytes_read, None) + reason = thread.GetStopReason() + if( thread.GetThreadID() == tid ): + self.assertEqual(reason, lldb.eStopReasonSignal) + signal = thread.GetStopReasonDataAtIndex(1) + # Check we got signal 4 (SIGILL) + self.assertEqual(signal, 4) + else: + signal = thread.GetStopReasonDataAtIndex(1) + # Check we got no signal on the other threads + self.assertEqual(signal, 0) + + self.dbg.DeleteTarget(target) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/main.cpp new file mode 100644 index 00000000000..dd83558bd69 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/main.cpp @@ -0,0 +1,62 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test verifies the correct handling of child thread exits. + +#include "pseudo_barrier.h" +#include <thread> +#include <csignal> + +pseudo_barrier_t g_barrier1; +pseudo_barrier_t g_barrier2; + +void * +thread1 () +{ + // Synchronize with the main thread. + pseudo_barrier_wait(g_barrier1); + + // Synchronize with the main thread and thread2. + pseudo_barrier_wait(g_barrier2); + + // Return + return NULL; // Should not reach here. (thread2 should raise SIGILL) +} + +void * +thread2 () +{ + raise(SIGILL); // Raise SIGILL + + // Synchronize with thread1 and the main thread. + pseudo_barrier_wait(g_barrier2); // Should not reach here. + + // Return + return NULL; +} + +int main () +{ + pseudo_barrier_init(g_barrier1, 2); + pseudo_barrier_init(g_barrier2, 3); + + // Create a thread. + std::thread thread_1(thread1); + + // Wait for thread1 to start. + pseudo_barrier_wait(g_barrier1); + + // Create another thread. + std::thread thread_2(thread2); + + // Wait for thread2 to start. + // Second thread should crash but first thread and main thread may reach here. + pseudo_barrier_wait(g_barrier2); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/main.mk b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/main.mk new file mode 100755 index 00000000000..566938ca0cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/main.mk @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/make-core.sh b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/make-core.sh new file mode 100755 index 00000000000..ea263c86ea4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/thread_crash/make-core.sh @@ -0,0 +1,64 @@ +#! /bin/sh + +linux_check_core_pattern() +{ + if grep -q '^|' </proc/sys/kernel/core_pattern; then + cat <<EOF +Your system uses a crash report tool ($(cat /proc/sys/kernel/core_pattern)). Core files +will not be generated. Please reset /proc/sys/kernel/core_pattern (requires root +privileges) to enable core generation. +EOF + exit 1 + fi +} + +OS=$(uname -s) +case "$OS" in +FreeBSD) + core_pattern=$(sysctl -n kern.corefile) + ;; +Linux) + core_pattern=$(cat /proc/sys/kernel/core_pattern) + ;; +*) + echo "OS $OS not supported" >&2 + exit 1 + ;; +esac + +set -e -x + +if [ "$OS" = Linux ]; then + linux_check_core_pattern +fi + +ulimit -c 1000 +real_limit=$(ulimit -c) +if [ $real_limit -lt 100 ]; then + cat <<EOF +Unable to increase the core file limit. Core file may be truncated! +To fix this, increase HARD core file limit (ulimit -H -c 1000). This may require root +privileges. +EOF +fi + +rm -f a.out +make -f main.mk + +cat <<EOF +Executable file is in a.out. +Core file will be saved according to pattern $core_pattern. +EOF + +# Save stack size and core_dump_filter +stack_size=`ulimit -s` +ulimit -Ss 32 # Decrease stack size to 32k => smaller core files. + +core_dump_filter=`cat /proc/self/coredump_filter` +echo 0 > /proc/self/coredump_filter + +exec ./a.out + +# Reset stack size and core_dump_filter +echo core_dump_filter > /proc/self/coredump_filter +ulimit -s $stack_size diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/mach-core/TestMachCore.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/mach-core/TestMachCore.py new file mode 100644 index 00000000000..7680b55e60d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/mach-core/TestMachCore.py @@ -0,0 +1,69 @@ +""" +Test basics of mach core file debugging. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class MachCoreTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + super(MachCoreTestCase, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(MachCoreTestCase, self).tearDown() + + # This was originally marked as expected failure on Windows, but it has + # started timing out instead, so the expectedFailure attribute no longer + # correctly tracks it: llvm.org/pr37371 + @skipIfWindows + def test_selected_thread(self): + """Test that the right thread is selected after a core is loaded.""" + # Create core form YAML. + self.yaml2obj("test.core.yaml", self.getBuildArtifact("test.core")) + + # Set debugger into synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + target = self.dbg.CreateTarget("") + + # Load OS plugin. + python_os_plugin_path = os.path.join(self.getSourceDir(), + 'operating_system.py') + command = "settings set target.process.python-os-plugin-path '{}'".format( + python_os_plugin_path) + self.dbg.HandleCommand(command) + + # Load core. + process = target.LoadCore(self.getBuildArtifact("test.core")) + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetNumThreads(), 3) + + # Verify our OS plug-in threads showed up + thread = process.GetThreadByID(0x111111111) + self.assertTrue(thread.IsValid( + ), "Make sure there is a thread 0x111111111 after we load the python OS plug-in" + ) + thread = process.GetThreadByID(0x222222222) + self.assertTrue(thread.IsValid( + ), "Make sure there is a thread 0x222222222 after we load the python OS plug-in" + ) + thread = process.GetThreadByID(0x333333333) + self.assertTrue(thread.IsValid( + ), "Make sure there is a thread 0x333333333 after we load the python OS plug-in" + ) + + # Verify that the correct thread is selected + thread = process.GetSelectedThread() + self.assertEqual(thread.GetThreadID(), 0x333333333) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/mach-core/operating_system.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/mach-core/operating_system.py new file mode 100644 index 00000000000..95a5bdc9dd8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/mach-core/operating_system.py @@ -0,0 +1,44 @@ +import lldb + + +class OperatingSystemPlugIn(object): + """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class""" + + def __init__(self, process): + '''Initialization needs a valid.SBProcess object. + + This plug-in will get created after a live process is valid and has stopped for the first time. + ''' + self.process = None + self.registers = None + self.threads = None + if isinstance(process, lldb.SBProcess) and process.IsValid(): + self.process = process + self.threads = None # Will be an dictionary containing info for each thread + + def get_target(self): + return self.process.target + + def get_thread_info(self): + if not self.threads: + self.threads = [{ + 'tid': 0x111111111, + 'name': 'one', + 'queue': 'queue1', + 'state': 'stopped', + 'stop_reason': 'none' + }, { + 'tid': 0x222222222, + 'name': 'two', + 'queue': 'queue2', + 'state': 'stopped', + 'stop_reason': 'none' + }, { + 'tid': 0x333333333, + 'name': 'three', + 'queue': 'queue3', + 'state': 'stopped', + 'stop_reason': 'sigstop', + 'core': 0 + }] + return self.threads diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/mach-core/test.core.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/mach-core/test.core.yaml new file mode 100644 index 00000000000..84ce54e45e1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/mach-core/test.core.yaml @@ -0,0 +1,853 @@ +--- !mach-o +FileHeader: + magic: 0xFEEDFACF + cputype: 0x01000007 + cpusubtype: 0x00000003 + filetype: 0x00000004 + ncmds: 59 + sizeofcmds: 4384 + flags: 0x00000000 + reserved: 0x00000000 +LoadCommands: + - cmd: LC_THREAD + cmdsize: 208 + PayloadBytes: + - 0x04 + - 0x00 + - 0x00 + - 0x00 + - 0x2A + - 0x00 + - 0x00 + - 0x00 + - 0x01 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x80 + - 0xF7 + - 0xBF + - 0xEF + - 0xFE + - 0x7F + - 0x00 + - 0x00 + - 0x20 + - 0xF6 + - 0xBF + - 0xEF + - 0xFE + - 0x7F + - 0x00 + - 0x00 + - 0x01 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x10 + - 0xF6 + - 0xBF + - 0xEF + - 0xFE + - 0x7F + - 0x00 + - 0x00 + - 0xF0 + - 0xF5 + - 0xBF + - 0xEF + - 0xFE + - 0x7F + - 0x00 + - 0x00 + - 0xF0 + - 0xF5 + - 0xBF + - 0xEF + - 0xFE + - 0x7F + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0xFF + - 0xFF + - 0xFF + - 0xFF + - 0xC8 + - 0xB0 + - 0x70 + - 0xA7 + - 0xFF + - 0x7F + - 0x00 + - 0x00 + - 0xD0 + - 0xB0 + - 0x70 + - 0xA7 + - 0xFF + - 0x7F + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0xA0 + - 0x0F + - 0x00 + - 0x00 + - 0x01 + - 0x00 + - 0x00 + - 0x00 + - 0x46 + - 0x02 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x2B + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x06 + - 0x00 + - 0x00 + - 0x00 + - 0x04 + - 0x00 + - 0x00 + - 0x00 + - 0x03 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x00 + - 0x10 + - 0x00 + - 0x02 + - 0xA7 + - 0xFF + - 0x7F + - 0x00 + - 0x00 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4294967296 + vmsize: 4096 + fileoff: 8192 + filesize: 4096 + maxprot: 5 + initprot: 5 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4294971392 + vmsize: 4096 + fileoff: 12288 + filesize: 4096 + maxprot: 1 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4294975488 + vmsize: 307200 + fileoff: 16384 + filesize: 307200 + maxprot: 5 + initprot: 5 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295282688 + vmsize: 12288 + fileoff: 323584 + filesize: 12288 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295294976 + vmsize: 217088 + fileoff: 335872 + filesize: 217088 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295512064 + vmsize: 110592 + fileoff: 552960 + filesize: 110592 + maxprot: 1 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295622656 + vmsize: 8192 + fileoff: 663552 + filesize: 8192 + maxprot: 1 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295630848 + vmsize: 8192 + fileoff: 671744 + filesize: 8192 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295639040 + vmsize: 4096 + fileoff: 679936 + filesize: 4096 + maxprot: 1 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295643136 + vmsize: 4096 + fileoff: 684032 + filesize: 4096 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295651328 + vmsize: 24576 + fileoff: 688128 + filesize: 24576 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295684096 + vmsize: 24576 + fileoff: 712704 + filesize: 24576 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295712768 + vmsize: 4096 + fileoff: 737280 + filesize: 4096 + maxprot: 1 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4295716864 + vmsize: 8192 + fileoff: 741376 + filesize: 8192 + maxprot: 1 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4296015872 + vmsize: 1048576 + fileoff: 749568 + filesize: 1048576 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4297064448 + vmsize: 1048576 + fileoff: 1798144 + filesize: 1048576 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4298113024 + vmsize: 1048576 + fileoff: 2846720 + filesize: 1048576 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 4303355904 + vmsize: 8388608 + fileoff: 3895296 + filesize: 8388608 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140732912369664 + vmsize: 8388608 + fileoff: 12283904 + filesize: 8388608 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140734252867584 + vmsize: 811999232 + fileoff: 20672512 + filesize: 811999232 + maxprot: 5 + initprot: 5 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735863480320 + vmsize: 20553728 + fileoff: 832671744 + filesize: 20553728 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735884034048 + vmsize: 2097152 + fileoff: 853225472 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735886131200 + vmsize: 2097152 + fileoff: 855322624 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735888228352 + vmsize: 2097152 + fileoff: 857419776 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735890325504 + vmsize: 2097152 + fileoff: 859516928 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735892422656 + vmsize: 2097152 + fileoff: 861614080 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735894519808 + vmsize: 2097152 + fileoff: 863711232 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735896616960 + vmsize: 2097152 + fileoff: 865808384 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735898714112 + vmsize: 2097152 + fileoff: 867905536 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735900811264 + vmsize: 2097152 + fileoff: 870002688 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735902908416 + vmsize: 10485760 + fileoff: 872099840 + filesize: 10485760 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735913394176 + vmsize: 4194304 + fileoff: 882585600 + filesize: 4194304 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735917588480 + vmsize: 2097152 + fileoff: 886779904 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735919685632 + vmsize: 2097152 + fileoff: 888877056 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735921782784 + vmsize: 4194304 + fileoff: 890974208 + filesize: 4194304 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735925977088 + vmsize: 4194304 + fileoff: 895168512 + filesize: 4194304 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735930171392 + vmsize: 6291456 + fileoff: 899362816 + filesize: 6291456 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735936462848 + vmsize: 2097152 + fileoff: 905654272 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735938560000 + vmsize: 2097152 + fileoff: 907751424 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735940657152 + vmsize: 2097152 + fileoff: 909848576 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735942754304 + vmsize: 2097152 + fileoff: 911945728 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735944851456 + vmsize: 6291456 + fileoff: 914042880 + filesize: 6291456 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735951142912 + vmsize: 2097152 + fileoff: 920334336 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735953240064 + vmsize: 4194304 + fileoff: 922431488 + filesize: 4194304 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735957434368 + vmsize: 2097152 + fileoff: 926625792 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735959531520 + vmsize: 2097152 + fileoff: 928722944 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735961628672 + vmsize: 20971520 + fileoff: 930820096 + filesize: 20971520 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735982600192 + vmsize: 6291456 + fileoff: 951791616 + filesize: 6291456 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735988891648 + vmsize: 2097152 + fileoff: 958083072 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735990988800 + vmsize: 2097152 + fileoff: 960180224 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735993085952 + vmsize: 2097152 + fileoff: 962277376 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735995183104 + vmsize: 2097152 + fileoff: 964374528 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735997280256 + vmsize: 2097152 + fileoff: 966471680 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140735999377408 + vmsize: 2097152 + fileoff: 968568832 + filesize: 2097152 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140736001474560 + vmsize: 1302528 + fileoff: 970665984 + filesize: 1302528 + maxprot: 3 + initprot: 3 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140736937222144 + vmsize: 219267072 + fileoff: 971968512 + filesize: 219267072 + maxprot: 1 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140737486258176 + vmsize: 4096 + fileoff: 1191235584 + filesize: 4096 + maxprot: 1 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: '' + vmaddr: 140737487028224 + vmsize: 4096 + fileoff: 1191239680 + filesize: 4096 + maxprot: 5 + initprot: 5 + nsects: 0 + flags: 0 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/TestMiniDumpNew.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/TestMiniDumpNew.py new file mode 100644 index 00000000000..62b6c80e0b3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/TestMiniDumpNew.py @@ -0,0 +1,463 @@ +""" +Test basics of Minidump debugging. +""" + +from six import iteritems + +import shutil + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class MiniDumpNewTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + _linux_x86_64_pid = 29917 + _linux_x86_64_not_crashed_pid = 29939 + _linux_x86_64_not_crashed_pid_offset = 0xD967 + + def setUp(self): + super(MiniDumpNewTestCase, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(MiniDumpNewTestCase, self).tearDown() + + def process_from_yaml(self, yaml_file): + minidump_path = self.getBuildArtifact(os.path.basename(yaml_file) + ".dmp") + self.yaml2obj(yaml_file, minidump_path) + self.target = self.dbg.CreateTarget(None) + self.process = self.target.LoadCore(minidump_path) + return self.process + + def check_state(self): + with open(os.devnull) as devnul: + # sanitize test output + self.dbg.SetOutputFileHandle(devnul, False) + self.dbg.SetErrorFileHandle(devnul, False) + + self.assertTrue(self.process.is_stopped) + + # Process.Continue + error = self.process.Continue() + self.assertFalse(error.Success()) + self.assertTrue(self.process.is_stopped) + + # Thread.StepOut + thread = self.process.GetSelectedThread() + thread.StepOut() + self.assertTrue(self.process.is_stopped) + + # command line + self.dbg.HandleCommand('s') + self.assertTrue(self.process.is_stopped) + self.dbg.HandleCommand('c') + self.assertTrue(self.process.is_stopped) + + # restore file handles + self.dbg.SetOutputFileHandle(None, False) + self.dbg.SetErrorFileHandle(None, False) + + def test_loadcore_error_status(self): + """Test the SBTarget.LoadCore(core, error) overload.""" + minidump_path = self.getBuildArtifact("linux-x86_64.dmp") + self.yaml2obj("linux-x86_64.yaml", minidump_path) + self.target = self.dbg.CreateTarget(None) + error = lldb.SBError() + self.process = self.target.LoadCore(minidump_path, error) + self.assertTrue(self.process, PROCESS_IS_VALID) + self.assertTrue(error.Success()) + + def test_loadcore_error_status_failure(self): + """Test the SBTarget.LoadCore(core, error) overload.""" + self.target = self.dbg.CreateTarget(None) + error = lldb.SBError() + self.process = self.target.LoadCore("non-existent.dmp", error) + self.assertFalse(self.process, PROCESS_IS_VALID) + self.assertTrue(error.Fail()) + + def test_process_info_in_minidump(self): + """Test that lldb can read the process information from the Minidump.""" + self.process_from_yaml("linux-x86_64.yaml") + self.assertTrue(self.process, PROCESS_IS_VALID) + self.assertEqual(self.process.GetNumThreads(), 1) + self.assertEqual(self.process.GetProcessID(), self._linux_x86_64_pid) + self.check_state() + + def test_memory_region_name(self): + self.process_from_yaml("regions-linux-map.yaml") + result = lldb.SBCommandReturnObject() + addr_region_name_pairs = [ + ("0x400d9000", "/system/bin/app_process"), + ("0x400db000", "/system/bin/app_process"), + ("0x400dd000", "/system/bin/linker"), + ("0x400ed000", "/system/bin/linker"), + ("0x400ee000", "/system/bin/linker"), + ("0x400fb000", "/system/lib/liblog.so"), + ("0x400fc000", "/system/lib/liblog.so"), + ("0x400fd000", "/system/lib/liblog.so"), + ("0x400ff000", "/system/lib/liblog.so"), + ("0x40100000", "/system/lib/liblog.so"), + ("0x40101000", "/system/lib/libc.so"), + ("0x40122000", "/system/lib/libc.so"), + ("0x40123000", "/system/lib/libc.so"), + ("0x40167000", "/system/lib/libc.so"), + ("0x40169000", "/system/lib/libc.so"), + ] + ci = self.dbg.GetCommandInterpreter() + for (addr, region_name) in addr_region_name_pairs: + command = 'memory region ' + addr + ci.HandleCommand(command, result, False) + message = 'Ensure memory "%s" shows up in output for "%s"' % ( + region_name, command) + self.assertTrue(region_name in result.GetOutput(), message) + + def test_thread_info_in_minidump(self): + """Test that lldb can read the thread information from the Minidump.""" + self.process_from_yaml("linux-x86_64.yaml") + self.check_state() + # This process crashed due to a segmentation fault in its + # one and only thread. + self.assertEqual(self.process.GetNumThreads(), 1) + thread = self.process.GetThreadAtIndex(0) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonSignal) + stop_description = thread.GetStopDescription(256) + self.assertTrue("SIGSEGV" in stop_description) + + def test_stack_info_in_minidump(self): + """Test that we can see a trivial stack in a breakpad-generated Minidump.""" + # target create linux-x86_64 -c linux-x86_64.dmp + self.dbg.CreateTarget("linux-x86_64") + self.target = self.dbg.GetSelectedTarget() + self.process = self.target.LoadCore("linux-x86_64.dmp") + self.check_state() + self.assertEqual(self.process.GetNumThreads(), 1) + self.assertEqual(self.process.GetProcessID(), self._linux_x86_64_pid) + thread = self.process.GetThreadAtIndex(0) + # frame #0: linux-x86_64`crash() + # frame #1: linux-x86_64`_start + self.assertEqual(thread.GetNumFrames(), 2) + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame.IsValid()) + self.assertTrue(frame.GetModule().IsValid()) + pc = frame.GetPC() + eip = frame.FindRegister("pc") + self.assertTrue(eip.IsValid()) + self.assertEqual(pc, eip.GetValueAsUnsigned()) + + def test_snapshot_minidump_dump_requested(self): + """Test that if we load a snapshot minidump file (meaning the process + did not crash) with exception code "DUMP_REQUESTED" there is no stop reason.""" + # target create -c linux-x86_64_not_crashed.dmp + self.dbg.CreateTarget(None) + self.target = self.dbg.GetSelectedTarget() + self.process = self.target.LoadCore("linux-x86_64_not_crashed.dmp") + self.check_state() + self.assertEqual(self.process.GetNumThreads(), 1) + thread = self.process.GetThreadAtIndex(0) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonNone) + stop_description = thread.GetStopDescription(256) + self.assertEqual(stop_description, "") + + def test_snapshot_minidump_null_exn_code(self): + """Test that if we load a snapshot minidump file (meaning the process + did not crash) with exception code zero there is no stop reason.""" + self.process_from_yaml("linux-x86_64_null_signal.yaml") + self.check_state() + self.assertEqual(self.process.GetNumThreads(), 1) + thread = self.process.GetThreadAtIndex(0) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonNone) + stop_description = thread.GetStopDescription(256) + self.assertEqual(stop_description, "") + + def check_register_unsigned(self, set, name, expected): + reg_value = set.GetChildMemberWithName(name) + self.assertTrue(reg_value.IsValid(), + 'Verify we have a register named "%s"' % (name)) + self.assertEqual(reg_value.GetValueAsUnsigned(), expected, + 'Verify "%s" == %i' % (name, expected)) + + def check_register_string_value(self, set, name, expected, format): + reg_value = set.GetChildMemberWithName(name) + self.assertTrue(reg_value.IsValid(), + 'Verify we have a register named "%s"' % (name)) + if format is not None: + reg_value.SetFormat(format) + self.assertEqual(reg_value.GetValue(), expected, + 'Verify "%s" has string value "%s"' % (name, + expected)) + + def test_arm64_registers(self): + """Test ARM64 registers from a breakpad created minidump.""" + self.process_from_yaml("arm64-macos.yaml") + self.check_state() + self.assertEqual(self.process.GetNumThreads(), 1) + thread = self.process.GetThreadAtIndex(0) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonNone) + stop_description = thread.GetStopDescription(256) + self.assertEqual(stop_description, "") + registers = thread.GetFrameAtIndex(0).GetRegisters() + # Verify the GPR registers are all correct + # Verify x0 - x31 register values + gpr = registers.GetValueAtIndex(0) + for i in range(32): + v = i+1 | i+2 << 32 | i+3 << 48 + w = i+1 + self.check_register_unsigned(gpr, 'x%i' % (i), v) + self.check_register_unsigned(gpr, 'w%i' % (i), w) + # Verify arg1 - arg8 register values + for i in range(1, 9): + v = i | i+1 << 32 | i+2 << 48 + self.check_register_unsigned(gpr, 'arg%i' % (i), v) + i = 29 + v = i+1 | i+2 << 32 | i+3 << 48 + self.check_register_unsigned(gpr, 'fp', v) + i = 30 + v = i+1 | i+2 << 32 | i+3 << 48 + self.check_register_unsigned(gpr, 'lr', v) + i = 31 + v = i+1 | i+2 << 32 | i+3 << 48 + self.check_register_unsigned(gpr, 'sp', v) + self.check_register_unsigned(gpr, 'pc', 0x1000) + self.check_register_unsigned(gpr, 'cpsr', 0x11223344) + self.check_register_unsigned(gpr, 'psr', 0x11223344) + + # Verify the FPR registers are all correct + fpr = registers.GetValueAtIndex(1) + for i in range(32): + v = "0x" + d = "0x" + s = "0x" + h = "0x" + for j in range(i+15, i-1, -1): + v += "%2.2x" % (j) + for j in range(i+7, i-1, -1): + d += "%2.2x" % (j) + for j in range(i+3, i-1, -1): + s += "%2.2x" % (j) + for j in range(i+1, i-1, -1): + h += "%2.2x" % (j) + self.check_register_string_value(fpr, "v%i" % (i), v, + lldb.eFormatHex) + self.check_register_string_value(fpr, "d%i" % (i), d, + lldb.eFormatHex) + self.check_register_string_value(fpr, "s%i" % (i), s, + lldb.eFormatHex) + self.check_register_string_value(fpr, "h%i" % (i), h, + lldb.eFormatHex) + self.check_register_unsigned(gpr, 'fpsr', 0x55667788) + self.check_register_unsigned(gpr, 'fpcr', 0x99aabbcc) + + def verify_arm_registers(self, apple=False): + """ + Verify values of all ARM registers from a breakpad created + minidump. + """ + if apple: + self.process_from_yaml("arm-macos.yaml") + else: + self.process_from_yaml("arm-linux.yaml") + self.check_state() + self.assertEqual(self.process.GetNumThreads(), 1) + thread = self.process.GetThreadAtIndex(0) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonNone) + stop_description = thread.GetStopDescription(256) + self.assertEqual(stop_description, "") + registers = thread.GetFrameAtIndex(0).GetRegisters() + # Verify the GPR registers are all correct + # Verify x0 - x31 register values + gpr = registers.GetValueAtIndex(0) + for i in range(1, 16): + self.check_register_unsigned(gpr, 'r%i' % (i), i+1) + # Verify arg1 - arg4 register values + for i in range(1, 5): + self.check_register_unsigned(gpr, 'arg%i' % (i), i) + if apple: + self.check_register_unsigned(gpr, 'fp', 0x08) + else: + self.check_register_unsigned(gpr, 'fp', 0x0c) + self.check_register_unsigned(gpr, 'lr', 0x0f) + self.check_register_unsigned(gpr, 'sp', 0x0e) + self.check_register_unsigned(gpr, 'pc', 0x10) + self.check_register_unsigned(gpr, 'cpsr', 0x11223344) + + # Verify the FPR registers are all correct + fpr = registers.GetValueAtIndex(1) + # Check d0 - d31 + self.check_register_unsigned(gpr, 'fpscr', 0x55667788aabbccdd) + for i in range(32): + value = (i+1) | (i+1) << 8 | (i+1) << 32 | (i+1) << 48 + self.check_register_unsigned(fpr, "d%i" % (i), value) + # Check s0 - s31 + for i in range(32): + i_val = (i >> 1) + 1 + if i & 1: + value = "%#8.8x" % (i_val | i_val << 16) + else: + value = "%#8.8x" % (i_val | i_val << 8) + self.check_register_string_value(fpr, "s%i" % (i), value, + lldb.eFormatHex) + # Check q0 - q15 + for i in range(15): + a = i * 2 + 1 + b = a + 1 + value = ("0x00%2.2x00%2.2x0000%2.2x%2.2x" + "00%2.2x00%2.2x0000%2.2x%2.2x") % (b, b, b, b, a, a, a, a) + self.check_register_string_value(fpr, "q%i" % (i), value, + lldb.eFormatHex) + + def test_linux_arm_registers(self): + """Test Linux ARM registers from a breakpad created minidump. + + The frame pointer is R11 for linux. + """ + self.verify_arm_registers(apple=False) + + def test_apple_arm_registers(self): + """Test Apple ARM registers from a breakpad created minidump. + + The frame pointer is R7 for linux. + """ + self.verify_arm_registers(apple=True) + + def do_test_deeper_stack(self, binary, core, pid): + target = self.dbg.CreateTarget(binary) + process = target.LoadCore(core) + thread = process.GetThreadAtIndex(0) + + self.assertEqual(process.GetProcessID(), pid) + + expected_stack = {1: 'bar', 2: 'foo', 3: '_start'} + self.assertGreaterEqual(thread.GetNumFrames(), len(expected_stack)) + for index, name in iteritems(expected_stack): + frame = thread.GetFrameAtIndex(index) + self.assertTrue(frame.IsValid()) + function_name = frame.GetFunctionName() + self.assertTrue(name in function_name) + + @skipIfLLVMTargetMissing("X86") + def test_deeper_stack_in_minidump(self): + """Test that we can examine a more interesting stack in a Minidump.""" + # Launch with the Minidump, and inspect the stack. + # target create linux-x86_64_not_crashed -c linux-x86_64_not_crashed.dmp + self.do_test_deeper_stack("linux-x86_64_not_crashed", + "linux-x86_64_not_crashed.dmp", + self._linux_x86_64_not_crashed_pid) + + def do_change_pid_in_minidump(self, core, newcore, offset, oldpid, newpid): + """ This assumes that the minidump is breakpad generated on Linux - + meaning that the PID in the file will be an ascii string part of + /proc/PID/status which is written in the file + """ + shutil.copyfile(core, newcore) + with open(newcore, "rb+") as f: + f.seek(offset) + currentpid = f.read(5).decode('utf-8') + self.assertEqual(currentpid, oldpid) + + f.seek(offset) + if len(newpid) < len(oldpid): + newpid += " " * (len(oldpid) - len(newpid)) + newpid += "\n" + f.write(newpid.encode('utf-8')) + + def test_deeper_stack_in_minidump_with_same_pid_running(self): + """Test that we read the information from the core correctly even if we + have a running process with the same PID""" + new_core = self.getBuildArtifact("linux-x86_64_not_crashed-pid.dmp") + self.do_change_pid_in_minidump("linux-x86_64_not_crashed.dmp", + new_core, + self._linux_x86_64_not_crashed_pid_offset, + str(self._linux_x86_64_not_crashed_pid), + str(os.getpid())) + self.do_test_deeper_stack("linux-x86_64_not_crashed", new_core, os.getpid()) + + def test_two_cores_same_pid(self): + """Test that we handle the situation if we have two core files with the same PID """ + new_core = self.getBuildArtifact("linux-x86_64_not_crashed-pid.dmp") + self.do_change_pid_in_minidump("linux-x86_64_not_crashed.dmp", + new_core, + self._linux_x86_64_not_crashed_pid_offset, + str(self._linux_x86_64_not_crashed_pid), + str(self._linux_x86_64_pid)) + self.do_test_deeper_stack("linux-x86_64_not_crashed", + new_core, self._linux_x86_64_pid) + self.test_stack_info_in_minidump() + + def test_local_variables_in_minidump(self): + """Test that we can examine local variables in a Minidump.""" + # Launch with the Minidump, and inspect a local variable. + # target create linux-x86_64_not_crashed -c linux-x86_64_not_crashed.dmp + self.target = self.dbg.CreateTarget("linux-x86_64_not_crashed") + self.process = self.target.LoadCore("linux-x86_64_not_crashed.dmp") + self.check_state() + thread = self.process.GetThreadAtIndex(0) + frame = thread.GetFrameAtIndex(1) + value = frame.EvaluateExpression('x') + self.assertEqual(value.GetValueAsSigned(), 3) + + def test_memory_regions_in_minidump(self): + """Test memory regions from a Minidump""" + self.process_from_yaml("regions-linux-map.yaml") + self.check_state() + + regions_count = 19 + region_info_list = self.process.GetMemoryRegions() + self.assertEqual(region_info_list.GetSize(), regions_count) + + def check_region(index, start, end, read, write, execute, mapped, name): + region_info = lldb.SBMemoryRegionInfo() + self.assertTrue( + self.process.GetMemoryRegionInfo(start, region_info).Success()) + self.assertEqual(start, region_info.GetRegionBase()) + self.assertEqual(end, region_info.GetRegionEnd()) + self.assertEqual(read, region_info.IsReadable()) + self.assertEqual(write, region_info.IsWritable()) + self.assertEqual(execute, region_info.IsExecutable()) + self.assertEqual(mapped, region_info.IsMapped()) + self.assertEqual(name, region_info.GetName()) + + # Ensure we have the same regions as SBMemoryRegionInfoList contains. + if index >= 0 and index < regions_count: + region_info_from_list = lldb.SBMemoryRegionInfo() + self.assertTrue(region_info_list.GetMemoryRegionAtIndex( + index, region_info_from_list)) + self.assertEqual(region_info_from_list, region_info) + + a = "/system/bin/app_process" + b = "/system/bin/linker" + c = "/system/lib/liblog.so" + d = "/system/lib/libc.so" + n = None + max_int = 0xffffffffffffffff + + # Test address before the first entry comes back with nothing mapped up + # to first valid region info + check_region(-1, 0x00000000, 0x400d9000, False, False, False, False, n) + check_region( 0, 0x400d9000, 0x400db000, True, False, True, True, a) + check_region( 1, 0x400db000, 0x400dc000, True, False, False, True, a) + check_region( 2, 0x400dc000, 0x400dd000, True, True, False, True, n) + check_region( 3, 0x400dd000, 0x400ec000, True, False, True, True, b) + check_region( 4, 0x400ec000, 0x400ed000, True, False, False, True, n) + check_region( 5, 0x400ed000, 0x400ee000, True, False, False, True, b) + check_region( 6, 0x400ee000, 0x400ef000, True, True, False, True, b) + check_region( 7, 0x400ef000, 0x400fb000, True, True, False, True, n) + check_region( 8, 0x400fb000, 0x400fc000, True, False, True, True, c) + check_region( 9, 0x400fc000, 0x400fd000, True, True, True, True, c) + check_region(10, 0x400fd000, 0x400ff000, True, False, True, True, c) + check_region(11, 0x400ff000, 0x40100000, True, False, False, True, c) + check_region(12, 0x40100000, 0x40101000, True, True, False, True, c) + check_region(13, 0x40101000, 0x40122000, True, False, True, True, d) + check_region(14, 0x40122000, 0x40123000, True, True, True, True, d) + check_region(15, 0x40123000, 0x40167000, True, False, True, True, d) + check_region(16, 0x40167000, 0x40169000, True, False, False, True, d) + check_region(17, 0x40169000, 0x4016b000, True, True, False, True, d) + check_region(18, 0x4016b000, 0x40176000, True, True, False, True, n) + check_region(-1, 0x40176000, max_int, False, False, False, False, n) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/TestMiniDumpUUID.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/TestMiniDumpUUID.py new file mode 100644 index 00000000000..ca0ad5f67b2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/TestMiniDumpUUID.py @@ -0,0 +1,195 @@ +""" +Test basics of Minidump debugging. +""" + +from six import iteritems + + +import lldb +import os +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class MiniDumpUUIDTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + super(MiniDumpUUIDTestCase, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(MiniDumpUUIDTestCase, self).tearDown() + + def verify_module(self, module, verify_path, verify_uuid): + uuid = module.GetUUIDString() + self.assertEqual(verify_path, module.GetFileSpec().fullpath) + self.assertEqual(verify_uuid, uuid) + + def get_minidump_modules(self, yaml_file): + minidump_path = self.getBuildArtifact(os.path.basename(yaml_file) + ".dmp") + self.yaml2obj(yaml_file, minidump_path) + self.target = self.dbg.CreateTarget(None) + self.process = self.target.LoadCore(minidump_path) + return self.target.modules + + def test_zero_uuid_modules(self): + """ + Test multiple modules having a MINIDUMP_MODULE.CvRecord that is valid, + but contains a PDB70 value whose age is zero and whose UUID values are + all zero. Prior to a fix all such modules would be duplicated to the + first one since the UUIDs claimed to be valid and all zeroes. Now we + ensure that the UUID is not valid for each module and that we have + each of the modules in the target after loading the core + """ + modules = self.get_minidump_modules("linux-arm-zero-uuids.yaml") + self.assertEqual(2, len(modules)) + self.verify_module(modules[0], "/file/does/not/exist/a", None) + self.verify_module(modules[1], "/file/does/not/exist/b", None) + + def test_uuid_modules_no_age(self): + """ + Test multiple modules having a MINIDUMP_MODULE.CvRecord that is valid, + and contains a PDB70 value whose age is zero and whose UUID values are + valid. Ensure we decode the UUID and don't include the age field in the UUID. + """ + modules = self.get_minidump_modules("linux-arm-uuids-no-age.yaml") + modules = self.target.modules + self.assertEqual(2, len(modules)) + self.verify_module(modules[0], "/tmp/a", "01020304-0506-0708-090A-0B0C0D0E0F10") + self.verify_module(modules[1], "/tmp/b", "0A141E28-323C-4650-5A64-6E78828C96A0") + + def test_uuid_modules_no_age_apple(self): + """ + Test multiple modules having a MINIDUMP_MODULE.CvRecord that is valid, + and contains a PDB70 value whose age is zero and whose UUID values are + valid. Ensure we decode the UUID and don't include the age field in the UUID. + Also ensure that the first uint32_t is byte swapped, along with the next + two uint16_t values. Breakpad incorrectly byte swaps these values when it + saves Darwin minidump files. + """ + modules = self.get_minidump_modules("macos-arm-uuids-no-age.yaml") + modules = self.target.modules + self.assertEqual(2, len(modules)) + self.verify_module(modules[0], "/tmp/a", "04030201-0605-0807-090A-0B0C0D0E0F10") + self.verify_module(modules[1], "/tmp/b", "281E140A-3C32-5046-5A64-6E78828C96A0") + + def test_uuid_modules_with_age(self): + """ + Test multiple modules having a MINIDUMP_MODULE.CvRecord that is valid, + and contains a PDB70 value whose age is valid and whose UUID values are + valid. Ensure we decode the UUID and include the age field in the UUID. + """ + modules = self.get_minidump_modules("linux-arm-uuids-with-age.yaml") + self.assertEqual(2, len(modules)) + self.verify_module(modules[0], "/tmp/a", "01020304-0506-0708-090A-0B0C0D0E0F10-10101010") + self.verify_module(modules[1], "/tmp/b", "0A141E28-323C-4650-5A64-6E78828C96A0-20202020") + + def test_uuid_modules_elf_build_id_16(self): + """ + Test multiple modules having a MINIDUMP_MODULE.CvRecord that is valid, + and contains a ELF build ID whose value is valid and is 16 bytes long. + """ + modules = self.get_minidump_modules("linux-arm-uuids-elf-build-id-16.yaml") + self.assertEqual(2, len(modules)) + self.verify_module(modules[0], "/tmp/a", "01020304-0506-0708-090A-0B0C0D0E0F10") + self.verify_module(modules[1], "/tmp/b", "0A141E28-323C-4650-5A64-6E78828C96A0") + + def test_uuid_modules_elf_build_id_20(self): + """ + Test multiple modules having a MINIDUMP_MODULE.CvRecord that is valid, + and contains a ELF build ID whose value is valid and is 20 bytes long. + """ + modules = self.get_minidump_modules("linux-arm-uuids-elf-build-id-20.yaml") + self.assertEqual(2, len(modules)) + self.verify_module(modules[0], "/tmp/a", "01020304-0506-0708-090A-0B0C0D0E0F10-11121314") + self.verify_module(modules[1], "/tmp/b", "0A141E28-323C-4650-5A64-6E78828C96A0-AAB4BEC8") + + def test_uuid_modules_elf_build_id_zero(self): + """ + Test multiple modules having a MINIDUMP_MODULE.CvRecord that is valid, + and contains a ELF build ID whose value is all zero. + """ + modules = self.get_minidump_modules("linux-arm-uuids-elf-build-id-zero.yaml") + self.assertEqual(2, len(modules)) + self.verify_module(modules[0], "/not/exist/a", None) + self.verify_module(modules[1], "/not/exist/b", None) + + def test_uuid_modules_elf_build_id_same(self): + """ + Test multiple modules having a MINIDUMP_MODULE.CvRecord that is + valid, and contains a ELF build ID whose value is the same. There + is an assert in the PlaceholderObjectFile that was firing when we + encountered this which was crashing the process that was checking + if PlaceholderObjectFile.m_base was the same as the address this + fake module was being loaded at. We need to ensure we don't crash + in such cases and that we add both modules even though they have + the same UUID. + """ + modules = self.get_minidump_modules("linux-arm-same-uuids.yaml") + self.assertEqual(2, len(modules)) + self.verify_module(modules[0], "/file/does/not/exist/a", + '11223344-1122-3344-1122-334411223344-11223344') + self.verify_module(modules[1], "/file/does/not/exist/b", + '11223344-1122-3344-1122-334411223344-11223344') + + @expectedFailureAll(oslist=["windows"]) + def test_partial_uuid_match(self): + """ + Breakpad has been known to create minidump files using CvRecord in each + module whose signature is set to PDB70 where the UUID only contains the + first 16 bytes of a 20 byte ELF build ID. Code was added to + ProcessMinidump.cpp to deal with this and allows partial UUID matching. + + This test verifies that if we have a minidump with a 16 byte UUID, that + we are able to associate a symbol file with a 20 byte UUID only if the + first 16 bytes match. In this case we will see the path from the file + we found in the test directory and the 20 byte UUID from the actual + file, not the 16 byte shortened UUID from the minidump. + """ + so_path = self.getBuildArtifact("libuuidmatch.so") + self.yaml2obj("libuuidmatch.yaml", so_path) + cmd = 'settings set target.exec-search-paths "%s"' % (os.path.dirname(so_path)) + self.dbg.HandleCommand(cmd) + modules = self.get_minidump_modules("linux-arm-partial-uuids-match.yaml") + self.assertEqual(1, len(modules)) + self.verify_module(modules[0], so_path, + "7295E17C-6668-9E05-CBB5-DEE5003865D5-5267C116") + + def test_partial_uuid_mismatch(self): + """ + Breakpad has been known to create minidump files using CvRecord in each + module whose signature is set to PDB70 where the UUID only contains the + first 16 bytes of a 20 byte ELF build ID. Code was added to + ProcessMinidump.cpp to deal with this and allows partial UUID matching. + + This test verifies that if we have a minidump with a 16 byte UUID, that + we are not able to associate a symbol file with a 20 byte UUID only if + any of the first 16 bytes do not match. In this case we will see the UUID + from the minidump file and the path from the minidump file. + """ + so_path = self.getBuildArtifact("libuuidmismatch.so") + self.yaml2obj("libuuidmismatch.yaml", so_path) + cmd = 'settings set target.exec-search-paths "%s"' % (os.path.dirname(so_path)) + self.dbg.HandleCommand(cmd) + modules = self.get_minidump_modules("linux-arm-partial-uuids-mismatch.yaml") + self.assertEqual(1, len(modules)) + self.verify_module(modules[0], + "/invalid/path/on/current/system/libuuidmismatch.so", + "7295E17C-6668-9E05-CBB5-DEE5003865D5") + + def test_relative_module_name(self): + old_cwd = os.getcwd() + self.addTearDownHook(lambda: os.chdir(old_cwd)) + os.chdir(self.getBuildDir()) + name = "file-with-a-name-unlikely-to-exist-in-the-current-directory.so" + open(name, "a").close() + modules = self.get_minidump_modules( + self.getSourcePath("relative_module_name.yaml")) + self.assertEqual(1, len(modules)) + self.verify_module(modules[0], name, None) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/arm-linux.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/arm-linux.yaml new file mode 100644 index 00000000000..072b4de411f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/arm-linux.yaml @@ -0,0 +1,18 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM + Platform ID: Linux + CSD Version: ABC123 + CPU: + CPUID: 0x00000000 + - Type: MiscInfo + Content: 00000000010000007B000000000000000000000000000000 + - Type: ThreadList + Threads: + - Thread Id: 0x00001000 + Context: 060000400100000002000000030000000400000005000000060000000700000008000000090000000A0000000B0000000C0000000D0000000E0000000F0000001000000044332211DDCCBBAA887766550101000001000100020200000200020003030000030003000404000004000400050500000500050006060000060006000707000007000700080800000800080009090000090009000A0A00000A000A000B0B00000B000B000C0C00000C000C000D0D00000D000D000E0E00000E000E000F0F00000F000F0010100000100010001111000011001100121200001200120013130000130013001414000014001400151500001500150016160000160016001717000017001700181800001800180019190000190019001A1A00001A001A001B1B00001B001B001C1C00001C001C001D1D00001D001D001E1E00001E001E001F1F00001F001F0020200000200020000000000001000100020002000300030004000400050005000600060007000700 + Stack: + Start of Memory Range: 0x0000000000000000 + Content: '' +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/arm-macos.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/arm-macos.yaml new file mode 100644 index 00000000000..b194492f6f0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/arm-macos.yaml @@ -0,0 +1,18 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM + Platform ID: MacOSX + CSD Version: ABC123 + CPU: + CPUID: 0x00000000 + - Type: MiscInfo + Content: 00000000010000007B000000000000000000000000000000 + - Type: ThreadList + Threads: + - Thread Id: 0x00001000 + Context: 060000400100000002000000030000000400000005000000060000000700000008000000090000000A0000000B0000000C0000000D0000000E0000000F0000001000000044332211DDCCBBAA887766550101000001000100020200000200020003030000030003000404000004000400050500000500050006060000060006000707000007000700080800000800080009090000090009000A0A00000A000A000B0B00000B000B000C0C00000C000C000D0D00000D000D000E0E00000E000E000F0F00000F000F0010100000100010001111000011001100121200001200120013130000130013001414000014001400151500001500150016160000160016001717000017001700181800001800180019190000190019001A1A00001A001A001B1B00001B001B001C1C00001C001C001D1D00001D001D001E1E00001E001E001F1F00001F001F0020200000200020000000000001000100020002000300030004000400050005000600060007000700 + Stack: + Start of Memory Range: 0x0000000000000000 + Content: '' +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/arm64-macos.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/arm64-macos.yaml new file mode 100644 index 00000000000..70817f14da5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/arm64-macos.yaml @@ -0,0 +1,18 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: BP_ARM64 + Platform ID: MacOSX + CSD Version: '15E216' + CPU: + CPUID: 0x00000000 + - Type: MiscInfo + Content: 00000000010000007B000000000000000000000000000000 + - Type: ThreadList + Threads: + - Thread Id: 0x00001000 + Context: 060000800000000001000000020003000200000003000400030000000400050004000000050006000500000006000700060000000700080007000000080009000800000009000A00090000000A000B000A0000000B000C000B0000000C000D000C0000000D000E000D0000000E000F000E0000000F0010000F00000010001100100000001100120011000000120013001200000013001400130000001400150014000000150016001500000016001700160000001700180017000000180019001800000019001A00190000001A001B001A0000001B001C001B0000001C001D001C0000001D001E001D0000001E001F001E0000001F0020001F00000020002100200000002100220000100000000000004433221188776655CCBBAA99000102030405060708090A0B0C0D0E0F0102030405060708090A0B0C0D0E0F1002030405060708090A0B0C0D0E0F1011030405060708090A0B0C0D0E0F1011120405060708090A0B0C0D0E0F1011121305060708090A0B0C0D0E0F1011121314060708090A0B0C0D0E0F1011121314150708090A0B0C0D0E0F1011121314151608090A0B0C0D0E0F1011121314151617090A0B0C0D0E0F1011121314151617180A0B0C0D0E0F101112131415161718190B0C0D0E0F101112131415161718191A0C0D0E0F101112131415161718191A1B0D0E0F101112131415161718191A1B1C0E0F101112131415161718191A1B1C1D0F101112131415161718191A1B1C1D1E101112131415161718191A1B1C1D1E1F1112131415161718191A1B1C1D1E1F2012131415161718191A1B1C1D1E1F2021131415161718191A1B1C1D1E1F2021221415161718191A1B1C1D1E1F2021222315161718191A1B1C1D1E1F2021222324161718191A1B1C1D1E1F2021222324251718191A1B1C1D1E1F2021222324252618191A1B1C1D1E1F2021222324252627191A1B1C1D1E1F2021222324252627281A1B1C1D1E1F202122232425262728291B1C1D1E1F202122232425262728292A1C1D1E1F202122232425262728292A2B1D1E1F202122232425262728292A2B2C1E1F202122232425262728292A2B2C2D1F202122232425262728292A2B2C2D2E + Stack: + Start of Memory Range: 0x0000000000000000 + Content: '' +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/install_breakpad.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/install_breakpad.cpp new file mode 100644 index 00000000000..c34ac17128f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/install_breakpad.cpp @@ -0,0 +1,16 @@ +#include "client/linux/handler/exception_handler.h" + +static bool dumpCallback(const google_breakpad::MinidumpDescriptor &descriptor, + void *context, bool succeeded) { + return succeeded; +} + +google_breakpad::ExceptionHandler *eh; + +void InstallBreakpad() { + google_breakpad::MinidumpDescriptor descriptor("/tmp"); + eh = new google_breakpad::ExceptionHandler(descriptor, NULL, dumpCallback, + NULL, true, -1); +} + +void WriteMinidump() { eh->WriteMinidump(); } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/libuuidmatch.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/libuuidmatch.yaml new file mode 100644 index 00000000000..3610694d4db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/libuuidmatch.yaml @@ -0,0 +1,14 @@ +--- !ELF +FileHeader: + Class: ELFCLASS32 + Data: ELFDATA2LSB + Type: ET_DYN + Machine: EM_ARM + Flags: [ EF_ARM_SOFT_FLOAT, EF_ARM_EABI_VER5 ] +Sections: + - Name: .note.gnu.build-id + Type: SHT_NOTE + Flags: [ SHF_ALLOC ] + Address: 0x0000000000000114 + AddressAlign: 0x0000000000000004 + Content: 040000001400000003000000474E55007295E17C66689E05CBB5DEE5003865D55267C116 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/libuuidmismatch.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/libuuidmismatch.yaml new file mode 100644 index 00000000000..5fef636228e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/libuuidmismatch.yaml @@ -0,0 +1,14 @@ +--- !ELF +FileHeader: + Class: ELFCLASS32 + Data: ELFDATA2LSB + Type: ET_DYN + Machine: EM_ARM + Flags: [ EF_ARM_SOFT_FLOAT, EF_ARM_EABI_VER5 ] +Sections: + - Name: .note.gnu.build-id + Type: SHT_NOTE + Flags: [ SHF_ALLOC ] + Address: 0x0000000000000114 + AddressAlign: 0x0000000000000004 + Content: 040000001400000003000000474E55008295E17C66689E05CBB5DEE5003865D55267C116 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-partial-uuids-match.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-partial-uuids-match.yaml new file mode 100644 index 00000000000..edb0001ff27 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-partial-uuids-match.yaml @@ -0,0 +1,15 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM + Platform ID: Linux + CSD Version: '15E216' + CPU: + CPUID: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/invalid/path/on/current/system/libuuidmatch.so' + CodeView Record: 525344537295E17C66689E05CBB5DEE5003865D50000000000 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-partial-uuids-mismatch.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-partial-uuids-mismatch.yaml new file mode 100644 index 00000000000..0b56a967bf6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-partial-uuids-mismatch.yaml @@ -0,0 +1,15 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM + Platform ID: Linux + CSD Version: '15E216' + CPU: + CPUID: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/invalid/path/on/current/system/libuuidmismatch.so' + CodeView Record: 525344537295E17C66689E05CBB5DEE5003865D50000000000 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-same-uuids.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-same-uuids.yaml new file mode 100644 index 00000000000..21c5220e415 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-same-uuids.yaml @@ -0,0 +1,21 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: AMD64 + Platform ID: Linux + CSD Version: '15E216' + CPU: + Vendor ID: GenuineIntel + Version Info: 0x00000000 + Feature Info: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/file/does/not/exist/a' + CodeView Record: '52534453112233441122334411223344112233441122334411' + - Base of Image: 0x0000000000003000 + Size of Image: 0x00001000 + Module Name: '/file/does/not/exist/b' + CodeView Record: '52534453112233441122334411223344112233441122334411' +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-elf-build-id-16.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-elf-build-id-16.yaml new file mode 100644 index 00000000000..f4c18b93334 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-elf-build-id-16.yaml @@ -0,0 +1,19 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM + Platform ID: Linux + CSD Version: '15E216' + CPU: + CPUID: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/a' + CodeView Record: 4C4570420102030405060708090A0B0C0D0E0F10 + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/b' + CodeView Record: 4C4570420A141E28323C46505A646E78828C96A0 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-elf-build-id-20.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-elf-build-id-20.yaml new file mode 100644 index 00000000000..e3c170fc335 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-elf-build-id-20.yaml @@ -0,0 +1,19 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM + Platform ID: Linux + CSD Version: '15E216' + CPU: + CPUID: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/a' + CodeView Record: 4C4570420102030405060708090A0B0C0D0E0F1011121314 + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/b' + CodeView Record: 4C4570420A141E28323C46505A646E78828C96A0AAB4BEC8 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-elf-build-id-zero.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-elf-build-id-zero.yaml new file mode 100644 index 00000000000..5bde77efaa7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-elf-build-id-zero.yaml @@ -0,0 +1,19 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM + Platform ID: Linux + CSD Version: '15E216' + CPU: + CPUID: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/not/exist/a' + CodeView Record: 4C45704200000000000000000000000000000000 + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/not/exist/b' + CodeView Record: 4C45704200000000000000000000000000000000 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-no-age.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-no-age.yaml new file mode 100644 index 00000000000..7b80fd51abd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-no-age.yaml @@ -0,0 +1,19 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM + Platform ID: Linux + CSD Version: '15E216' + CPU: + CPUID: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/a' + CodeView Record: 525344530102030405060708090A0B0C0D0E0F100000000000 + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/b' + CodeView Record: 525344530A141E28323C46505A646E78828C96A00000000000 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-with-age.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-with-age.yaml new file mode 100644 index 00000000000..083b313254e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-uuids-with-age.yaml @@ -0,0 +1,19 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM + Platform ID: Linux + CSD Version: '15E216' + CPU: + CPUID: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/a' + CodeView Record: 525344530102030405060708090A0B0C0D0E0F101010101000 + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/b' + CodeView Record: 525344530A141E28323C46505A646E78828C96A02020202000 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-zero-uuids.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-zero-uuids.yaml new file mode 100644 index 00000000000..7ca887cdf2c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-arm-zero-uuids.yaml @@ -0,0 +1,21 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: AMD64 + Platform ID: Linux + CSD Version: '15E216' + CPU: + Vendor ID: GenuineIntel + Version Info: 0x00000000 + Feature Info: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/file/does/not/exist/a' + CodeView Record: '52534453000000000000000000000000000000000000000000' + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/file/does/not/exist/b' + CodeView Record: '52534453000000000000000000000000000000000000000000' +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64 Binary files differnew file mode 100755 index 00000000000..078d9c8fa90 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64.cpp new file mode 100644 index 00000000000..61d31492940 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64.cpp @@ -0,0 +1,12 @@ +void crash() { + volatile int *a = (int *)(nullptr); + *a = 1; +} + +extern "C" void _start(); +void InstallBreakpad(); + +void _start() { + InstallBreakpad(); + crash(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64.dmp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64.dmp Binary files differnew file mode 100644 index 00000000000..e2ae724abe9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64.dmp diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64.yaml new file mode 100644 index 00000000000..21ea3ba5dea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64.yaml @@ -0,0 +1,44 @@ +--- !minidump +Streams: + - Type: ThreadList + Threads: + - Thread Id: 0x000074DD + Context: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000B0010000000000033000000000000000000000002020100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040109600000000000100000000000000000000000000000068E7D0C8FF7F000068E7D0C8FF7F000097E6D0C8FF7F000010109600000000000000000000000000020000000000000088E4D0C8FF7F0000603FFF85C77F0000F00340000000000080E7D0C8FF7F000000000000000000000000000000000000E0034000000000007F0300000000000000000000000000000000000000000000801F0000FFFF00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF252525252525252525252525252525250000000000000000000000000000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FF00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + Stack: + Start of Memory Range: 0x00007FFFC8D0E000 + Content: DEADBEEFBAADF00D + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000400000 + Size of Image: 0x00001000 + Module Name: '/tmp/test/linux-x86_64' + CodeView Record: 4C457042E35C283BC327C28762DB788BF5A4078BE2351448 + - Type: Exception + Thread ID: 0x000074DD + Exception Record: + Exception Code: 0x0000000B + Thread Context: 00000000 + - Type: SystemInfo + Processor Arch: AMD64 + Processor Level: 6 + Processor Revision: 15876 + Number of Processors: 40 + Platform ID: Linux + CSD Version: 'Linux 3.13.0-91-generic' + CPU: + Vendor ID: GenuineIntel + Version Info: 0x00000000 + Feature Info: 0x00000000 + - Type: LinuxProcStatus + Text: | + Name: linux-x86_64 + State: t (tracing stop) + Tgid: 29917 + Ngid: 0 + Pid: 29917 + PPid: 29370 + TracerPid: 29918 + Uid: 1001 1001 1001 1001 + Gid: 1001 1001 1001 1001 + +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_not_crashed b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_not_crashed Binary files differnew file mode 100755 index 00000000000..8b38cdb48bd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_not_crashed diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_not_crashed.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_not_crashed.cpp new file mode 100644 index 00000000000..070c565e72b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_not_crashed.cpp @@ -0,0 +1,22 @@ +void InstallBreakpad(); +void WriteMinidump(); + +int global = 42; + +int bar(int x) { + WriteMinidump(); + int y = 4 * x + global; + return y; +} + +int foo(int x) { + int y = 2 * bar(3 * x); + return y; +} + +extern "C" void _start(); + +void _start() { + InstallBreakpad(); + foo(1); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_not_crashed.dmp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_not_crashed.dmp Binary files differnew file mode 100644 index 00000000000..ad4b61a7bbb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_not_crashed.dmp diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_null_signal.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_null_signal.yaml new file mode 100644 index 00000000000..93b3fd0e8aa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/linux-x86_64_null_signal.yaml @@ -0,0 +1,25 @@ +--- !minidump +Streams: + - Type: ThreadList + Threads: + - Thread Id: 0x00002177 + Context: 0000 + Stack: + Start of Memory Range: 0x00007FFE2F689000 + Content: 00000000 + - Type: Exception + Thread ID: 0x00002177 + Exception Record: + Exception Code: 0x00000000 + Exception Address: 0x0000000000400582 + Thread Context: 0000 + - Type: SystemInfo + Processor Arch: AMD64 + Platform ID: Linux + - Type: LinuxProcStatus + Text: | + Name: busyloop + Umask: 0002 + State: t (tracing stop) + Pid: 8567 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/macos-arm-uuids-no-age.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/macos-arm-uuids-no-age.yaml new file mode 100644 index 00000000000..57e291ee1b1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/macos-arm-uuids-no-age.yaml @@ -0,0 +1,21 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: AMD64 + Platform ID: MacOSX + CSD Version: '15E216' + CPU: + Vendor ID: GenuineIntel + Version Info: 0x00000000 + Feature Info: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/a' + CodeView Record: 525344530102030405060708090A0B0C0D0E0F100000000000 + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: '/tmp/b' + CodeView Record: 525344530A141E28323C46505A646E78828C96A00000000000 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/makefile.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/makefile.txt new file mode 100644 index 00000000000..79a95d61d85 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/makefile.txt @@ -0,0 +1,29 @@ +# This makefile aims to make the binaries as small as possible, for us not to +# upload huge binary blobs in the repo. +# The binary should have debug symbols because stack unwinding doesn't work +# correctly using the information in the Minidump only. Also we want to evaluate +# local variables, etc. +# Breakpad compiles as a static library, so statically linking againts it +# makes the binary huge. +# Dynamically linking to it does improve things, but we are still #include-ing +# breakpad headers (which is a lot of source code for which we generate debug +# symbols) +# So, install_breakpad.cpp does the #include-ing and defines a global function +# "InstallBreakpad" that does all the exception handler registration. +# We compile install_breakpad to object file and then link it, alongside the +# static libbreakpad, into a shared library. +# Then the binaries dynamically link to that lib. +# The other optimisation is not using the standard library (hence the _start +# instead of main). We only link dynamically to some standard libraries. +# This way we have a tiny binary (~8K) that has debug symbols and uses breakpad +# to generate a Minidump when the binary crashes/requests such. +# +CC=g++ +FLAGS=-g --std=c++11 +INCLUDE=-I$HOME/breakpad/src/src/ +LINK=-L. -lbreakpad -lpthread -nostdlib -lc -lstdc++ -lgcc_s -fno-exceptions +all: + $(CC) $(FLAGS) -fPIC -c install_breakpad.cpp $(INCLUDE) -o install_breakpad.o + ld -shared install_breakpad.o libbreakpad_client.a -o libbreakpad.so + $(CC) $(FLAGS) -o linux-x86_64 linux-x86_64.cpp $(LINK) + $(CC) $(FLAGS) -o linux-x86_64_not_crashed linux-x86_64_not_crashed.cpp $(LINK) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/regions-linux-map.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/regions-linux-map.yaml new file mode 100644 index 00000000000..3c0961eba07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/regions-linux-map.yaml @@ -0,0 +1,33 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: ARM64 + Platform ID: Linux + CSD Version: '15E216' + CPU: + CPUID: 0x00000000 + - Type: MiscInfo + Content: 00000000010000007B000000000000000000000000000000 + - Type: LinuxMaps + Text: | + 400d9000-400db000 r-xp 00000000 b3:04 227 /system/bin/app_process + 400db000-400dc000 r--p 00001000 b3:04 227 /system/bin/app_process + 400dc000-400dd000 rw-p 00000000 00:00 0 + 400dd000-400ec000 r-xp 00000000 b3:04 300 /system/bin/linker + 400ec000-400ed000 r--p 00000000 00:00 0 + 400ed000-400ee000 r--p 0000f000 b3:04 300 /system/bin/linker + 400ee000-400ef000 rw-p 00010000 b3:04 300 /system/bin/linker + 400ef000-400fb000 rw-p 00000000 00:00 0 + 400fb000-400fc000 r-xp 00000000 b3:04 1096 /system/lib/liblog.so + 400fc000-400fd000 rwxp 00001000 b3:04 1096 /system/lib/liblog.so + 400fd000-400ff000 r-xp 00002000 b3:04 1096 /system/lib/liblog.so + 400ff000-40100000 r--p 00003000 b3:04 1096 /system/lib/liblog.so + 40100000-40101000 rw-p 00004000 b3:04 1096 /system/lib/liblog.so + 40101000-40122000 r-xp 00000000 b3:04 955 /system/lib/libc.so + 40122000-40123000 rwxp 00021000 b3:04 955 /system/lib/libc.so + 40123000-40167000 r-xp 00022000 b3:04 955 /system/lib/libc.so + 40167000-40169000 r--p 00065000 b3:04 955 /system/lib/libc.so + 40169000-4016b000 rw-p 00067000 b3:04 955 /system/lib/libc.so + 4016b000-40176000 rw-p 00000000 00:00 0 + +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/relative_module_name.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/relative_module_name.yaml new file mode 100644 index 00000000000..23f2b490280 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump-new/relative_module_name.yaml @@ -0,0 +1,17 @@ +--- !minidump +Streams: + - Type: SystemInfo + Processor Arch: AMD64 + Platform ID: Linux + CSD Version: '15E216' + CPU: + Vendor ID: GenuineIntel + Version Info: 0x00000000 + Feature Info: 0x00000000 + - Type: ModuleList + Modules: + - Base of Image: 0x0000000000001000 + Size of Image: 0x00001000 + Module Name: 'file-with-a-name-unlikely-to-exist-in-the-current-directory.so' + CodeView Record: '' +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/Makefile new file mode 100644 index 00000000000..65e9dd2fa9e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py new file mode 100644 index 00000000000..c3301fb323c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py @@ -0,0 +1,176 @@ +""" +Test basics of mini dump debugging. +""" + +from six import iteritems + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class MiniDumpTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_process_info_in_mini_dump(self): + """Test that lldb can read the process information from the minidump.""" + # target create -c fizzbuzz_no_heap.dmp + self.dbg.CreateTarget("") + self.target = self.dbg.GetSelectedTarget() + self.process = self.target.LoadCore("fizzbuzz_no_heap.dmp") + self.assertTrue(self.process, PROCESS_IS_VALID) + self.assertEqual(self.process.GetNumThreads(), 1) + self.assertEqual(self.process.GetProcessID(), 4440) + + def test_thread_info_in_mini_dump(self): + """Test that lldb can read the thread information from the minidump.""" + # target create -c fizzbuzz_no_heap.dmp + self.dbg.CreateTarget("") + self.target = self.dbg.GetSelectedTarget() + self.process = self.target.LoadCore("fizzbuzz_no_heap.dmp") + # This process crashed due to an access violation (0xc0000005) in its + # one and only thread. + self.assertEqual(self.process.GetNumThreads(), 1) + thread = self.process.GetThreadAtIndex(0) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonException) + stop_description = thread.GetStopDescription(256) + self.assertTrue("0xc0000005" in stop_description) + + def test_modules_in_mini_dump(self): + """Test that lldb can read the list of modules from the minidump.""" + # target create -c fizzbuzz_no_heap.dmp + self.dbg.CreateTarget("") + self.target = self.dbg.GetSelectedTarget() + self.process = self.target.LoadCore("fizzbuzz_no_heap.dmp") + self.assertTrue(self.process, PROCESS_IS_VALID) + expected_modules = [ + { + 'filename' : r"C:\Users\amccarth\Documents\Visual Studio 2013\Projects\fizzbuzz\Debug/fizzbuzz.exe", + 'uuid' : '0F45B791-9A96-46F9-BF8F-2D6076EA421A-00000011', + }, + { + 'filename' : r"C:\Windows\SysWOW64/ntdll.dll", + 'uuid' : 'BBB0846A-402C-4052-A16B-67650BBFE6B0-00000002', + }, + { + 'filename' : r"C:\Windows\SysWOW64/kernel32.dll", + 'uuid' : 'E5CB7E1B-005E-4113-AB98-98D6913B52D8-00000002', + }, + { + 'filename' : r"C:\Windows\SysWOW64/KERNELBASE.dll", + 'uuid' : '0BF95241-CB0D-4BD4-AC5D-186A6452E522-00000001', + }, + { + 'filename' : r"C:\Windows\System32/MSVCP120D.dll", + 'uuid' : '3C05516E-57E7-40EB-8D3F-9722C5BD80DD-00000001', + }, + { + 'filename' : r"C:\Windows\System32/MSVCR120D.dll", + 'uuid' : '6382FB86-46C4-4046-AE42-8D97B3F91FF2-00000001', + }, + ] + self.assertEqual(self.target.GetNumModules(), len(expected_modules)) + for module, expected in zip(self.target.modules, expected_modules): + self.assertTrue(module.IsValid()) + self.assertEqual(module.file.fullpath, expected['filename']) + self.assertEqual(module.GetUUIDString(), expected['uuid']) + + def test_breakpad_uuid_matching(self): + """Test that the uuid computation algorithms in minidump and breakpad + files match.""" + self.target = self.dbg.CreateTarget("") + self.process = self.target.LoadCore("fizzbuzz_no_heap.dmp") + self.assertTrue(self.process, PROCESS_IS_VALID) + self.expect("target symbols add fizzbuzz.syms", substrs=["symbol file", + "fizzbuzz.syms", "has been added to", "fizzbuzz.exe"]), + self.assertTrue(self.target.modules[0].FindSymbol("main")) + + @skipIfLLVMTargetMissing("X86") + def test_stack_info_in_mini_dump(self): + """Test that we can see a trivial stack in a VS-generate mini dump.""" + # target create -c fizzbuzz_no_heap.dmp + self.dbg.CreateTarget("") + self.target = self.dbg.GetSelectedTarget() + self.process = self.target.LoadCore("fizzbuzz_no_heap.dmp") + self.assertEqual(self.process.GetNumThreads(), 1) + thread = self.process.GetThreadAtIndex(0) + + pc_list = [ 0x00164d14, 0x00167c79, 0x00167e6d, 0x7510336a, 0x77759882, 0x77759855] + + self.assertEqual(thread.GetNumFrames(), len(pc_list)) + for i in range(len(pc_list)): + frame = thread.GetFrameAtIndex(i) + self.assertTrue(frame.IsValid()) + self.assertEqual(frame.GetPC(), pc_list[i]) + self.assertTrue(frame.GetModule().IsValid()) + + @skipUnlessWindows # Minidump saving works only on windows + def test_deeper_stack_in_mini_dump(self): + """Test that we can examine a more interesting stack in a mini dump.""" + self.build() + exe = self.getBuildArtifact("a.out") + core = self.getBuildArtifact("core.dmp") + try: + # Set a breakpoint and capture a mini dump. + target = self.dbg.CreateTarget(exe) + breakpoint = target.BreakpointCreateByName("bar") + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertEqual(process.GetState(), lldb.eStateStopped) + self.assertTrue(process.SaveCore(core)) + self.assertTrue(os.path.isfile(core)) + self.assertTrue(process.Kill().Success()) + + # Launch with the mini dump, and inspect the stack. + target = self.dbg.CreateTarget(None) + process = target.LoadCore(core) + thread = process.GetThreadAtIndex(0) + + expected_stack = {0: 'bar', 1: 'foo', 2: 'main'} + self.assertGreaterEqual(thread.GetNumFrames(), len(expected_stack)) + for index, name in iteritems(expected_stack): + frame = thread.GetFrameAtIndex(index) + self.assertTrue(frame.IsValid()) + function_name = frame.GetFunctionName() + self.assertTrue(name in function_name) + + finally: + # Clean up the mini dump file. + self.assertTrue(self.dbg.DeleteTarget(target)) + if (os.path.isfile(core)): + os.unlink(core) + + @skipUnlessWindows # Minidump saving works only on windows + def test_local_variables_in_mini_dump(self): + """Test that we can examine local variables in a mini dump.""" + self.build() + exe = self.getBuildArtifact("a.out") + core = self.getBuildArtifact("core.dmp") + try: + # Set a breakpoint and capture a mini dump. + target = self.dbg.CreateTarget(exe) + breakpoint = target.BreakpointCreateByName("bar") + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertEqual(process.GetState(), lldb.eStateStopped) + self.assertTrue(process.SaveCore(core)) + self.assertTrue(os.path.isfile(core)) + self.assertTrue(process.Kill().Success()) + + # Launch with the mini dump, and inspect a local variable. + target = self.dbg.CreateTarget(None) + process = target.LoadCore(core) + thread = process.GetThreadAtIndex(0) + frame = thread.GetFrameAtIndex(0) + value = frame.EvaluateExpression('x') + self.assertEqual(value.GetValueAsSigned(), 3) + + finally: + # Clean up the mini dump file. + self.assertTrue(self.dbg.DeleteTarget(target)) + if (os.path.isfile(core)): + os.unlink(core) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.cpp new file mode 100644 index 00000000000..295d4a1f24d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.cpp @@ -0,0 +1,31 @@ +// A sample program for getting minidumps on Windows. + +#include <iostream> + +bool +fizz(int x) +{ + return x % 3 == 0; +} + +bool +buzz(int x) +{ + return x % 5 == 0; +} + +int +main() +{ + int *buggy = 0; + + for (int i = 1; i <= 100; ++i) + { + if (fizz(i)) std::cout << "fizz"; + if (buzz(i)) std::cout << "buzz"; + if (!fizz(i) && !buzz(i)) std::cout << i; + std::cout << '\n'; + } + + return *buggy; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.syms b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.syms new file mode 100644 index 00000000000..cab06c1c9d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.syms @@ -0,0 +1,2 @@ +MODULE windows x86 0F45B7919A9646F9BF8F2D6076EA421A11 fizzbuzz.pdb
+PUBLIC 1000 0 main
diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz_no_heap.dmp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz_no_heap.dmp Binary files differnew file mode 100644 index 00000000000..19008c91fc3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz_no_heap.dmp diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/main.cpp new file mode 100644 index 00000000000..4037ea522ca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/main.cpp @@ -0,0 +1,21 @@ +int global = 42; + +int +bar(int x) +{ + int y = 4*x + global; + return y; +} + +int +foo(int x) +{ + int y = 2*bar(3*x); + return y; +} + +int +main() +{ + return 0 * foo(1); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/1lwp_SIGSEGV.aarch64 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/1lwp_SIGSEGV.aarch64 Binary files differnew file mode 100755 index 00000000000..de0208c756d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/1lwp_SIGSEGV.aarch64 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/1lwp_SIGSEGV.amd64 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/1lwp_SIGSEGV.amd64 Binary files differnew file mode 100755 index 00000000000..56fa077bd6a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/1lwp_SIGSEGV.amd64 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/1lwp_SIGSEGV.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/1lwp_SIGSEGV.c new file mode 100644 index 00000000000..972e9678af5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/1lwp_SIGSEGV.c @@ -0,0 +1,14 @@ +static void bar(char *boom) { + char F = 'b'; + *boom = 47; // Frame bar +} + +static void foo(char *boom, void (*boomer)(char *)) { + char F = 'f'; + boomer(boom); // Frame foo +} + +void main(void) { + char F = 'm'; + foo(0, bar); // Frame main +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_process_SIGSEGV.aarch64 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_process_SIGSEGV.aarch64 Binary files differnew file mode 100755 index 00000000000..8781f033c5a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_process_SIGSEGV.aarch64 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_process_SIGSEGV.amd64 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_process_SIGSEGV.amd64 Binary files differnew file mode 100755 index 00000000000..32a49852215 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_process_SIGSEGV.amd64 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_process_SIGSEGV.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_process_SIGSEGV.c new file mode 100644 index 00000000000..fcbfa8a6b51 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_process_SIGSEGV.c @@ -0,0 +1,37 @@ +#include <lwp.h> +#include <stddef.h> +#include <stdlib.h> +#include <unistd.h> +#include <signal.h> + +volatile int sem = 0; + +static void bar() { + char F = 'b'; + sem = 1; + while (1) continue; // Frame bar +} + +static void foo(void (*boomer)()) { + char F = 'f'; + boomer(); // Frame foo +} + +static void lwp_main(void *unused) { + char F = 'l'; + foo(bar); // Frame lwp_main +} + +int main(int argc, char **argv) { + ucontext_t uc; + lwpid_t lid; + static const size_t ssize = 16 * 1024; + void *stack; + + stack = malloc(ssize); + _lwp_makecontext(&uc, lwp_main, NULL, NULL, stack, ssize); + _lwp_create(&uc, 0, &lid); + while (sem != 1) continue; + kill(getpid(), SIGSEGV); + _lwp_wait(lid, NULL); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_t2_SIGSEGV.aarch64 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_t2_SIGSEGV.aarch64 Binary files differnew file mode 100755 index 00000000000..89394a7c084 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_t2_SIGSEGV.aarch64 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_t2_SIGSEGV.amd64 b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_t2_SIGSEGV.amd64 Binary files differnew file mode 100755 index 00000000000..d304de160f0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_t2_SIGSEGV.amd64 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_t2_SIGSEGV.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_t2_SIGSEGV.c new file mode 100644 index 00000000000..1cd86631edd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/2lwp_t2_SIGSEGV.c @@ -0,0 +1,30 @@ +#include <lwp.h> +#include <stddef.h> +#include <stdlib.h> + +static void bar(char *boom) { + char F = 'b'; + *boom = 47; // Frame bar +} + +static void foo(char *boom, void (*boomer)(char *)) { + char F = 'f'; + boomer(boom); // Frame foo +} + +void lwp_main(void *unused) { + char F = 'l'; + foo(0, bar); // Frame lwp_main +} + +int main(int argc, char **argv) { + ucontext_t uc; + lwpid_t lid; + static const size_t ssize = 16 * 1024; + void *stack; + + stack = malloc(ssize); + _lwp_makecontext(&uc, lwp_main, NULL, NULL, stack, ssize); + _lwp_create(&uc, 0, &lid); + _lwp_wait(lid, NULL); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/GNUmakefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/GNUmakefile new file mode 100644 index 00000000000..62c719d3d2f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/GNUmakefile @@ -0,0 +1,15 @@ +ARCH = $(shell uname -m) +PROGRAMS = 1lwp_SIGSEGV 2lwp_t2_SIGSEGV 2lwp_process_SIGSEGV +EXECS = $(patsubst %,%.$(ARCH),$(PROGRAMS)) +CORES = $(patsubst %,%.core,$(EXECS)) + +all: $(CORES) $(EXECS) +clean: + rm -f $(CORES) $(EXECS) + +%.core: % + sysctl -w proc.$$$$.corename=$@; ulimit -s 16; ! ./$< +%.$(ARCH): %.c + $(CC) -o $@ -g $< + +.PHONY: all clean diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/TestNetBSDCore.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/TestNetBSDCore.py new file mode 100644 index 00000000000..067b04d997d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/netbsd-core/TestNetBSDCore.py @@ -0,0 +1,237 @@ +""" +Test NetBSD core file debugging. +""" + +from __future__ import division, print_function + +import signal +import os + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NetBSDCoreCommonTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + super(NetBSDCoreCommonTestCase, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(NetBSDCoreCommonTestCase, self).tearDown() + + def check_memory_regions(self, process, region_count): + region_list = process.GetMemoryRegions() + self.assertEqual(region_list.GetSize(), region_count) + + region = lldb.SBMemoryRegionInfo() + + # Check we have the right number of regions. + self.assertEqual(region_list.GetSize(), region_count) + + # Check that getting a region beyond the last in the list fails. + self.assertFalse( + region_list.GetMemoryRegionAtIndex( + region_count, region)) + + # Check each region is valid. + for i in range(region_list.GetSize()): + # Check we can actually get this region. + self.assertTrue(region_list.GetMemoryRegionAtIndex(i, region)) + + # Every region in the list should be mapped. + self.assertTrue(region.IsMapped()) + + # Test the address at the start of a region returns it's enclosing + # region. + begin_address = region.GetRegionBase() + region_at_begin = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo(begin_address, region_at_begin) + self.assertEqual(region, region_at_begin) + + # Test an address in the middle of a region returns it's enclosing + # region. + middle_address = (region.GetRegionBase() + + region.GetRegionEnd()) // 2 + region_at_middle = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo( + middle_address, region_at_middle) + self.assertEqual(region, region_at_middle) + + # Test the address at the end of a region returns it's enclosing + # region. + end_address = region.GetRegionEnd() - 1 + region_at_end = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo(end_address, region_at_end) + self.assertEqual(region, region_at_end) + + # Check that quering the end address does not return this region but + # the next one. + next_region = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo( + region.GetRegionEnd(), next_region) + self.assertNotEqual(region, next_region) + self.assertEqual( + region.GetRegionEnd(), + next_region.GetRegionBase()) + + # Check that query beyond the last region returns an unmapped region + # that ends at LLDB_INVALID_ADDRESS + last_region = lldb.SBMemoryRegionInfo() + region_list.GetMemoryRegionAtIndex(region_count - 1, last_region) + end_region = lldb.SBMemoryRegionInfo() + error = process.GetMemoryRegionInfo( + last_region.GetRegionEnd(), end_region) + self.assertFalse(end_region.IsMapped()) + self.assertEqual( + last_region.GetRegionEnd(), + end_region.GetRegionBase()) + self.assertEqual(end_region.GetRegionEnd(), lldb.LLDB_INVALID_ADDRESS) + + def check_state(self, process): + with open(os.devnull) as devnul: + # sanitize test output + self.dbg.SetOutputFileHandle(devnul, False) + self.dbg.SetErrorFileHandle(devnul, False) + + self.assertTrue(process.is_stopped) + + # Process.Continue + error = process.Continue() + self.assertFalse(error.Success()) + self.assertTrue(process.is_stopped) + + # Thread.StepOut + thread = process.GetSelectedThread() + thread.StepOut() + self.assertTrue(process.is_stopped) + + # command line + self.dbg.HandleCommand('s') + self.assertTrue(process.is_stopped) + self.dbg.HandleCommand('c') + self.assertTrue(process.is_stopped) + + # restore file handles + self.dbg.SetOutputFileHandle(None, False) + self.dbg.SetErrorFileHandle(None, False) + + def check_backtrace(self, thread, filename, backtrace): + self.assertGreaterEqual(thread.GetNumFrames(), len(backtrace)) + src = filename.rpartition('.')[0] + '.c' + for i in range(len(backtrace)): + frame = thread.GetFrameAtIndex(i) + self.assertTrue(frame) + if not backtrace[i].startswith('_'): + self.assertEqual(frame.GetFunctionName(), backtrace[i]) + self.assertEqual(frame.GetLineEntry().GetLine(), + line_number(src, "Frame " + backtrace[i])) + self.assertEqual( + frame.FindVariable("F").GetValueAsUnsigned(), ord( + backtrace[i][0])) + + def do_test(self, filename, pid, region_count): + target = self.dbg.CreateTarget(filename) + process = target.LoadCore(filename + ".core") + + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetNumThreads(), self.THREAD_COUNT) + self.assertEqual(process.GetProcessID(), pid) + + self.check_state(process) + + self.check_stack(process, pid, filename) + + self.check_memory_regions(process, region_count) + + self.dbg.DeleteTarget(target) + + +class NetBSD1LWPCoreTestCase(NetBSDCoreCommonTestCase): + THREAD_COUNT = 1 + + def check_stack(self, process, pid, filename): + thread = process.GetSelectedThread() + self.assertTrue(thread) + self.assertEqual(thread.GetThreadID(), 1) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonSignal) + self.assertEqual(thread.GetStopReasonDataCount(), 1) + self.assertEqual(thread.GetStopReasonDataAtIndex(0), signal.SIGSEGV) + backtrace = ["bar", "foo", "main"] + self.check_backtrace(thread, filename, backtrace) + + @skipIfLLVMTargetMissing("AArch64") + def test_aarch64(self): + """Test single-threaded aarch64 core dump.""" + self.do_test("1lwp_SIGSEGV.aarch64", pid=8339, region_count=32) + + @skipIfLLVMTargetMissing("X86") + def test_amd64(self): + """Test single-threaded amd64 core dump.""" + self.do_test("1lwp_SIGSEGV.amd64", pid=693, region_count=21) + + +class NetBSD2LWPT2CoreTestCase(NetBSDCoreCommonTestCase): + THREAD_COUNT = 2 + + def check_stack(self, process, pid, filename): + thread = process.GetSelectedThread() + self.assertTrue(thread) + self.assertEqual(thread.GetThreadID(), 2) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonSignal) + self.assertEqual(thread.GetStopReasonDataCount(), 1) + self.assertEqual(thread.GetStopReasonDataAtIndex(0), signal.SIGSEGV) + backtrace = ["bar", "foo", "lwp_main"] + self.check_backtrace(thread, filename, backtrace) + + # thread 1 should have no signal + thread = process.GetThreadByID(1) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonSignal) + self.assertEqual(thread.GetStopReasonDataCount(), 1) + self.assertEqual(thread.GetStopReasonDataAtIndex(0), 0) + + @skipIfLLVMTargetMissing("AArch64") + def test_aarch64(self): + """Test double-threaded aarch64 core dump where thread 2 is signalled.""" + self.do_test("2lwp_t2_SIGSEGV.aarch64", pid=14142, region_count=31) + + @skipIfLLVMTargetMissing("X86") + def test_amd64(self): + """Test double-threaded amd64 core dump where thread 2 is signalled.""" + self.do_test("2lwp_t2_SIGSEGV.amd64", pid=622, region_count=24) + + +class NetBSD2LWPProcessSigCoreTestCase(NetBSDCoreCommonTestCase): + THREAD_COUNT = 2 + + def check_stack(self, process, pid, filename): + thread = process.GetSelectedThread() + self.assertTrue(thread) + self.assertEqual(thread.GetThreadID(), 2) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonSignal) + self.assertEqual(thread.GetStopReasonDataCount(), 1) + self.assertEqual(thread.GetStopReasonDataAtIndex(0), signal.SIGSEGV) + backtrace = ["bar", "foo", "lwp_main"] + self.check_backtrace(thread, filename, backtrace) + + # thread 1 should have the same signal + thread = process.GetThreadByID(1) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonSignal) + self.assertEqual(thread.GetStopReasonDataCount(), 1) + self.assertEqual(thread.GetStopReasonDataAtIndex(0), signal.SIGSEGV) + + @skipIfLLVMTargetMissing("AArch64") + def test_aarch64(self): + """Test double-threaded aarch64 core dump where process is signalled.""" + self.do_test("2lwp_process_SIGSEGV.aarch64", pid=1403, region_count=30) + + @skipIfLLVMTargetMissing("X86") + def test_amd64(self): + """Test double-threaded amd64 core dump where process is signalled.""" + self.do_test("2lwp_process_SIGSEGV.amd64", pid=665, region_count=24) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/TestWow64MiniDump.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/TestWow64MiniDump.py new file mode 100644 index 00000000000..cbfc8525ea2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/TestWow64MiniDump.py @@ -0,0 +1,72 @@ +""" +Test basics of a mini dump taken of a 32-bit process running in WoW64 + +WoW64 is the subsystem that lets 32-bit processes run in 64-bit Windows. If you +capture a mini dump of a process running under WoW64 with a 64-bit debugger, you +end up with a dump of the WoW64 layer. In that case, LLDB must do extra work to +get the 32-bit register contexts. +""" + +from six import iteritems + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class Wow64MiniDumpTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_wow64_mini_dump(self): + """Test that lldb can read the process information from the minidump.""" + # target create -c fizzbuzz_wow64.dmp + target = self.dbg.CreateTarget("") + process = target.LoadCore("fizzbuzz_wow64.dmp") + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetNumThreads(), 1) + self.assertEqual(process.GetProcessID(), 0x1E9C) + + def test_thread_info_in_wow64_mini_dump(self): + """Test that lldb can read the thread information from the minidump.""" + # target create -c fizzbuzz_wow64.dmp + target = self.dbg.CreateTarget("") + process = target.LoadCore("fizzbuzz_wow64.dmp") + # This process crashed due to an access violation (0xc0000005), but the + # minidump doesn't have an exception record--perhaps the crash handler + # ate it. + # TODO: See if we can recover the exception information from the TEB, + # which, according to Windbg, has a pointer to an exception list. + + # In the dump, none of the threads are stopped, so we cannot use + # lldbutil.get_stopped_thread. + thread = process.GetThreadAtIndex(0) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonNone) + + def test_stack_info_in_wow64_mini_dump(self): + """Test that we can see a trivial stack in a VS-generate mini dump.""" + # target create -c fizzbuzz_no_heap.dmp + target = self.dbg.CreateTarget("") + process = target.LoadCore("fizzbuzz_wow64.dmp") + self.assertGreaterEqual(process.GetNumThreads(), 1) + # This process crashed due to an access violation (0xc0000005), but the + # minidump doesn't have an exception record--perhaps the crash handler + # ate it. + # TODO: See if we can recover the exception information from the TEB, + # which, according to Windbg, has a pointer to an exception list. + + # In the dump, none of the threads are stopped, so we cannot use + # lldbutil.get_stopped_thread. + thread = process.GetThreadAtIndex(0) + # The crash is in main, so there should be at least one frame on the + # stack. + self.assertGreaterEqual(thread.GetNumFrames(), 1) + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame.IsValid()) + pc = frame.GetPC() + eip = frame.FindRegister("pc") + self.assertTrue(eip.IsValid()) + self.assertEqual(pc, eip.GetValueAsUnsigned()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/fizzbuzz.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/fizzbuzz.cpp new file mode 100644 index 00000000000..295d4a1f24d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/fizzbuzz.cpp @@ -0,0 +1,31 @@ +// A sample program for getting minidumps on Windows. + +#include <iostream> + +bool +fizz(int x) +{ + return x % 3 == 0; +} + +bool +buzz(int x) +{ + return x % 5 == 0; +} + +int +main() +{ + int *buggy = 0; + + for (int i = 1; i <= 100; ++i) + { + if (fizz(i)) std::cout << "fizz"; + if (buzz(i)) std::cout << "buzz"; + if (!fizz(i) && !buzz(i)) std::cout << i; + std::cout << '\n'; + } + + return *buggy; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/fizzbuzz_wow64.dmp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/fizzbuzz_wow64.dmp Binary files differnew file mode 100644 index 00000000000..3d97186f2cd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/postmortem/wow64_minidump/fizzbuzz_wow64.dmp diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/Makefile new file mode 100644 index 00000000000..032f9cda29c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/Makefile @@ -0,0 +1,4 @@ +DYLIB_NAME := unlikely_name +DYLIB_CXX_SOURCES := foo.cpp +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/TestPreRunDylibs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/TestPreRunDylibs.py new file mode 100644 index 00000000000..1ac18a771f1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/TestPreRunDylibs.py @@ -0,0 +1,33 @@ + +import unittest2 +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * + +class TestPreRunLibraries(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipIf(oslist=no_match(['darwin','macos'])) + def test(self): + """Test that we find directly linked dylib pre-run.""" + + self.build() + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # I don't know what the name of a shared library + # extension is in general, so instead of using FindModule, + # I'll iterate through the module and do a basename match. + found_it = False + for module in target.modules: + file_name = module.GetFileSpec().GetFilename() + if file_name.find("unlikely_name") != -1: + found_it = True + break + + self.assertTrue(found_it, "Couldn't find unlikely_to_occur_name in loaded libraries.") + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/foo.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/foo.cpp new file mode 100644 index 00000000000..8dad0a23f36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/foo.cpp @@ -0,0 +1,3 @@ +#include "foo.h" + +int call_foo1() { return foo1(); } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/foo.h new file mode 100644 index 00000000000..060b91f5a5e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/foo.h @@ -0,0 +1,6 @@ +LLDB_TEST_API inline int foo1() { return 1; } // !BR1 + +LLDB_TEST_API inline int foo2() { return 2; } // !BR2 + +LLDB_TEST_API extern int call_foo1(); +LLDB_TEST_API extern int call_foo2(); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/main.cpp new file mode 100644 index 00000000000..c9295a5c7d3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/pre_run_dylibs/main.cpp @@ -0,0 +1,9 @@ +#include "foo.h" + +int call_foo2() { return foo2(); } + +int +main() // !BR_main +{ + return call_foo1() + call_foo2(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_group/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_group/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_group/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py new file mode 100644 index 00000000000..fe541c7832c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py @@ -0,0 +1,90 @@ +"""Test that we handle inferiors which change their process group""" + + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ChangeProcessGroupTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.c. + self.line = line_number('main.c', '// Set breakpoint here') + + @skipIfFreeBSD # Times out on FreeBSD llvm.org/pr23731 + @skipIfWindows # setpgid call does not exist on Windows + @expectedFailureAndroid("http://llvm.org/pr23762", api_levels=[16]) + @expectedFailureNetBSD + def test_setpgid(self): + self.build() + exe = self.getBuildArtifact("a.out") + + # Use a file as a synchronization point between test and inferior. + pid_file_path = lldbutil.append_to_process_working_directory(self, + "pid_file_%d" % (int(time.time()))) + self.addTearDownHook( + lambda: self.run_platform_command( + "rm %s" % + (pid_file_path))) + + popen = self.spawnSubprocess(exe, [pid_file_path]) + self.addTearDownHook(self.cleanupSubprocesses) + + pid = lldbutil.wait_for_file_on_target(self, pid_file_path) + + # make sure we cleanup the forked child also + def cleanupChild(): + if lldb.remote_platform: + lldb.remote_platform.Kill(int(pid)) + else: + if os.path.exists("/proc/" + pid): + os.kill(int(pid), signal.SIGKILL) + self.addTearDownHook(cleanupChild) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + listener = lldb.SBListener("my.attach.listener") + error = lldb.SBError() + process = target.AttachToProcessWithID(listener, int(pid), error) + self.assertTrue(error.Success() and process, PROCESS_IS_VALID) + + # set a breakpoint just before the setpgid() call + lldbutil.run_break_set_by_file_and_line( + self, 'main.c', self.line, num_expected_locations=-1) + + thread = process.GetSelectedThread() + + # release the child from its loop + value = thread.GetSelectedFrame().EvaluateExpression("release_child_flag = 1") + self.assertTrue(value.IsValid() and value.GetValueAsUnsigned(0) == 1) + process.Continue() + + # make sure the child's process group id is different from its pid + value = thread.GetSelectedFrame().EvaluateExpression("(int)getpgid(0)") + self.assertTrue(value.IsValid()) + self.assertNotEqual(value.GetValueAsUnsigned(0), int(pid)) + + # step over the setpgid() call + thread.StepOver() + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonPlanComplete) + + # verify that the process group has been set correctly + # this also checks that we are still in full control of the child + value = thread.GetSelectedFrame().EvaluateExpression("(int)getpgid(0)") + self.assertTrue(value.IsValid()) + self.assertEqual(value.GetValueAsUnsigned(0), int(pid)) + + # run to completion + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateExited) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_group/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_group/main.c new file mode 100644 index 00000000000..7e986bbac65 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_group/main.c @@ -0,0 +1,71 @@ +#include <stdio.h> +#include <unistd.h> +#include <sys/wait.h> + +volatile int release_child_flag = 0; + +int main(int argc, char const *argv[]) +{ + pid_t child = fork(); + if (child == -1) + { + perror("fork"); + return 1; + } + + if (child > 0) + { // parent + if (argc < 2) + { + fprintf(stderr, "Need pid filename.\n"); + return 2; + } + + // Let the test suite know the child's pid. + FILE *pid_file = fopen(argv[1], "w"); + if (pid_file == NULL) + { + perror("fopen"); + return 3; + } + + fprintf(pid_file, "%d\n", child); + if (fclose(pid_file) == EOF) + { + perror("fclose"); + return 4; + } + + // And wait for the child to finish it's work. + int status = 0; + pid_t wpid = wait(&status); + if (wpid == -1) + { + perror("wait"); + return 5; + } + if (wpid != child) + { + fprintf(stderr, "wait() waited for wrong child\n"); + return 6; + } + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) + { + fprintf(stderr, "child did not exit correctly\n"); + return 7; + } + } + else + { // child + lldb_enable_attach(); + + while (! release_child_flag) // Wait for debugger to attach + sleep(1); + + printf("Child's previous process group is: %d\n", getpgid(0)); + setpgid(0, 0); // Set breakpoint here + printf("Child's process group set to: %d\n", getpgid(0)); + } + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/Makefile new file mode 100644 index 00000000000..65e9dd2fa9e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py new file mode 100644 index 00000000000..d561af02d30 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py @@ -0,0 +1,65 @@ +""" +Test saving a core file (or mini dump). +""" + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ProcessSaveCoreTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @not_remote_testsuite_ready + @skipUnlessWindows + def test_cannot_save_core_unless_process_stopped(self): + """Test that SaveCore fails if the process isn't stopped.""" + self.build() + exe = self.getBuildArtifact("a.out") + core = self.getBuildArtifact("core.dmp") + target = self.dbg.CreateTarget(exe) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertNotEqual(process.GetState(), lldb.eStateStopped) + error = process.SaveCore(core) + self.assertTrue(error.Fail()) + + @not_remote_testsuite_ready + @skipUnlessWindows + def test_save_windows_mini_dump(self): + """Test that we can save a Windows mini dump.""" + self.build() + exe = self.getBuildArtifact("a.out") + core = self.getBuildArtifact("core.dmp") + try: + target = self.dbg.CreateTarget(exe) + breakpoint = target.BreakpointCreateByName("bar") + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertEqual(process.GetState(), lldb.eStateStopped) + self.assertTrue(process.SaveCore(core)) + self.assertTrue(os.path.isfile(core)) + self.assertTrue(process.Kill().Success()) + + # To verify, we'll launch with the mini dump, and ensure that we see + # the executable in the module list. + target = self.dbg.CreateTarget(None) + process = target.LoadCore(core) + files = [ + target.GetModuleAtIndex(i).GetFileSpec() for i in range( + 0, target.GetNumModules())] + paths = [ + os.path.join( + f.GetDirectory(), + f.GetFilename()) for f in files] + self.assertTrue(exe in paths) + + finally: + # Clean up the mini dump file. + self.assertTrue(self.dbg.DeleteTarget(target)) + if (os.path.isfile(core)): + os.unlink(core) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/main.cpp new file mode 100644 index 00000000000..4037ea522ca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/process_save_core/main.cpp @@ -0,0 +1,21 @@ +int global = 42; + +int +bar(int x) +{ + int y = 4*x + global; + return y; +} + +int +foo(int x) +{ + int y = 2*bar(3*x); + return y; +} + +int +main() +{ + return 0 * foo(1); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/TestPtrRefs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/TestPtrRefs.py new file mode 100644 index 00000000000..8ca26398fca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/TestPtrRefs.py @@ -0,0 +1,46 @@ +""" +Test the ptr_refs tool on Darwin +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestPtrRefs(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_ptr_refs(self): + """Test format string functionality.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + main_file_spec = lldb.SBFileSpec('main.c') + breakpoint = target.BreakpointCreateBySourceRegex( + 'break', main_file_spec) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.line1 and the break condition should hold. + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + + frame = thread.GetFrameAtIndex(0) + + self.dbg.HandleCommand("script import lldb.macosx.heap") + self.expect("ptr_refs my_ptr", substrs=["malloc", "stack"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/main.c new file mode 100644 index 00000000000..f46862efd8b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ptr_refs/main.c @@ -0,0 +1,26 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +struct referent { + const char *p; +}; + +int main (int argc, char const *argv[]) +{ + const char *my_ptr = strdup("hello"); + struct referent *r = malloc(sizeof(struct referent)); + r->p = my_ptr; + + printf("%p\n", r); // break here + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/recursion/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/recursion/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/recursion/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py new file mode 100644 index 00000000000..e949f1a1a07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py @@ -0,0 +1,67 @@ +""" +Test lldb data formatter subsystem. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class ValueObjectRecursionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that deeply nested ValueObjects still work.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + root = self.frame().FindVariable("root") + child = root.GetChildAtIndex(1) + if self.TraceOn(): + print(root) + print(child) + for i in range(0, 15000): + child = child.GetChildAtIndex(1) + if self.TraceOn(): + print(child) + self.assertTrue( + child.IsValid(), + "could not retrieve the deep ValueObject") + self.assertTrue( + child.GetChildAtIndex(0).IsValid(), + "the deep ValueObject has no value") + self.assertTrue( + child.GetChildAtIndex(0).GetValueAsUnsigned() != 0, + "the deep ValueObject has a zero value") + self.assertTrue( + child.GetChildAtIndex(1).GetValueAsUnsigned() != 0, + "the deep ValueObject has no next") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/recursion/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/recursion/main.cpp new file mode 100644 index 00000000000..bd5278ace7d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/recursion/main.cpp @@ -0,0 +1,40 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> + +struct node; +struct node { + int value; + node* next; + node () : value(1),next(NULL) {} + node (int v) : value(v), next(NULL) {} +}; + +void make_tree(node* root, int count) +{ + int countdown=1; + if (!root) + return; + root->value = countdown; + while (count > 0) + { + root->next = new node(++countdown); + root = root->next; + count--; + } +} + +int main (int argc, const char * argv[]) +{ + node root(1); + make_tree(&root,25000); + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/rerun/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/rerun/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/rerun/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py new file mode 100644 index 00000000000..d2e5701f28e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py @@ -0,0 +1,60 @@ +""" +Test that argdumper is a viable launching strategy. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestRerun(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test(self): + self.build() + exe = self.getBuildArtifact("a.out") + + self.runCmd("target create %s" % exe) + + # Create the target + target = self.dbg.CreateTarget(exe) + + # Create any breakpoints we need + breakpoint = target.BreakpointCreateBySourceRegex( + 'break here', lldb.SBFileSpec("main.cpp", False)) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + self.runCmd("process launch 1 2 3") + + process = self.process() + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, breakpoint) + self.assertIsNotNone( + thread, "Process should be stopped at a breakpoint in main") + self.assertTrue(thread.IsValid(), "Stopped thread is not valid") + + self.expect("frame variable argv[1]", substrs=['1']) + self.expect("frame variable argv[2]", substrs=['2']) + self.expect("frame variable argv[3]", substrs=['3']) + + # Let program exit + self.runCmd("continue") + + # Re-run with no args and make sure we still run with 1 2 3 as arguments as + # they should have been stored in "target.run-args" + self.runCmd("process launch") + + process = self.process() + thread = lldbutil.get_one_thread_stopped_at_breakpoint( + process, breakpoint) + + self.assertIsNotNone( + thread, "Process should be stopped at a breakpoint in main") + self.assertTrue(thread.IsValid(), "Stopped thread is not valid") + + self.expect("frame variable argv[1]", substrs=['1']) + self.expect("frame variable argv[2]", substrs=['2']) + self.expect("frame variable argv[3]", substrs=['3']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/rerun/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/rerun/main.cpp new file mode 100644 index 00000000000..cbef8d1e6da --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/rerun/main.cpp @@ -0,0 +1,5 @@ +int +main (int argc, char const **argv) +{ + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/return-value/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/return-value/Makefile new file mode 100644 index 00000000000..138642ce206 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/return-value/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := call-func.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py new file mode 100644 index 00000000000..a5439b11a18 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py @@ -0,0 +1,279 @@ +""" +Test getting return-values correctly when stepping out +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ReturnValueTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def affected_by_pr33042(self): + return ("clang" in self.getCompiler() and self.getArchitecture() == + "aarch64" and self.getPlatform() == "linux") + + def affected_by_pr44132(self): + return (self.getArchitecture() == "aarch64" and self.getPlatform() == "linux") + + # ABIMacOSX_arm can't fetch simple values inside a structure + def affected_by_radar_34562999(self): + return (self.getArchitecture() == 'armv7' or self.getArchitecture() == 'armv7k') and self.platformIsDarwin() + + @expectedFailureAll(oslist=["freebsd"], archs=["i386"]) + @expectedFailureAll(oslist=["macosx"], archs=["i386"], bugnumber="<rdar://problem/28719652>") + @expectedFailureAll( + oslist=["linux"], + compiler="clang", + compiler_version=[ + "<=", + "3.6"], + archs=["i386"]) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + @add_test_categories(['pyapi']) + def test_with_python(self): + """Test getting return values from stepping out.""" + self.build() + exe = self.getBuildArtifact("a.out") + (self.target, self.process, thread, inner_sint_bkpt) = lldbutil.run_to_name_breakpoint(self, "inner_sint", exe_name = exe) + + error = lldb.SBError() + + # inner_sint returns the variable value, so capture that here: + in_int = thread.GetFrameAtIndex(0).FindVariable( + "value").GetValueAsSigned(error) + self.assertTrue(error.Success()) + + thread.StepOut() + + self.assertTrue(self.process.GetState() == lldb.eStateStopped) + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) + + frame = thread.GetFrameAtIndex(0) + fun_name = frame.GetFunctionName() + self.assertTrue(fun_name == "outer_sint(int)") + + return_value = thread.GetStopReturnValue() + self.assertTrue(return_value.IsValid()) + + ret_int = return_value.GetValueAsSigned(error) + self.assertTrue(error.Success()) + self.assertTrue(in_int == ret_int) + + # Run again and we will stop in inner_sint the second time outer_sint is called. + # Then test stepping out two frames at once: + + thread_list = lldbutil.continue_to_breakpoint(self.process, inner_sint_bkpt) + self.assertTrue(len(thread_list) == 1) + thread = thread_list[0] + + # We are done with the inner_sint breakpoint: + self.target.BreakpointDelete(inner_sint_bkpt.GetID()) + + frame = thread.GetFrameAtIndex(1) + fun_name = frame.GetFunctionName() + self.assertTrue(fun_name == "outer_sint(int)") + in_int = frame.FindVariable("value").GetValueAsSigned(error) + self.assertTrue(error.Success()) + + thread.StepOutOfFrame(frame) + + self.assertTrue(self.process.GetState() == lldb.eStateStopped) + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) + frame = thread.GetFrameAtIndex(0) + fun_name = frame.GetFunctionName() + self.assertTrue(fun_name == "main") + + ret_value = thread.GetStopReturnValue() + self.assertTrue(return_value.IsValid()) + ret_int = ret_value.GetValueAsSigned(error) + self.assertTrue(error.Success()) + self.assertTrue(2 * in_int == ret_int) + + # Now try some simple returns that have different types: + inner_float_bkpt = self.target.BreakpointCreateByName( + "inner_float(float)", exe) + self.assertTrue(inner_float_bkpt, VALID_BREAKPOINT) + self.process.Continue() + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + self.process, inner_float_bkpt) + self.assertTrue(len(thread_list) == 1) + thread = thread_list[0] + + self.target.BreakpointDelete(inner_float_bkpt.GetID()) + + frame = thread.GetFrameAtIndex(0) + in_value = frame.FindVariable("value") + in_float = float(in_value.GetValue()) + thread.StepOut() + + self.assertTrue(self.process.GetState() == lldb.eStateStopped) + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) + + frame = thread.GetFrameAtIndex(0) + fun_name = frame.GetFunctionName() + self.assertTrue(fun_name == "outer_float(float)") + + #return_value = thread.GetStopReturnValue() + #self.assertTrue(return_value.IsValid()) + #return_float = float(return_value.GetValue()) + + #self.assertTrue(in_float == return_float) + + if not self.affected_by_radar_34562999() and not self.affected_by_pr44132(): + self.return_and_test_struct_value("return_one_int") + self.return_and_test_struct_value("return_two_int") + self.return_and_test_struct_value("return_three_int") + self.return_and_test_struct_value("return_four_int") + if not self.affected_by_pr33042(): + self.return_and_test_struct_value("return_five_int") + + self.return_and_test_struct_value("return_two_double") + self.return_and_test_struct_value("return_one_double_two_float") + self.return_and_test_struct_value("return_one_int_one_float_one_int") + + self.return_and_test_struct_value("return_one_pointer") + self.return_and_test_struct_value("return_two_pointer") + self.return_and_test_struct_value("return_one_float_one_pointer") + self.return_and_test_struct_value("return_one_int_one_pointer") + self.return_and_test_struct_value("return_three_short_one_float") + + self.return_and_test_struct_value("return_one_int_one_double") + self.return_and_test_struct_value("return_one_int_one_double_one_int") + self.return_and_test_struct_value( + "return_one_short_one_double_one_short") + self.return_and_test_struct_value("return_one_float_one_int_one_float") + self.return_and_test_struct_value("return_two_float") + # I am leaving out the packed test until we have a way to tell CLANG + # about alignment when reading DWARF for packed types. + #self.return_and_test_struct_value ("return_one_int_one_double_packed") + self.return_and_test_struct_value("return_one_int_one_long") + + @expectedFailureAll(oslist=["freebsd"], archs=["i386"]) + @expectedFailureAll(oslist=["macosx"], archs=["i386"], bugnumber="<rdar://problem/28719652>") + @expectedFailureAll( + oslist=["linux"], + compiler="clang", + compiler_version=[ + "<=", + "3.6"], + archs=["i386"]) + @expectedFailureAll(compiler=["gcc"], archs=["x86_64", "i386"]) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + @skipIfDarwinEmbedded # <rdar://problem/33976032> ABIMacOSX_arm64 doesn't get structs this big correctly + def test_vector_values(self): + self.build() + exe = self.getBuildArtifact("a.out") + error = lldb.SBError() + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + main_bktp = self.target.BreakpointCreateByName("main", exe) + self.assertTrue(main_bktp, VALID_BREAKPOINT) + + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertEqual(len(lldbutil.get_threads_stopped_at_breakpoint( + self.process, main_bktp)), 1) + + self.return_and_test_struct_value("return_vector_size_float32_8") + self.return_and_test_struct_value("return_vector_size_float32_16") + if not self.affected_by_pr44132(): + self.return_and_test_struct_value("return_vector_size_float32_32") + self.return_and_test_struct_value("return_ext_vector_size_float32_2") + self.return_and_test_struct_value("return_ext_vector_size_float32_4") + if not self.affected_by_pr44132(): + self.return_and_test_struct_value("return_ext_vector_size_float32_8") + + # limit the nested struct and class tests to only x86_64 + @skipIf(archs=no_match(['x86_64'])) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_for_cpp_support(self): + self.build() + exe = self.getBuildArtifact("a.out") + (self.target, self.process, thread, inner_sint_bkpt) = lldbutil.run_to_name_breakpoint(self, "inner_sint", exe_name = exe) + + error = lldb.SBError() + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + main_bktp = self.target.BreakpointCreateByName("main", exe) + self.assertTrue(main_bktp, VALID_BREAKPOINT) + + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertEqual(len(lldbutil.get_threads_stopped_at_breakpoint( + self.process, main_bktp)), 1) + # nested struct tests + self.return_and_test_struct_value("return_nested_one_float_three_base") + self.return_and_test_struct_value("return_double_nested_one_float_one_nested") + self.return_and_test_struct_value("return_nested_float_struct") + # class test + self.return_and_test_struct_value("return_base_class_one_char") + self.return_and_test_struct_value("return_nested_class_float_and_base") + self.return_and_test_struct_value("return_double_nested_class_float_and_nested") + self.return_and_test_struct_value("return_base_class") + self.return_and_test_struct_value("return_derived_class") + + @skipIf(compiler="clang", compiler_version=['<', '7.0']) + def return_and_test_struct_value(self, func_name): + """Pass in the name of the function to return from - takes in value, returns value.""" + + # Set the breakpoint, run to it, finish out. + bkpt = self.target.BreakpointCreateByName(func_name) + self.assertTrue(bkpt.GetNumResolvedLocations() > 0) + + self.process.Continue() + + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + self.process, bkpt) + + self.assertTrue(len(thread_list) == 1) + thread = thread_list[0] + + self.target.BreakpointDelete(bkpt.GetID()) + + in_value = thread.GetFrameAtIndex(0).FindVariable("value") + + self.assertTrue(in_value.IsValid()) + num_in_children = in_value.GetNumChildren() + + # This is a little hokey, but if we don't get all the children now, then + # once we've stepped we won't be able to get them? + + for idx in range(0, num_in_children): + in_child = in_value.GetChildAtIndex(idx) + in_child_str = in_child.GetValue() + + thread.StepOut() + + self.assertTrue(self.process.GetState() == lldb.eStateStopped) + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) + + # Assuming all these functions step out to main. Could figure out the caller dynamically + # if that would add something to the test. + frame = thread.GetFrameAtIndex(0) + fun_name = frame.GetFunctionName() + self.assertTrue(fun_name == "main") + + frame = thread.GetFrameAtIndex(0) + ret_value = thread.GetStopReturnValue() + + self.assertTrue(ret_value.IsValid()) + + num_ret_children = ret_value.GetNumChildren() + self.assertTrue(num_in_children == num_ret_children) + for idx in range(0, num_ret_children): + in_child = in_value.GetChildAtIndex(idx) + ret_child = ret_value.GetChildAtIndex(idx) + in_child_str = in_child.GetValue() + ret_child_str = ret_child.GetValue() + + self.assertEqual(in_child_str, ret_child_str) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/return-value/call-func.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/return-value/call-func.cpp new file mode 100644 index 00000000000..c538e8479a9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/return-value/call-func.cpp @@ -0,0 +1,607 @@ +// Some convenient things to return: +static char *g_first_pointer = "I am the first"; +static char *g_second_pointer = "I am the second"; + +// First we have some simple functions that return standard types, ints, floats and doubles. +// We have a function calling a function in a few cases to test that if you stop in the +// inner function then do "up/fin" you get the return value from the outer-most frame. + +int +inner_sint (int value) +{ + return value; +} + +int +outer_sint (int value) +{ + int outer_value = 2 * inner_sint (value); + return outer_value; +} + +float +inner_float (float value) +{ + return value; +} + +float +outer_float (float value) +{ + float outer_value = 2 * inner_float(value); + return outer_value; +} + +double +return_double (double value) +{ + return value; +} + +long double +return_long_double (long double value) +{ + return value; +} + +char * +return_pointer (char *value) +{ + return value; +} + +struct one_int +{ + int one_field; +}; + +struct one_int +return_one_int (struct one_int value) +{ + return value; +} + +struct two_int +{ + int first_field; + int second_field; +}; + +struct two_int +return_two_int (struct two_int value) +{ + return value; +} + +struct three_int +{ + int first_field; + int second_field; + int third_field; +}; + +struct three_int +return_three_int (struct three_int value) +{ + return value; +} + +struct four_int +{ + int first_field; + int second_field; + int third_field; + int fourth_field; +}; + +struct four_int +return_four_int (struct four_int value) +{ + return value; +} + +struct five_int +{ + int first_field; + int second_field; + int third_field; + int fourth_field; + int fifth_field; +}; + +struct five_int +return_five_int (struct five_int value) +{ + return value; +} + +struct one_int_one_double +{ + int first_field; + double second_field; +}; + +struct one_int_one_double +return_one_int_one_double (struct one_int_one_double value) +{ + return value; +} + +struct one_int_one_double_one_int +{ + int one_field; + double second_field; + int third_field; +}; + +struct one_int_one_double_one_int +return_one_int_one_double_one_int (struct one_int_one_double_one_int value) +{ + return value; +} + +struct one_short_one_double_one_short +{ + int one_field; + double second_field; + int third_field; +}; + +struct one_short_one_double_one_short +return_one_short_one_double_one_short (struct one_short_one_double_one_short value) +{ + return value; +} + +struct three_short_one_float +{ + short one_field; + short second_field; + short third_field; + float fourth_field; +}; + +struct three_short_one_float +return_three_short_one_float (struct three_short_one_float value) +{ + return value; +} + +struct one_int_one_float_one_int +{ + int one_field; + float second_field; + int third_field; +}; + +struct one_int_one_float_one_int +return_one_int_one_float_one_int (struct one_int_one_float_one_int value) +{ + return value; +} + +struct one_float_one_int_one_float +{ + float one_field; + int second_field; + float third_field; +}; + +struct one_float_one_int_one_float +return_one_float_one_int_one_float (struct one_float_one_int_one_float value) +{ + return value; +} + +struct one_double_two_float +{ + double one_field; + float second_field; + float third_field; +}; + +struct one_double_two_float +return_one_double_two_float (struct one_double_two_float value) +{ + return value; +} + +struct two_double +{ + double first_field; + double second_field; +}; + +struct two_double +return_two_double (struct two_double value) +{ + return value; +} + +struct two_float +{ + float first_field; + float second_field; +}; + +struct two_float +return_two_float (struct two_float value) +{ + return value; +} + +struct one_int_one_double_packed +{ + int first_field; + double second_field; +} __attribute__((__packed__)); + +struct one_int_one_double_packed +return_one_int_one_double_packed (struct one_int_one_double_packed value) +{ + return value; +} + +struct one_int_one_long +{ + int first_field; + long second_field; +}; + +struct one_int_one_long +return_one_int_one_long (struct one_int_one_long value) +{ + return value; +} + +struct one_pointer +{ + char *first_field; +}; + +struct one_pointer +return_one_pointer (struct one_pointer value) +{ + return value; +} + +struct two_pointer +{ + char *first_field; + char *second_field; +}; + +struct two_pointer +return_two_pointer (struct two_pointer value) +{ + return value; +} + +struct one_float_one_pointer +{ + float first_field; + char *second_field; +}; + +struct one_float_one_pointer +return_one_float_one_pointer (struct one_float_one_pointer value) +{ + return value; +} + +struct one_int_one_pointer +{ + int first_field; + char *second_field; +}; + +struct one_int_one_pointer +return_one_int_one_pointer (struct one_int_one_pointer value) +{ + return value; +} + +struct base_one_char { + char c; +}; + +struct nested_one_float_three_base { + float f; + struct base_one_char b1; + struct base_one_char b2; + struct base_one_char b3; +}; // returned in RAX for both SysV and Windows + +struct nested_one_float_three_base +return_nested_one_float_three_base (struct nested_one_float_three_base value) +{ + return value; +} + +struct double_nested_one_float_one_nested { + float f; + struct nested_one_float_three_base ns; +}; // SysV-ABI: returned in XMM0 + RAX +// Windows-ABI: returned in memory + +struct double_nested_one_float_one_nested +return_double_nested_one_float_one_nested(struct double_nested_one_float_one_nested value) +{ + return value; +} + +struct base_float_struct { + float f1; + float f2; +}; + +struct nested_float_struct { + double d; + struct base_float_struct bfs; +}; // SysV-ABI: return in xmm0 + xmm1 +// Windows-ABI: returned in memory + +struct nested_float_struct +return_nested_float_struct (struct nested_float_struct value) +{ + return value; +} + +struct six_double_three_int { + double d1; // 8 + double d2; // 8 + int i1; // 4 + double d3; // 8 + double d4; // 8 + int i2; // 4 + double d5; // 8 + double d6; // 8 + int i3; // 4 +}; // returned in memeory on both SysV and Windows + +struct six_double_three_int +return_six_double_three_int (struct six_double_three_int value) { + return value; +} + +typedef float vector_size_float32_8 __attribute__((__vector_size__(8))); +typedef float vector_size_float32_16 __attribute__((__vector_size__(16))); +typedef float vector_size_float32_32 __attribute__((__vector_size__(32))); + +typedef float ext_vector_size_float32_2 __attribute__((ext_vector_type(2))); +typedef float ext_vector_size_float32_4 __attribute__((ext_vector_type(4))); +typedef float ext_vector_size_float32_8 __attribute__((ext_vector_type(8))); + +vector_size_float32_8 +return_vector_size_float32_8 (vector_size_float32_8 value) +{ + return value; +} + +vector_size_float32_16 +return_vector_size_float32_16 (vector_size_float32_16 value) +{ + return value; +} + +vector_size_float32_32 +return_vector_size_float32_32 (vector_size_float32_32 value) +{ + return value; +} + +ext_vector_size_float32_2 +return_ext_vector_size_float32_2 (ext_vector_size_float32_2 value) +{ + return value; +} + +ext_vector_size_float32_4 +return_ext_vector_size_float32_4 (ext_vector_size_float32_4 value) +{ + return value; +} + +ext_vector_size_float32_8 +return_ext_vector_size_float32_8 (ext_vector_size_float32_8 value) +{ + return value; +} + +class base_class_one_char { +public: + char c = '!'; +}; // returned in RAX for both ABI + +base_class_one_char +return_base_class_one_char(base_class_one_char value) { + return value; +} + +class nested_class_float_and_base { +public: + float f = 0.1; + base_class_one_char b; +}; // returned in RAX for both ABI + +nested_class_float_and_base +return_nested_class_float_and_base(nested_class_float_and_base value) { + return value; +} + +class double_nested_class_float_and_nested { +public: + float f = 0.2; + nested_class_float_and_base n; +}; // SysV-ABI: returned in XMM0 + RAX +// Windows-ABI: returned in memory + +double_nested_class_float_and_nested +return_double_nested_class_float_and_nested( + double_nested_class_float_and_nested value) { + return value; +} + +class base_class { +public: + base_class() { + c = 'a'; + c2 = 'b'; + } +private: + char c; +protected: + char c2; +}; // returned in RAX for both ABI + +base_class +return_base_class(base_class value) { + return value; +} + +class sub_class : base_class { +public: + sub_class() { + c2 = '&'; + i = 10; + } +private: + int i; +}; // size 8; should be returned in RAX +// Since it's in register, lldb won't be able to get the +// fields in base class, expected to fail. + +sub_class +return_sub_class(sub_class value) { + return value; +} + +class abstract_class { +public: + virtual char getChar() = 0; +private: + int i = 8; +protected: + char c = '!'; +}; + +class derived_class : abstract_class { +public: + derived_class() { + c = '?'; + } + char getChar() { + return this->c; + } +private: + char c2 = '$'; +}; // size: 16; contains non POD member, returned in memory + +derived_class +return_derived_class(derived_class value) { + return value; +} + +int +main () +{ + int first_int = 123456; + int second_int = 234567; + + outer_sint (first_int); + outer_sint (second_int); + + float first_float_value = 12.34; + float second_float_value = 23.45; + + outer_float (first_float_value); + outer_float (second_float_value); + + double double_value = -23.45; + + return_double (double_value); + + return_pointer(g_first_pointer); + + long double long_double_value = -3456789.987654321; + + return_long_double (long_double_value); + + // Okay, now the structures: + return_one_int ((struct one_int) {10}); + return_two_int ((struct two_int) {10, 20}); + return_three_int ((struct three_int) {10, 20, 30}); + return_four_int ((struct four_int) {10, 20, 30, 40}); + return_five_int ((struct five_int) {10, 20, 30, 40, 50}); + + return_two_double ((struct two_double) {10.0, 20.0}); + return_one_double_two_float ((struct one_double_two_float) {10.0, 20.0, 30.0}); + return_one_int_one_float_one_int ((struct one_int_one_float_one_int) {10, 20.0, 30}); + + return_one_pointer ((struct one_pointer) {g_first_pointer}); + return_two_pointer ((struct two_pointer) {g_first_pointer, g_second_pointer}); + return_one_float_one_pointer ((struct one_float_one_pointer) {10.0, g_first_pointer}); + return_one_int_one_pointer ((struct one_int_one_pointer) {10, g_first_pointer}); + return_three_short_one_float ((struct three_short_one_float) {10, 20, 30, 40.0}); + + return_one_int_one_double ((struct one_int_one_double) {10, 20.0}); + return_one_int_one_double_one_int ((struct one_int_one_double_one_int) {10, 20.0, 30}); + return_one_short_one_double_one_short ((struct one_short_one_double_one_short) {10, 20.0, 30}); + return_one_float_one_int_one_float ((struct one_float_one_int_one_float) {10.0, 20, 30.0}); + return_two_float ((struct two_float) { 10.0, 20.0}); + return_one_int_one_double_packed ((struct one_int_one_double_packed) {10, 20.0}); + return_one_int_one_long ((struct one_int_one_long) {10, 20}); + + return_nested_one_float_three_base((struct nested_one_float_three_base) { + 10.0, + (struct base_one_char) { + 'x' + }, + (struct base_one_char) { + 'y' + }, + (struct base_one_char) { + 'z' + } + }); + return_double_nested_one_float_one_nested((struct double_nested_one_float_one_nested) { + 10.0, + (struct nested_one_float_three_base) { + 20.0, + (struct base_one_char) { + 'x' + }, + (struct base_one_char) { + 'y' + }, + (struct base_one_char) { + 'z' + } + }}); + return_nested_float_struct((struct nested_float_struct) { + 10.0, + (struct base_float_struct) { + 20.0, + 30.0 + }}); + return_six_double_three_int((struct six_double_three_int) { + 10.0, 20.0, 1, 30.0, 40.0, 2, 50.0, 60.0, 3}); + + return_base_class_one_char(base_class_one_char()); + return_nested_class_float_and_base(nested_class_float_and_base()); + return_double_nested_class_float_and_nested(double_nested_class_float_and_nested()); + return_base_class(base_class()); + // this is expected to fail + return_sub_class(sub_class()); + return_derived_class(derived_class()); + + return_vector_size_float32_8 (( vector_size_float32_8 ){1.5, 2.25}); + return_vector_size_float32_16 (( vector_size_float32_16 ){1.5, 2.25, 4.125, 8.0625}); + return_vector_size_float32_32 (( vector_size_float32_32 ){1.5, 2.25, 4.125, 8.0625, 7.89, 8.52, 6.31, 9.12}); + + return_ext_vector_size_float32_2 ((ext_vector_size_float32_2){ 16.5, 32.25}); + return_ext_vector_size_float32_4 ((ext_vector_size_float32_4){ 16.5, 32.25, 64.125, 128.0625}); + return_ext_vector_size_float32_8 ((ext_vector_size_float32_8){ 16.5, 32.25, 64.125, 128.0625, 1.59, 3.57, 8.63, 9.12 }); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/set-data/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/set-data/Makefile new file mode 100644 index 00000000000..37dd8f40a9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/set-data/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py new file mode 100644 index 00000000000..5b0a7bd07fe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py @@ -0,0 +1,68 @@ +""" +Set the contents of variables and registers using raw data +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SetDataTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_set_data(self): + """Test setting the contents of variables and registers using raw data.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.runCmd("br s -p First") + self.runCmd("br s -p Second") + + self.runCmd("run", RUN_SUCCEEDED) + + self.expect("p myFoo.x", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['2']) + + process = self.dbg.GetSelectedTarget().GetProcess() + frame = process.GetSelectedThread().GetFrameAtIndex(0) + + x = frame.FindVariable("myFoo").GetChildMemberWithName("x") + + my_data = lldb.SBData.CreateDataFromSInt32Array( + lldb.eByteOrderLittle, 8, [4]) + err = lldb.SBError() + + self.assertTrue(x.SetData(my_data, err)) + + self.runCmd("continue") + + self.expect("p myFoo.x", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['4']) + + frame = process.GetSelectedThread().GetFrameAtIndex(0) + + x = frame.FindVariable("string") + + if process.GetAddressByteSize() == 8: + my_data = lldb.SBData.CreateDataFromUInt64Array( + process.GetByteOrder(), 8, [0]) + else: + my_data = lldb.SBData.CreateDataFromUInt32Array( + process.GetByteOrder(), 4, [0]) + + err = lldb.SBError() + + self.assertTrue(x.SetData(my_data, err)) + + self.expect( + "fr var -d run-target string", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'NSString *', + 'nil']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/set-data/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/set-data/main.m new file mode 100644 index 00000000000..e1e69dc5571 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/set-data/main.m @@ -0,0 +1,19 @@ +#import <Foundation/Foundation.h> + +int main () +{ + @autoreleasepool + { + struct foo { + int x; + int y; + } myFoo; + + myFoo.x = 2; + myFoo.y = 3; // First breakpoint + + NSString *string = [NSString stringWithFormat:@"%s", "Hello world!"]; + + NSLog(@"%d %@", myFoo.x, string); // Second breakpoint + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/show_location/TestShowLocationDwarf5.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/show_location/TestShowLocationDwarf5.py new file mode 100644 index 00000000000..1d4bc6f1345 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/show_location/TestShowLocationDwarf5.py @@ -0,0 +1,36 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + +# This test checks that source code location is shown correctly +# when DWARF5 debug information is used. + +class TestTargetSourceMap(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(archs="aarch64", oslist="linux", + bugnumber="https://bugs.llvm.org/show_bug.cgi?id=44180") + def test_source_map(self): + # Set the target soure map to map "./" to the current test directory. + yaml_path = os.path.join(self.getSourceDir(), "a.yaml") + yaml_base, ext = os.path.splitext(yaml_path) + obj_path = self.getBuildArtifact(yaml_base) + self.yaml2obj(yaml_path, obj_path) + + def cleanup(): + if os.path.exists(obj_path): + os.unlink(obj_path) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Create a target with the object file we just created from YAML + target = self.dbg.CreateTarget(obj_path) + + # Check we are able to show the locations properly. + self.expect("b main", VALID_BREAKPOINT_LOCATION, + substrs=['main + 13 at test.cpp:2:3, address = 0x000000000040052d']) + + self.expect("b foo", VALID_BREAKPOINT_LOCATION, + substrs=['foo() + 4 at test.cpp:6:1, address = 0x0000000000400534']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/show_location/a.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/show_location/a.yaml new file mode 100644 index 00000000000..27b119d3df6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/show_location/a.yaml @@ -0,0 +1,58 @@ +# This file is a shorten version of the output +# produced with the following invocations and input: +# ./clang test.cpp -g -gdwarf-5 -o test.exe +# ./obj2yaml test.exe > test.yaml +# +# // test.cpp +# int main() { +# return 0; +# } +# +# void foo() { +# } + +--- !ELF +FileHeader: + Class: ELFCLASS64 + Data: ELFDATA2LSB + Type: ET_EXEC + Machine: EM_X86_64 + Entry: 0x0000000000400440 +Sections: + - Name: .text + Type: SHT_PROGBITS + Flags: [ SHF_ALLOC, SHF_EXECINSTR ] + Address: 0x0000000000400440 + AddressAlign: 0x0000000000000010 + Content: 31ED4989D15E4889E24883E4F0505449C7C0B005400048C7C14005400048C7C720054000E8B7FFFFFFF4660F1F44000055B820204000483D202040004889E57417B8000000004885C0740D5DBF20204000FFE00F1F4400005DC3660F1F440000BE20204000554881EE202040004889E548C1FE034889F048C1E83F4801C648D1FE7415B8000000004885C0740B5DBF20204000FFE00F1F005DC3660F1F440000803D391B0000007517554889E5E87EFFFFFFC605271B0000015DC30F1F440000F3C30F1F4000662E0F1F840000000000554889E55DEB89660F1F840000000000554889E531C0C745FC000000005DC390554889E55DC3662E0F1F840000000000415741564189FF415541544C8D25B618000055488D2DB6180000534989F64989D54C29E54883EC0848C1FD03E87FFEFFFF4885ED742031DB0F1F8400000000004C89EA4C89F64489FF41FF14DC4883C3014839EB75EA4883C4085B5D415C415D415E415FC390662E0F1F840000000000F3C3 + - Name: .debug_str_offsets + Type: SHT_PROGBITS + AddressAlign: 0x0000000000000001 + Content: 200000000500000000000000230000002C0000004A0000004F000000530000005B000000 + - Name: .debug_str + Type: SHT_PROGBITS + Flags: [ SHF_MERGE, SHF_STRINGS ] + AddressAlign: 0x0000000000000001 + Content: 636C616E672076657273696F6E20382E302E3020287472756E6B203334313935382900746573742E637070002F686F6D652F756D622F4C4C564D2F6275696C645F6C6C64622F62696E006D61696E00696E74005F5A33666F6F7600666F6F00 + - Name: .debug_abbrev + Type: SHT_PROGBITS + AddressAlign: 0x0000000000000001 + Content: 011101252513050325721710171B25110112060000022E0011011206401803253A0B3B0B49133F190000032E001101120640186E2503253A0B3B0B3F19000004240003253E0B0B0B000000 + - Name: .debug_info + Type: SHT_PROGBITS + AddressAlign: 0x0000000000000001 + Content: 50000000050001080000000001000400010800000000000000022005400000000000160000000220054000000000000F00000001560301014F000000033005400000000000060000000156050601050404050400 + - Name: .debug_macinfo + Type: SHT_PROGBITS + AddressAlign: 0x0000000000000001 + Content: '00' + - Name: .debug_line + Type: SHT_PROGBITS + AddressAlign: 0x0000000000000001 + Content: 70000000050008004C000000010101FB0E0D00010101010000000100000101011F010000000003011F020F051E021E00000000FD7C0F2E46BA561F7BDA351B04E677091E00000000FD7C0F2E46BA561F7BDA351B04E6770900090220054000000000000105030AC905003F05010A4B0202000101 + - Name: .debug_line_str + Type: SHT_PROGBITS + Flags: [ SHF_MERGE, SHF_STRINGS ] + AddressAlign: 0x0000000000000001 + Content: 2F686F6D652F756D622F4C4C564D2F6275696C645F6C6C64622F62696E00746573742E63707000 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py new file mode 100644 index 00000000000..ca268af63c4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py @@ -0,0 +1,112 @@ +"""Test that lldb command 'process signal SIGUSR1' to send a signal to the inferior works.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SendSignalTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.c', 'Put breakpoint here') + + @expectedFailureAll( + oslist=['freebsd'], + bugnumber="llvm.org/pr23318: does not report running state") + @expectedFailureNetBSD(bugnumber='llvm.org/pr43959') + @skipIfWindows # Windows does not support signals + def test_with_run_command(self): + """Test that lldb command 'process signal SIGUSR1' sends a signal to the inferior process.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByLocation('main.c', self.line) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Get the breakpoint location from breakpoint after we verified that, + # indeed, it has one location. + location = breakpoint.GetLocationAtIndex(0) + self.assertTrue(location and + location.IsEnabled(), + VALID_BREAKPOINT_LOCATION) + + # Now launch the process, no arguments & do not stop at entry point. + launch_info = lldb.SBLaunchInfo([exe]) + launch_info.SetWorkingDirectory(self.get_process_working_directory()) + + process_listener = lldb.SBListener("signal_test_listener") + launch_info.SetListener(process_listener) + error = lldb.SBError() + process = target.Launch(launch_info, error) + self.assertTrue(process, PROCESS_IS_VALID) + + self.runCmd("process handle -n False -p True -s True SIGUSR1") + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid(), "We hit the first breakpoint.") + + # After resuming the process, send it a SIGUSR1 signal. + + self.setAsync(True) + + self.assertTrue( + process_listener.IsValid(), + "Got a good process listener") + + # Disable our breakpoint, we don't want to hit it anymore... + breakpoint.SetEnabled(False) + + # Now continue: + process.Continue() + + # If running remote test, there should be a connected event + if lldb.remote_platform: + self.match_state(process_listener, lldb.eStateConnected) + + self.match_state(process_listener, lldb.eStateRunning) + + # Now signal the process, and make sure it stops: + process.Signal(lldbutil.get_signal_number('SIGUSR1')) + + self.match_state(process_listener, lldb.eStateStopped) + + # Now make sure the thread was stopped with a SIGUSR1: + threads = lldbutil.get_stopped_threads(process, lldb.eStopReasonSignal) + self.assertTrue(len(threads) == 1, "One thread stopped for a signal.") + thread = threads[0] + + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There was data in the event.") + self.assertTrue( + thread.GetStopReasonDataAtIndex(0) == lldbutil.get_signal_number('SIGUSR1'), + "The stop signal was SIGUSR1") + + def match_state(self, process_listener, expected_state): + num_seconds = 5 + broadcaster = self.process().GetBroadcaster() + event_type_mask = lldb.SBProcess.eBroadcastBitStateChanged + event = lldb.SBEvent() + got_event = process_listener.WaitForEventForBroadcasterWithType( + num_seconds, broadcaster, event_type_mask, event) + self.assertTrue(got_event, "Got an event") + state = lldb.SBProcess.GetStateFromEvent(event) + self.assertTrue(state == expected_state, + "It was the %s state." % + lldb.SBDebugger_StateAsCString(expected_state)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-abrt/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-abrt/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-abrt/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-abrt/TestHandleAbort.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-abrt/TestHandleAbort.py new file mode 100644 index 00000000000..5f3eb31c83a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-abrt/TestHandleAbort.py @@ -0,0 +1,70 @@ +"""Test that we can unwind out of a SIGABRT handler""" + + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class HandleAbortTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @skipIfWindows # signals do not exist on Windows + @expectedFailureNetBSD + def test_inferior_handle_sigabrt(self): + """Inferior calls abort() and handles the resultant SIGABRT. + Stopped at a breakpoint in the handler, verify that the backtrace + includes the function that called abort().""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # launch + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetState(), lldb.eStateStopped) + signo = process.GetUnixSignals().GetSignalNumberFromName("SIGABRT") + + thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal) + self.assertTrue( + thread and thread.IsValid(), + "Thread should be stopped due to a signal") + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There should be data in the event.") + self.assertEqual(thread.GetStopReasonDataAtIndex(0), + signo, "The stop signal should be SIGABRT") + + # Continue to breakpoint in abort handler + bkpt = target.FindBreakpointByID( + lldbutil.run_break_set_by_source_regexp(self, "Set a breakpoint here")) + threads = lldbutil.continue_to_breakpoint(process, bkpt) + self.assertEqual(len(threads), 1, "Expected single thread") + thread = threads[0] + + # Expect breakpoint in 'handler' + frame = thread.GetFrameAtIndex(0) + self.assertEqual(frame.GetDisplayFunctionName(), "handler", "Unexpected break?") + + # Expect that unwinding should find 'abort_caller' + foundFoo = False + for frame in thread: + if frame.GetDisplayFunctionName() == "abort_caller": + foundFoo = True + + self.assertTrue(foundFoo, "Unwinding did not find func that called abort") + + # Continue until we exit. + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), 0) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-abrt/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-abrt/main.c new file mode 100644 index 00000000000..c2daea1e84e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-abrt/main.c @@ -0,0 +1,25 @@ +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> + +void handler(int sig) +{ + printf("Set a breakpoint here.\n"); + exit(0); +} + +void abort_caller() { + abort(); +} + +int main() +{ + if (signal(SIGABRT, handler) == SIG_ERR) + { + perror("signal"); + return 1; + } + + abort_caller(); + return 2; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py new file mode 100644 index 00000000000..30ae201ed14 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py @@ -0,0 +1,47 @@ +"""Test that we can debug inferiors that handle SIGSEGV by themselves""" + + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class HandleSegvTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfWindows # signals do not exist on Windows + @skipIfDarwin + @expectedFailureNetBSD + def test_inferior_handle_sigsegv(self): + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # launch + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetState(), lldb.eStateStopped) + signo = process.GetUnixSignals().GetSignalNumberFromName("SIGSEGV") + + thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal) + self.assertTrue( + thread and thread.IsValid(), + "Thread should be stopped due to a signal") + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There was data in the event.") + self.assertEqual(thread.GetStopReasonDataAtIndex(0), + signo, "The stop signal was SIGSEGV") + + # Continue until we exit. + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), 0) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/main.c new file mode 100644 index 00000000000..27d9b8e500a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/main.c @@ -0,0 +1,58 @@ +#include <sys/mman.h> +#include <signal.h> +#include <stdio.h> +#include <unistd.h> + +enum { + kMmapSize = 0x1000, + kMagicValue = 47, +}; + +void *address; +volatile sig_atomic_t signaled = 0; + +void handler(int sig) +{ + signaled = 1; + if (munmap(address, kMmapSize) != 0) + { + perror("munmap"); + _exit(5); + } + + void* newaddr = mmap(address, kMmapSize, PROT_READ | PROT_WRITE, + MAP_ANON | MAP_FIXED | MAP_PRIVATE, -1, 0); + if (newaddr != address) + { + fprintf(stderr, "Newly mmaped address (%p) does not equal old address (%p).\n", + newaddr, address); + _exit(6); + } + *(int*)newaddr = kMagicValue; +} + +int main() +{ + if (signal(SIGSEGV, handler) == SIG_ERR) + { + perror("signal"); + return 1; + } + + address = mmap(NULL, kMmapSize, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0); + if (address == MAP_FAILED) + { + perror("mmap"); + return 2; + } + + // This should first trigger a segfault. Our handler will make the memory readable and write + // the magic value into memory. + if (*(int*)address != kMagicValue) + return 3; + + if (! signaled) + return 4; + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/main.c new file mode 100644 index 00000000000..77e76050341 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/main.c @@ -0,0 +1,27 @@ +#include <signal.h> +#include <stdio.h> +#include <unistd.h> + +void handler_usr1 (int i) +{ + puts ("got signal usr1"); +} + +void handler_alrm (int i) +{ + puts ("got signal ALRM"); +} + +int main () +{ + int i = 0; + + signal (SIGUSR1, handler_usr1); + signal (SIGALRM, handler_alrm); + + puts ("Put breakpoint here"); + + while (i++ < 20) + sleep (1); +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py new file mode 100644 index 00000000000..70271e43cff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py @@ -0,0 +1,190 @@ +"""Test that we handle inferiors that send signals to themselves""" + + + +import lldb +import re +from lldbsuite.test.lldbplatformutil import getDarwinOSTriples +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipIfWindows # signals do not exist on Windows +class RaiseTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipIfNetBSD # Hangs on NetBSD + def test_sigstop(self): + self.build() + self.signal_test('SIGSTOP', False) + # passing of SIGSTOP is not correctly handled, so not testing that + # scenario: https://llvm.org/bugs/show_bug.cgi?id=23574 + + @skipIfDarwin # darwin does not support real time signals + @skipIfTargetAndroid() + def test_sigsigrtmin(self): + self.build() + self.signal_test('SIGRTMIN', True) + + @skipIfNetBSD # Hangs on NetBSD + def test_sigtrap(self): + self.build() + self.signal_test('SIGTRAP', True) + + def launch(self, target, signal): + # launch the process, do not stop at entry point. + process = target.LaunchSimple( + [signal], None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + self.assertEqual(process.GetState(), lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "Thread should be stopped due to a breakpoint") + return process + + def set_handle(self, signal, pass_signal, stop_at_signal, notify_signal): + return_obj = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle %s -p %s -s %s -n %s" % + (signal, pass_signal, stop_at_signal, notify_signal), return_obj) + self.assertTrue( + return_obj.Succeeded(), + "Setting signal handling failed") + + def signal_test(self, signal, test_passing): + """Test that we handle inferior raising signals""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + lldbutil.run_break_set_by_symbol(self, "main") + + # launch + process = self.launch(target, signal) + signo = process.GetUnixSignals().GetSignalNumberFromName(signal) + + # retrieve default signal disposition + return_obj = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand( + "process handle %s " % signal, return_obj) + match = re.match( + 'NAME *PASS *STOP *NOTIFY.*(false|true) *(false|true) *(false|true)', + return_obj.GetOutput(), + re.IGNORECASE | re.DOTALL) + if not match: + self.fail('Unable to retrieve default signal disposition.') + default_pass = match.group(1) + default_stop = match.group(2) + default_notify = match.group(3) + + # Make sure we stop at the signal + self.set_handle(signal, "false", "true", "true") + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateStopped) + thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal) + self.assertTrue( + thread.IsValid(), + "Thread should be stopped due to a signal") + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There was data in the event.") + self.assertEqual(thread.GetStopReasonDataAtIndex(0), signo, + "The stop signal was %s" % signal) + + # Continue until we exit. + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), 0) + + # launch again + process = self.launch(target, signal) + + # Make sure we do not stop at the signal. We should still get the + # notification. + self.set_handle(signal, "false", "false", "true") + self.expect( + "process continue", + substrs=[ + "stopped and restarted", + signal]) + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), 0) + + # launch again + process = self.launch(target, signal) + + # Make sure we do not stop at the signal, and we do not get the + # notification. + self.set_handle(signal, "false", "false", "false") + self.expect( + "process continue", + substrs=["stopped and restarted"], + matching=False) + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), 0) + + if not test_passing: + # reset signal handling to default + self.set_handle(signal, default_pass, default_stop, default_notify) + return + + # launch again + process = self.launch(target, signal) + + # Make sure we stop at the signal + self.set_handle(signal, "true", "true", "true") + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateStopped) + thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal) + self.assertTrue( + thread.IsValid(), + "Thread should be stopped due to a signal") + self.assertTrue( + thread.GetStopReasonDataCount() >= 1, + "There was data in the event.") + self.assertEqual( + thread.GetStopReasonDataAtIndex(0), + process.GetUnixSignals().GetSignalNumberFromName(signal), + "The stop signal was %s" % + signal) + + # Continue until we exit. The process should receive the signal. + process.Continue() + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), signo) + + # launch again + process = self.launch(target, signal) + + # Make sure we do not stop at the signal. We should still get the notification. Process + # should receive the signal. + self.set_handle(signal, "true", "false", "true") + self.expect( + "process continue", + substrs=[ + "stopped and restarted", + signal]) + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), signo) + + # launch again + process = self.launch(target, signal) + + # Make sure we do not stop at the signal, and we do not get the notification. Process + # should receive the signal. + self.set_handle(signal, "true", "false", "false") + self.expect( + "process continue", + substrs=["stopped and restarted"], + matching=False) + self.assertEqual(process.GetState(), lldb.eStateExited) + self.assertEqual(process.GetExitStatus(), signo) + + # reset signal handling to default + self.set_handle(signal, default_pass, default_stop, default_notify) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/main.c new file mode 100644 index 00000000000..4203fe5d4c8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/signal/raise/main.c @@ -0,0 +1,49 @@ +#include <signal.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +void handler(int signo) +{ + _exit(signo); +} + +int main (int argc, char *argv[]) +{ + if (signal(SIGTRAP, handler) == SIG_ERR) + { + perror("signal(SIGTRAP)"); + return 1; + } +#ifndef __APPLE__ + // Real time signals not supported on apple platforms. + if (signal(SIGRTMIN, handler) == SIG_ERR) + { + perror("signal(SIGRTMIN)"); + return 1; + } +#endif + + if (argc < 2) + { + puts("Please specify a signal to raise"); + return 1; + } + + if (strcmp(argv[1], "SIGSTOP") == 0) + raise(SIGSTOP); + else if (strcmp(argv[1], "SIGTRAP") == 0) + raise(SIGTRAP); +#ifndef __APPLE__ + else if (strcmp(argv[1], "SIGRTMIN") == 0) + raise(SIGRTMIN); +#endif + else + { + printf("Unknown signal: %s\n", argv[1]); + return 1; + } + + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/source-map/TestTargetSourceMap.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/source-map/TestTargetSourceMap.py new file mode 100644 index 00000000000..80c4877ad32 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/source-map/TestTargetSourceMap.py @@ -0,0 +1,43 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * + + +class TestTargetSourceMap(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_source_map(self): + """Test target.source-map' functionality.""" + # Set the target soure map to map "./" to the current test directory + src_dir = self.getSourceDir() + src_path = os.path.join(src_dir, "main.c") + yaml_path = os.path.join(src_dir, "a.yaml") + yaml_base, ext = os.path.splitext(yaml_path) + obj_path = self.getBuildArtifact("main.o") + self.yaml2obj(yaml_path, obj_path) + + # Create a target with the object file we just created from YAML + target = self.dbg.CreateTarget(obj_path) + + # Set a breakpoint before we remap source and verify that it fails + bp = target.BreakpointCreateByLocation(src_path, 2) + self.assertTrue(bp.GetNumLocations() == 0, + "make sure no breakpoints were resolved without map") + src_map_cmd = 'settings set target.source-map . "%s"' % (src_dir) + self.dbg.HandleCommand(src_map_cmd) + + # Set a breakpoint after we remap source and verify that it succeeds + bp = target.BreakpointCreateByLocation(src_path, 2) + self.assertTrue(bp.GetNumLocations() == 1, + "make sure breakpoint was resolved with map") + + # Now make sure that we can actually FIND the source file using this + # remapping: + retval = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand("source list -f main.c -l 2", retval) + self.assertTrue(retval.Succeeded(), "source list didn't succeed.") + self.assertTrue(retval.GetOutput() != None, "We got no ouput from source list") + self.assertTrue("return" in retval.GetOutput(), "We didn't find the source file...") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/source-map/Trivial/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/source-map/Trivial/main.c new file mode 100644 index 00000000000..921907253c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/source-map/Trivial/main.c @@ -0,0 +1,7 @@ +int main() +{ + return 0; +} +int main () { + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/source-map/a.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/source-map/a.yaml new file mode 100644 index 00000000000..d14e9a3b832 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/source-map/a.yaml @@ -0,0 +1,410 @@ +--- !mach-o +FileHeader: + magic: 0xFEEDFACF + cputype: 0x01000007 + cpusubtype: 0x00000003 + filetype: 0x00000001 + ncmds: 4 + sizeofcmds: 1160 + flags: 0x00002000 + reserved: 0x00000000 +LoadCommands: + - cmd: LC_SEGMENT_64 + cmdsize: 1032 + segname: '' + vmaddr: 0 + vmsize: 744 + fileoff: 1192 + filesize: 744 + maxprot: 7 + initprot: 7 + nsects: 12 + flags: 0 + Sections: + - sectname: __text + segname: __TEXT + addr: 0x0000000000000000 + size: 22 + offset: 0x000004A8 + align: 4 + reloff: 0x00000000 + nreloc: 0 + flags: 0x80000400 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __debug_str + segname: __DWARF + addr: 0x0000000000000016 + size: 108 + offset: 0x000004BE + align: 0 + reloff: 0x00000000 + nreloc: 0 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __debug_abbrev + segname: __DWARF + addr: 0x0000000000000082 + size: 83 + offset: 0x0000052A + align: 0 + reloff: 0x00000000 + nreloc: 0 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __debug_info + segname: __DWARF + addr: 0x00000000000000D5 + size: 126 + offset: 0x0000057D + align: 0 + reloff: 0x00000790 + nreloc: 2 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __debug_macinfo + segname: __DWARF + addr: 0x0000000000000153 + size: 1 + offset: 0x000005FB + align: 0 + reloff: 0x00000000 + nreloc: 0 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __apple_names + segname: __DWARF + addr: 0x0000000000000154 + size: 60 + offset: 0x000005FC + align: 0 + reloff: 0x00000000 + nreloc: 0 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __apple_objc + segname: __DWARF + addr: 0x0000000000000190 + size: 36 + offset: 0x00000638 + align: 0 + reloff: 0x00000000 + nreloc: 0 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __apple_namespac + segname: __DWARF + addr: 0x00000000000001B4 + size: 36 + offset: 0x0000065C + align: 0 + reloff: 0x00000000 + nreloc: 0 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __apple_types + segname: __DWARF + addr: 0x00000000000001D8 + size: 102 + offset: 0x00000680 + align: 0 + reloff: 0x00000000 + nreloc: 0 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __compact_unwind + segname: __LD + addr: 0x0000000000000240 + size: 32 + offset: 0x000006E8 + align: 3 + reloff: 0x000007A0 + nreloc: 1 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __eh_frame + segname: __TEXT + addr: 0x0000000000000260 + size: 64 + offset: 0x00000708 + align: 3 + reloff: 0x00000000 + nreloc: 0 + flags: 0x6800000B + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __debug_line + segname: __DWARF + addr: 0x00000000000002A0 + size: 72 + offset: 0x00000748 + align: 0 + reloff: 0x000007A8 + nreloc: 1 + flags: 0x02000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - cmd: LC_BUILD_VERSION + cmdsize: 24 + platform: 1 + minos: 658944 + sdk: 658944 + ntools: 0 + - cmd: LC_SYMTAB + cmdsize: 24 + symoff: 1968 + nsyms: 1 + stroff: 1984 + strsize: 8 + - cmd: LC_DYSYMTAB + cmdsize: 80 + ilocalsym: 0 + nlocalsym: 0 + iextdefsym: 0 + nextdefsym: 1 + iundefsym: 1 + nundefsym: 0 + tocoff: 0 + ntoc: 0 + modtaboff: 0 + nmodtab: 0 + extrefsymoff: 0 + nextrefsyms: 0 + indirectsymoff: 0 + nindirectsyms: 0 + extreloff: 0 + nextrel: 0 + locreloff: 0 + nlocrel: 0 +LinkEditData: + NameList: + - n_strx: 1 + n_type: 0x0F + n_sect: 1 + n_desc: 0 + n_value: 0 + StringTable: + - '' + - _main + - '' +DWARF: + debug_str: + - 'Apple LLVM version 10.0.1 (clang-1001.0.37.3)' + - './Trivial/main.c' + - '.' + - main + - int + - argc + - argv + - char + debug_abbrev: + - Code: 0x00000001 + Tag: DW_TAG_compile_unit + Children: DW_CHILDREN_yes + Attributes: + - Attribute: DW_AT_producer + Form: DW_FORM_strp + - Attribute: DW_AT_language + Form: DW_FORM_data2 + - Attribute: DW_AT_name + Form: DW_FORM_strp + - Attribute: DW_AT_stmt_list + Form: DW_FORM_sec_offset + - Attribute: DW_AT_comp_dir + Form: DW_FORM_strp + - Attribute: DW_AT_low_pc + Form: DW_FORM_addr + - Attribute: DW_AT_high_pc + Form: DW_FORM_data4 + - Code: 0x00000002 + Tag: DW_TAG_subprogram + Children: DW_CHILDREN_yes + Attributes: + - Attribute: DW_AT_low_pc + Form: DW_FORM_addr + - Attribute: DW_AT_high_pc + Form: DW_FORM_data4 + - Attribute: DW_AT_frame_base + Form: DW_FORM_exprloc + - Attribute: DW_AT_name + Form: DW_FORM_strp + - Attribute: DW_AT_decl_file + Form: DW_FORM_data1 + - Attribute: DW_AT_decl_line + Form: DW_FORM_data1 + - Attribute: DW_AT_prototyped + Form: DW_FORM_flag_present + - Attribute: DW_AT_type + Form: DW_FORM_ref4 + - Attribute: DW_AT_external + Form: DW_FORM_flag_present + - Code: 0x00000003 + Tag: DW_TAG_formal_parameter + Children: DW_CHILDREN_no + Attributes: + - Attribute: DW_AT_location + Form: DW_FORM_exprloc + - Attribute: DW_AT_name + Form: DW_FORM_strp + - Attribute: DW_AT_decl_file + Form: DW_FORM_data1 + - Attribute: DW_AT_decl_line + Form: DW_FORM_data1 + - Attribute: DW_AT_type + Form: DW_FORM_ref4 + - Code: 0x00000004 + Tag: DW_TAG_base_type + Children: DW_CHILDREN_no + Attributes: + - Attribute: DW_AT_name + Form: DW_FORM_strp + - Attribute: DW_AT_encoding + Form: DW_FORM_data1 + - Attribute: DW_AT_byte_size + Form: DW_FORM_data1 + - Code: 0x00000005 + Tag: DW_TAG_pointer_type + Children: DW_CHILDREN_no + Attributes: + - Attribute: DW_AT_type + Form: DW_FORM_ref4 + - Code: 0x00000006 + Tag: DW_TAG_const_type + Children: DW_CHILDREN_no + Attributes: + - Attribute: DW_AT_type + Form: DW_FORM_ref4 + debug_info: + - Length: + TotalLength: 122 + Version: 4 + AbbrOffset: 0 + AddrSize: 8 + Entries: + - AbbrCode: 0x00000001 + Values: + - Value: 0x0000000000000000 + - Value: 0x000000000000000C + - Value: 0x000000000000002E + - Value: 0x0000000000000000 + - Value: 0x000000000000003F + - Value: 0x0000000000000000 + - Value: 0x0000000000000016 + - AbbrCode: 0x00000002 + Values: + - Value: 0x0000000000000000 + - Value: 0x0000000000000016 + - Value: 0x0000000000000001 + BlockData: + - 0x56 + - Value: 0x0000000000000054 + - Value: 0x0000000000000001 + - Value: 0x0000000000000001 + - Value: 0x0000000000000001 + - Value: 0x0000000000000060 + - Value: 0x0000000000000001 + - AbbrCode: 0x00000003 + Values: + - Value: 0x0000000000000002 + BlockData: + - 0x91 + - 0x78 + - Value: 0x000000000000005D + - Value: 0x0000000000000001 + - Value: 0x0000000000000001 + - Value: 0x0000000000000060 + - AbbrCode: 0x00000003 + Values: + - Value: 0x0000000000000002 + BlockData: + - 0x91 + - 0x70 + - Value: 0x0000000000000062 + - Value: 0x0000000000000001 + - Value: 0x0000000000000001 + - Value: 0x0000000000000067 + - AbbrCode: 0x00000000 + Values: [] + - AbbrCode: 0x00000004 + Values: + - Value: 0x0000000000000059 + - Value: 0x0000000000000005 + - Value: 0x0000000000000004 + - AbbrCode: 0x00000005 + Values: + - Value: 0x000000000000006C + - AbbrCode: 0x00000005 + Values: + - Value: 0x0000000000000071 + - AbbrCode: 0x00000006 + Values: + - Value: 0x0000000000000076 + - AbbrCode: 0x00000004 + Values: + - Value: 0x0000000000000067 + - Value: 0x0000000000000006 + - Value: 0x0000000000000001 + - AbbrCode: 0x00000000 + Values: [] + debug_line: + - Length: + TotalLength: 68 + Version: 4 + PrologueLength: 40 + MinInstLength: 1 + MaxOpsPerInst: 1 + DefaultIsStmt: 1 + LineBase: 251 + LineRange: 14 + OpcodeBase: 13 + StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ] + IncludeDirs: + - './Trivial' + Files: + - Name: main.c + DirIdx: 1 + ModTime: 0 + Length: 0 + Opcodes: + - Opcode: DW_LNS_extended_op + ExtLen: 9 + SubOpcode: DW_LNE_set_address + Data: 0 + - Opcode: DW_LNS_copy + Data: 0 + - Opcode: DW_LNS_set_column + Data: 3 + - Opcode: DW_LNS_set_prologue_end + Data: 3 + - Opcode: DW_LNS_const_add_pc + Data: 3 + - Opcode: 0x3D + Data: 3 + - Opcode: DW_LNS_advance_pc + Data: 2 + - Opcode: DW_LNS_extended_op + ExtLen: 1 + SubOpcode: DW_LNE_end_sequence + Data: 2 +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/stats_api/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/stats_api/Makefile new file mode 100644 index 00000000000..c9319d6e688 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/stats_api/Makefile @@ -0,0 +1,2 @@ +C_SOURCES := main.c +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/stats_api/TestStatisticsAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/stats_api/TestStatisticsAPI.py new file mode 100644 index 00000000000..d4903b5269a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/stats_api/TestStatisticsAPI.py @@ -0,0 +1,34 @@ +# Test the SBAPI for GetStatistics() + +import json +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestStatsAPI(TestBase): + mydir = TestBase.compute_mydir(__file__) + + def test_stats_api(self): + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + + # Test enabling/disabling stats + self.assertFalse(target.GetCollectingStats()) + target.SetCollectingStats(True) + self.assertTrue(target.GetCollectingStats()) + target.SetCollectingStats(False) + self.assertFalse(target.GetCollectingStats()) + + # Test the function to get the statistics in JSON'ish. + stats = target.GetStatistics() + stream = lldb.SBStream() + res = stats.GetAsJSON(stream) + stats_json = sorted(json.loads(stream.GetData())) + self.assertEqual(len(stats_json), 4) + self.assertTrue("Number of expr evaluation failures" in stats_json) + self.assertTrue("Number of expr evaluation successes" in stats_json) + self.assertTrue("Number of frame var failures" in stats_json) + self.assertTrue("Number of frame var successes" in stats_json) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/stats_api/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/stats_api/main.c new file mode 100644 index 00000000000..03b2213bb9a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/stats_api/main.c @@ -0,0 +1,3 @@ +int main(void) { + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/Makefile new file mode 100644 index 00000000000..374e58b89a8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/Makefile @@ -0,0 +1,6 @@ +C_SOURCES := with-debug.c without-debug.c + +include Makefile.rules + +without-debug.o: without-debug.c + $(CC) $(CFLAGS_NO_DEBUG) -c $< diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py new file mode 100644 index 00000000000..629efb5d99b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py @@ -0,0 +1,152 @@ +""" +Test thread step-in, step-over and step-out work with the "Avoid no debug" option. +""" + + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StepAvoidsNoDebugTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + def test_step_out_with_python(self): + """Test stepping out using avoid-no-debug with dsyms.""" + self.build() + self.get_to_starting_point() + self.do_step_out_past_nodebug() + + @add_test_categories(['pyapi']) + @decorators.expectedFailureAll( + compiler="gcc", bugnumber="llvm.org/pr28549") + @decorators.expectedFailureAll( + compiler="clang", + compiler_version=[ + ">=", + "3.9"], + archs=["i386"], + bugnumber="llvm.org/pr28549") + def test_step_over_with_python(self): + """Test stepping over using avoid-no-debug with dwarf.""" + self.build() + self.get_to_starting_point() + self.do_step_over_past_nodebug() + + @add_test_categories(['pyapi']) + @decorators.expectedFailureAll( + compiler="gcc", bugnumber="llvm.org/pr28549") + @decorators.expectedFailureAll( + compiler="clang", + compiler_version=[ + ">=", + "3.9"], + archs=["i386"], + bugnumber="llvm.org/pr28549") + @expectedFailureAll(oslist=["ios", "tvos", "bridgeos"], bugnumber="<rdar://problem/34026777>") # lldb doesn't step past last source line in function on arm64 + @expectedFailureAll(archs=["aarch64"], oslist=["linux"], + bugnumber="llvm.org/pr44057") + def test_step_in_with_python(self): + """Test stepping in using avoid-no-debug with dwarf.""" + self.build() + self.get_to_starting_point() + self.do_step_in_past_nodebug() + + def setUp(self): + TestBase.setUp(self) + self.main_source = "with-debug.c" + self.main_source_spec = lldb.SBFileSpec("with-debug.c") + self.dbg.HandleCommand( + "settings set target.process.thread.step-out-avoid-nodebug true") + + def tearDown(self): + self.dbg.HandleCommand( + "settings set target.process.thread.step-out-avoid-nodebug false") + TestBase.tearDown(self) + + def hit_correct_line(self, pattern): + target_line = line_number(self.main_source, pattern) + self.assertTrue( + target_line != 0, + "Could not find source pattern " + + pattern) + cur_line = self.thread.frames[0].GetLineEntry().GetLine() + self.assertTrue( + cur_line == target_line, + "Stepped to line %d instead of expected %d with pattern '%s'." % + (cur_line, + target_line, + pattern)) + + def hit_correct_function(self, pattern): + name = self.thread.frames[0].GetFunctionName() + self.assertTrue( + pattern in name, "Got to '%s' not the expected function '%s'." % + (name, pattern)) + + def get_to_starting_point(self): + exe = self.getBuildArtifact("a.out") + error = lldb.SBError() + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + inner_bkpt = self.target.BreakpointCreateBySourceRegex( + "Stop here and step out of me", self.main_source_spec) + self.assertTrue(inner_bkpt, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(self.process, PROCESS_IS_VALID) + + # Now finish, and make sure the return value is correct. + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, inner_bkpt) + self.assertTrue(len(threads) == 1, "Stopped at inner breakpoint.") + self.thread = threads[0] + + def do_step_out_past_nodebug(self): + # The first step out takes us to the called_from_nodebug frame, just to make sure setting + # step-out-avoid-nodebug doesn't change the behavior in frames with + # debug info. + self.thread.StepOut() + self.hit_correct_line( + "intermediate_return_value = called_from_nodebug_actual(some_value)") + self.thread.StepOut() + self.hit_correct_line( + "int return_value = no_debug_caller(5, called_from_nodebug)") + + def do_step_over_past_nodebug(self): + self.thread.StepOver() + self.hit_correct_line( + "intermediate_return_value = called_from_nodebug_actual(some_value)") + self.thread.StepOver() + self.hit_correct_line("return intermediate_return_value") + self.thread.StepOver() + # Note, lldb doesn't follow gdb's distinction between "step-out" and "step-over/step-in" + # when exiting a frame. In all cases we leave the pc at the point where we exited the + # frame. In gdb, step-over/step-in move to the end of the line they stepped out to. + # If we ever change this we will need to fix this test. + self.hit_correct_line( + "int return_value = no_debug_caller(5, called_from_nodebug)") + + def do_step_in_past_nodebug(self): + self.thread.StepInto() + self.hit_correct_line( + "intermediate_return_value = called_from_nodebug_actual(some_value)") + self.thread.StepInto() + self.hit_correct_line("return intermediate_return_value") + self.thread.StepInto() + # Note, lldb doesn't follow gdb's distinction between "step-out" and "step-over/step-in" + # when exiting a frame. In all cases we leave the pc at the point where we exited the + # frame. In gdb, step-over/step-in move to the end of the line they stepped out to. + # If we ever change this we will need to fix this test. + self.hit_correct_line( + "int return_value = no_debug_caller(5, called_from_nodebug)") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/with-debug.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/with-debug.c new file mode 100644 index 00000000000..c7ac309d2c1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/with-debug.c @@ -0,0 +1,29 @@ +#include <stdio.h> + +typedef int (*debug_callee) (int); + +extern int no_debug_caller (int, debug_callee); + +int +called_from_nodebug_actual(int some_value) +{ + int return_value = 0; + return_value = printf ("Length: %d.\n", some_value); + return return_value; // Stop here and step out of me +} + +int +called_from_nodebug(int some_value) +{ + int intermediate_return_value = 0; + intermediate_return_value = called_from_nodebug_actual(some_value); + return intermediate_return_value; +} + +int +main() +{ + int return_value = no_debug_caller(5, called_from_nodebug); + printf ("I got: %d.\n", return_value); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/without-debug.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/without-debug.c new file mode 100644 index 00000000000..d71d74af5e9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/without-debug.c @@ -0,0 +1,17 @@ +typedef int (*debug_callee) (int); + +int +no_debug_caller_intermediate(int input, debug_callee callee) +{ + int return_value = 0; + return_value = callee(input); + return return_value; +} + +int +no_debug_caller (int input, debug_callee callee) +{ + int return_value = 0; + return_value = no_debug_caller_intermediate (input, callee); + return return_value; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/Steps.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/Steps.py new file mode 100644 index 00000000000..4133cbbe608 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/Steps.py @@ -0,0 +1,83 @@ +import lldb + +class StepWithChild: + def __init__(self, thread_plan): + self.thread_plan = thread_plan + self.child_thread_plan = self.queue_child_thread_plan() + + def explains_stop(self, event): + return False + + def should_stop(self, event): + if not self.child_thread_plan.IsPlanComplete(): + return False + + self.thread_plan.SetPlanComplete(True) + + return True + + def should_step(self): + return False + + def queue_child_thread_plan(self): + return None + +class StepOut(StepWithChild): + def __init__(self, thread_plan, dict): + StepWithChild.__init__(self, thread_plan) + + def queue_child_thread_plan(self): + return self.thread_plan.QueueThreadPlanForStepOut(0) + +class StepScripted(StepWithChild): + def __init__(self, thread_plan, dict): + StepWithChild.__init__(self, thread_plan) + + def queue_child_thread_plan(self): + return self.thread_plan.QueueThreadPlanForStepScripted("Steps.StepOut") + +# This plan does a step-over until a variable changes value. +class StepUntil(StepWithChild): + def __init__(self, thread_plan, args_data, dict): + self.frame = thread_plan.GetThread().frames[0] + self.target = thread_plan.GetThread().GetProcess().GetTarget() + func_entry = args_data.GetValueForKey("variable_name") + + if not func_entry.IsValid(): + print("Did not get a valid entry for variable_name") + func_name = func_entry.GetStringValue(100) + + self.value = self.frame.FindVariable(func_name) + if self.value.GetError().Fail(): + print("Failed to get foo value: %s"%(self.value.GetError().GetCString())) + else: + print("'foo' value: %d"%(self.value.GetValueAsUnsigned())) + + StepWithChild.__init__(self, thread_plan) + + + def queue_child_thread_plan(self): + le = self.frame.GetLineEntry() + start_addr = le.GetStartAddress() + start = start_addr.GetLoadAddress(self.target) + end = le.GetEndAddress().GetLoadAddress(self.target) + return self.thread_plan.QueueThreadPlanForStepOverRange(start_addr, + end - start) + + def should_stop(self, event): + if not self.child_thread_plan.IsPlanComplete(): + return False + + # If we've stepped out of this frame, stop. + if not self.frame.IsValid(): + return True + + if not self.value.IsValid(): + return True + + print("Got next value: %d"%(self.value.GetValueAsUnsigned())) + if not self.value.GetValueDidChange(): + self.child_thread_plan = self.queue_child_thread_plan() + return False + else: + return True diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/TestStepScripted.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/TestStepScripted.py new file mode 100644 index 00000000000..eb1b5822580 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/TestStepScripted.py @@ -0,0 +1,108 @@ +""" +Tests stepping with scripted thread plans. +""" + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + +class StepScriptedTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + TestBase.setUp(self) + self.main_source_file = lldb.SBFileSpec("main.c") + self.runCmd("command script import Steps.py") + + def test_standard_step_out(self): + """Tests stepping with the scripted thread plan laying over a standard + thread plan for stepping out.""" + self.build() + self.step_out_with_scripted_plan("Steps.StepOut") + + def test_scripted_step_out(self): + """Tests stepping with the scripted thread plan laying over an another + scripted thread plan for stepping out.""" + self.build() + self.step_out_with_scripted_plan("Steps.StepScripted") + + def step_out_with_scripted_plan(self, name): + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", + self.main_source_file) + + frame = thread.GetFrameAtIndex(0) + self.assertEqual("foo", frame.GetFunctionName()) + + err = thread.StepUsingScriptedThreadPlan(name) + self.assertTrue(err.Success(), err.GetCString()) + + frame = thread.GetFrameAtIndex(0) + self.assertEqual("main", frame.GetFunctionName()) + + + def test_misspelled_plan_name(self): + """Test that we get a useful error if we misspell the plan class name""" + self.build() + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", + self.main_source_file) + stop_id = process.GetStopID() + # Pass a non-existent class for the plan class: + err = thread.StepUsingScriptedThreadPlan("NoSuchModule.NoSuchPlan") + + # Make sure we got a good error: + self.assertTrue(err.Fail(), "We got a failure state") + msg = err.GetCString() + self.assertTrue("NoSuchModule.NoSuchPlan" in msg, "Mentioned missing class") + + # Make sure we didn't let the process run: + self.assertEqual(stop_id, process.GetStopID(), "Process didn't run") + + def test_checking_variable(self): + """Test that we can call SBValue API's from a scripted thread plan - using SBAPI's to step""" + self.do_test_checking_variable(False) + + def test_checking_variable_cli(self): + """Test that we can call SBValue API's from a scripted thread plan - using cli to step""" + self.do_test_checking_variable(True) + + def do_test_checking_variable(self, use_cli): + self.build() + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", + self.main_source_file) + + frame = thread.GetFrameAtIndex(0) + self.assertEqual("foo", frame.GetFunctionName()) + foo_val = frame.FindVariable("foo") + self.assertTrue(foo_val.GetError().Success(), "Got the foo variable") + self.assertEqual(foo_val.GetValueAsUnsigned(), 10, "foo starts at 10") + + if use_cli: + result = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand( + "thread step-scripted -C Steps.StepUntil -k variable_name -v foo", + result) + self.assertTrue(result.Succeeded()) + else: + args_data = lldb.SBStructuredData() + data = lldb.SBStream() + data.Print('{"variable_name" : "foo"}') + error = args_data.SetFromJSON(data) + self.assertTrue(error.Success(), "Made the args_data correctly") + + err = thread.StepUsingScriptedThreadPlan("Steps.StepUntil", args_data, True) + self.assertTrue(err.Success(), err.GetCString()) + + # We should not have exited: + self.assertEqual(process.GetState(), lldb.eStateStopped, "We are stopped") + + # We should still be in foo: + self.assertEqual("foo", frame.GetFunctionName()) + + # And foo should have changed: + self.assertTrue(foo_val.GetValueDidChange(), "Foo changed") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/main.c new file mode 100644 index 00000000000..bfd8a35d556 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/step_scripted/main.c @@ -0,0 +1,13 @@ +#include <stdio.h> + +void foo() { + int foo = 10; + printf("%d\n", foo); // Set a breakpoint here. + foo = 20; + printf("%d\n", foo); +} + +int main() { + foo(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq1/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq1/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq1/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq1/TestAmbiguousTailCallSeq1.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq1/TestAmbiguousTailCallSeq1.py new file mode 100644 index 00000000000..fbd629672be --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq1/TestAmbiguousTailCallSeq1.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + [decorators.skipUnlessHasCallSiteInfo, + decorators.skipIf(dwarf_version=['<', '4'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq1/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq1/main.cpp new file mode 100644 index 00000000000..b59c063ade2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq1/main.cpp @@ -0,0 +1,32 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) sink() { + x++; //% self.filecheck("bt", "main.cpp") + // CHECK-NOT: func{{[23]}}_amb +} + +void __attribute__((noinline)) func3_amb() { sink(); /* tail */ } + +void __attribute__((noinline)) func2_amb() { sink(); /* tail */ } + +void __attribute__((noinline)) func1() { + if (x > 0) + func2_amb(); /* tail */ + else + func3_amb(); /* tail */ +} + +int __attribute__((disable_tail_calls)) main(int argc, char **) { + // The sequences `main -> func1 -> f{2,3}_amb -> sink` are both plausible. Test + // that lldb doesn't attempt to guess which one occurred. + func1(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq2/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq2/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq2/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq2/TestAmbiguousTailCallSeq2.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq2/TestAmbiguousTailCallSeq2.py new file mode 100644 index 00000000000..fbd629672be --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq2/TestAmbiguousTailCallSeq2.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + [decorators.skipUnlessHasCallSiteInfo, + decorators.skipIf(dwarf_version=['<', '4'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq2/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq2/main.cpp new file mode 100644 index 00000000000..21c89199b9f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/ambiguous_tail_call_seq2/main.cpp @@ -0,0 +1,37 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) sink() { + x++; //% self.filecheck("bt", "main.cpp") + // CHECK-NOT: func{{[23]}} +} + +void func2(); + +void __attribute__((noinline)) func1() { + if (x < 1) + func2(); + else + sink(); +} + +void __attribute__((noinline)) func2() { + if (x < 1) + sink(); + else + func1(); +} + +int main() { + // Tail recursion creates ambiguous execution histories. + x = 0; + func1(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_call_site/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_call_site/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_call_site/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_call_site/TestDisambiguateCallSite.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_call_site/TestDisambiguateCallSite.py new file mode 100644 index 00000000000..fbd629672be --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_call_site/TestDisambiguateCallSite.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + [decorators.skipUnlessHasCallSiteInfo, + decorators.skipIf(dwarf_version=['<', '4'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_call_site/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_call_site/main.cpp new file mode 100644 index 00000000000..d4578c67a26 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_call_site/main.cpp @@ -0,0 +1,31 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) sink() { + x++; //% self.filecheck("bt", "main.cpp", "-implicit-check-not=artificial") + // CHECK: frame #0: 0x{{[0-9a-f]+}} a.out`sink() at main.cpp:[[@LINE-1]]:4 [opt] + // CHECK-NEXT: func2{{.*}} [opt] [artificial] + // CHECK-NEXT: main{{.*}} [opt] +} + +void __attribute__((noinline)) func2() { + sink(); /* tail */ +} + +void __attribute__((noinline)) func1() { sink(); /* tail */ } + +int __attribute__((disable_tail_calls)) main(int argc, char **) { + // The sequences `main -> f{1,2} -> sink` are both plausible. Test that + // return-pc call site info allows lldb to pick the correct sequence. + func2(); + if (argc == 100) + func1(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_paths_to_common_sink/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_paths_to_common_sink/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_paths_to_common_sink/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_paths_to_common_sink/TestDisambiguatePathsToCommonSink.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_paths_to_common_sink/TestDisambiguatePathsToCommonSink.py new file mode 100644 index 00000000000..fbd629672be --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_paths_to_common_sink/TestDisambiguatePathsToCommonSink.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + [decorators.skipUnlessHasCallSiteInfo, + decorators.skipIf(dwarf_version=['<', '4'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_paths_to_common_sink/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_paths_to_common_sink/main.cpp new file mode 100644 index 00000000000..6284ef40811 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_paths_to_common_sink/main.cpp @@ -0,0 +1,37 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) sink2() { + x++; //% self.filecheck("bt", "main.cpp", "-check-prefix=FROM-FUNC1") + // FROM-FUNC1: frame #0: 0x{{[0-9a-f]+}} a.out`sink{{.*}} at main.cpp:[[@LINE-1]]:{{.*}} [opt] + // FROM-FUNC1-NEXT: sink({{.*}} [opt] + // FROM-FUNC1-NEXT: func1{{.*}} [opt] [artificial] + // FROM-FUNC1-NEXT: main{{.*}} [opt] +} + +void __attribute__((noinline)) sink(bool called_from_main) { + if (called_from_main) { + x++; //% self.filecheck("bt", "main.cpp", "-check-prefix=FROM-MAIN") + // FROM-MAIN: frame #0: 0x{{[0-9a-f]+}} a.out`sink{{.*}} at main.cpp:[[@LINE-1]]:{{.*}} [opt] + // FROM-MAIN-NEXT: main{{.*}} [opt] + } else { + sink2(); + } +} + +void __attribute__((noinline)) func1() { sink(false); /* tail */ } + +int __attribute__((disable_tail_calls)) main(int argc, char **) { + // When func1 tail-calls sink, make sure that the former appears in the + // backtrace. + sink(true); + func1(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_tail_call_seq/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_tail_call_seq/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_tail_call_seq/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_tail_call_seq/TestDisambiguateTailCallSeq.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_tail_call_seq/TestDisambiguateTailCallSeq.py new file mode 100644 index 00000000000..fbd629672be --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_tail_call_seq/TestDisambiguateTailCallSeq.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + [decorators.skipUnlessHasCallSiteInfo, + decorators.skipIf(dwarf_version=['<', '4'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_tail_call_seq/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_tail_call_seq/main.cpp new file mode 100644 index 00000000000..7816385dda0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/disambiguate_tail_call_seq/main.cpp @@ -0,0 +1,30 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) sink() { + x++; //% self.filecheck("bt", "main.cpp", "-implicit-check-not=artificial") + // CHECK: frame #0: 0x{{[0-9a-f]+}} a.out`sink() at main.cpp:[[@LINE-1]]:4 [opt] + // CHECK-NEXT: func3{{.*}} [opt] [artificial] + // CHECK-NEXT: func1{{.*}} [opt] [artificial] + // CHECK-NEXT: main{{.*}} [opt] +} + +void __attribute__((noinline)) func3() { sink(); /* tail */ } + +void __attribute__((noinline)) func2() { sink(); /* tail */ } + +void __attribute__((noinline)) func1() { func3(); /* tail */ } + +int __attribute__((disable_tail_calls)) main(int argc, char **) { + // The sequences `main -> func1 -> f{2,3} -> sink` are both plausible. Test + // that lldb picks the latter sequence. + func1(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/inlining_and_tail_calls/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/inlining_and_tail_calls/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/inlining_and_tail_calls/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/inlining_and_tail_calls/TestInliningAndTailCalls.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/inlining_and_tail_calls/TestInliningAndTailCalls.py new file mode 100644 index 00000000000..fbd629672be --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/inlining_and_tail_calls/TestInliningAndTailCalls.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + [decorators.skipUnlessHasCallSiteInfo, + decorators.skipIf(dwarf_version=['<', '4'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/inlining_and_tail_calls/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/inlining_and_tail_calls/main.cpp new file mode 100644 index 00000000000..a592d51169d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/inlining_and_tail_calls/main.cpp @@ -0,0 +1,49 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) tail_call_sink() { + x++; //% self.filecheck("bt", "main.cpp", "-check-prefix=TAIL-CALL-SINK") + // TAIL-CALL-SINK: frame #0: 0x{{[0-9a-f]+}} a.out`tail_call_sink() at main.cpp:[[@LINE-1]]:4 [opt] + // TAIL-CALL-SINK-NEXT: func3{{.*}} [opt] [artificial] + // TAIL-CALL-SINK-NEXT: main{{.*}} [opt] + + // TODO: The backtrace should include inlinable_function_which_tail_calls. +} + +void __attribute__((always_inline)) inlinable_function_which_tail_calls() { + tail_call_sink(); +} + +void __attribute__((noinline)) func3() { + inlinable_function_which_tail_calls(); +} + +void __attribute__((always_inline)) inline_sink() { + x++; //% self.filecheck("bt", "main.cpp", "-check-prefix=INLINE-SINK") + // INLINE-SINK: frame #0: 0x{{[0-9a-f]+}} a.out`func2() [inlined] inline_sink() at main.cpp:[[@LINE-1]]:4 [opt] + // INLINE-SINK-NEXT: func2{{.*}} [opt] + // INLINE-SINK-NEXT: func1{{.*}} [opt] [artificial] + // INLINE-SINK-NEXT: main{{.*}} [opt] +} + +void __attribute__((noinline)) func2() { inline_sink(); /* inlined */ } + +void __attribute__((noinline)) func1() { func2(); /* tail */ } + +int __attribute__((disable_tail_calls)) main() { + // First, call a function that tail-calls a function, which itself inlines + // a third function. + func1(); + + // Next, call a function which contains an inlined tail-call. + func3(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/sbapi_support/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/sbapi_support/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/sbapi_support/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/sbapi_support/TestTailCallFrameSBAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/sbapi_support/TestTailCallFrameSBAPI.py new file mode 100644 index 00000000000..e597b8d1696 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/sbapi_support/TestTailCallFrameSBAPI.py @@ -0,0 +1,65 @@ +""" +Test SB API support for identifying artificial (tail call) frames. +""" + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + +class TestTailCallFrameSBAPI(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipIf(compiler="clang", compiler_version=['<', '8.0']) + @skipIf(dwarf_version=['<', '4']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr26265") + def test_tail_call_frame_sbapi(self): + self.build() + self.do_test() + + def do_test(self): + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateBySourceRegex("break here", + lldb.SBFileSpec("main.cpp")) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + error = lldb.SBError() + launch_info = lldb.SBLaunchInfo(None) + process = target.Launch(launch_info, error) + self.assertTrue(process, PROCESS_IS_VALID) + + # Did we hit our breakpoint? + threads = lldbutil.get_threads_stopped_at_breakpoint(process, + breakpoint) + self.assertEqual( + len(threads), 1, + "There should be a thread stopped at our breakpoint") + + self.assertEqual(breakpoint.GetHitCount(), 1) + + thread = threads[0] + + # Here's what we expect to see in the backtrace: + # frame #0: ... a.out`sink() at main.cpp:13:4 [opt] + # frame #1: ... a.out`func3() at main.cpp:14:1 [opt] [artificial] + # frame #2: ... a.out`func2() at main.cpp:18:62 [opt] + # frame #3: ... a.out`func1() at main.cpp:18:85 [opt] [artificial] + # frame #4: ... a.out`main at main.cpp:23:3 [opt] + names = ["sink", "func3", "func2", "func1", "main"] + artificiality = [False, True, False, True, False] + for idx, (name, is_artificial) in enumerate(zip(names, artificiality)): + frame = thread.GetFrameAtIndex(idx) + + # Use a relaxed substring check because function dislpay names are + # platform-dependent. E.g we see "void sink(void)" on Windows, but + # "sink()" on Darwin. This seems like a bug -- just work around it + # for now. + self.assertTrue(name in frame.GetDisplayFunctionName()) + self.assertEqual(frame.IsArtificial(), is_artificial) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/sbapi_support/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/sbapi_support/main.cpp new file mode 100644 index 00000000000..5a2775b0dea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/sbapi_support/main.cpp @@ -0,0 +1,24 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) sink() { + x++; /* break here */ +} + +void __attribute__((noinline)) func3() { sink(); /* tail */ } + +void __attribute__((disable_tail_calls, noinline)) func2() { func3(); /* regular */ } + +void __attribute__((noinline)) func1() { func2(); /* tail */ } + +int __attribute__((disable_tail_calls)) main() { + func1(); /* regular */ + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_message/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_message/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_message/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_message/TestArtificialFrameStepOutMessage.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_message/TestArtificialFrameStepOutMessage.py new file mode 100644 index 00000000000..fbd629672be --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_message/TestArtificialFrameStepOutMessage.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + [decorators.skipUnlessHasCallSiteInfo, + decorators.skipIf(dwarf_version=['<', '4'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_message/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_message/main.cpp new file mode 100644 index 00000000000..df43bcc98ea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_message/main.cpp @@ -0,0 +1,27 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) sink() { + x++; //% self.filecheck("finish", "main.cpp", "-implicit-check-not=artificial") + // CHECK: stop reason = step out + // CHECK-NEXT: Stepped out past: frame #1: 0x{{[0-9a-f]+}} a.out`func3{{.*}} [opt] [artificial] + // CHECK: frame #0: 0x{{[0-9a-f]+}} a.out`func2{{.*}} [opt] +} + +void __attribute__((noinline)) func3() { sink(); /* tail */ } + +void __attribute__((disable_tail_calls, noinline)) func2() { func3(); /* regular */ } + +void __attribute__((noinline)) func1() { func2(); /* tail */ } + +int __attribute__((disable_tail_calls)) main() { + func1(); /* regular */ + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_or_return/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_or_return/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_or_return/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_or_return/TestSteppingOutWithArtificialFrames.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_or_return/TestSteppingOutWithArtificialFrames.py new file mode 100644 index 00000000000..24fc2ba6956 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_or_return/TestSteppingOutWithArtificialFrames.py @@ -0,0 +1,92 @@ +""" +Test SB API support for identifying artificial (tail call) frames. +""" + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + +class TestArtificialFrameThreadStepOut1(TestBase): + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def prepare_thread(self): + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateBySourceRegex("break here", + lldb.SBFileSpec("main.cpp")) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + error = lldb.SBError() + launch_info = lldb.SBLaunchInfo(None) + process = target.Launch(launch_info, error) + self.assertTrue(process, PROCESS_IS_VALID) + + # Did we hit our breakpoint? + threads = lldbutil.get_threads_stopped_at_breakpoint(process, + breakpoint) + self.assertEqual( + len(threads), 1, + "There should be a thread stopped at our breakpoint") + + self.assertEqual(breakpoint.GetHitCount(), 1) + + thread = threads[0] + + # Here's what we expect to see in the backtrace: + # frame #0: ... a.out`sink() at main.cpp:13:4 [opt] + # frame #1: ... a.out`func3() at main.cpp:14:1 [opt] [artificial] + # frame #2: ... a.out`func2() at main.cpp:18:62 [opt] + # frame #3: ... a.out`func1() at main.cpp:18:85 [opt] [artificial] + # frame #4: ... a.out`main at main.cpp:23:3 [opt] + return thread + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr26265") + def test_stepping_out_past_artificial_frame(self): + self.build() + thread = self.prepare_thread() + + # Frame #0's ancestor is artificial. Stepping out should move to + # frame #2, because we behave as-if artificial frames were not present. + thread.StepOut() + frame2 = thread.GetSelectedFrame() + self.assertEqual(frame2.GetDisplayFunctionName(), "func2()") + self.assertFalse(frame2.IsArtificial()) + + # Ditto: stepping out of frame #2 should move to frame #4. + thread.StepOut() + frame4 = thread.GetSelectedFrame() + self.assertEqual(frame4.GetDisplayFunctionName(), "main") + self.assertFalse(frame2.IsArtificial()) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr26265") + def test_return_past_artificial_frame(self): + self.build() + thread = self.prepare_thread() + + value = lldb.SBValue() + + # Frame #0's ancestor is artificial. Returning from frame #0 should move + # to frame #2. + thread.ReturnFromFrame(thread.GetSelectedFrame(), value) + frame2 = thread.GetSelectedFrame() + self.assertEqual(frame2.GetDisplayFunctionName(), "func2()") + self.assertFalse(frame2.IsArtificial()) + + # Ditto: stepping out of frame #2 should move to frame #4. + thread.ReturnFromFrame(thread.GetSelectedFrame(), value) + frame4 = thread.GetSelectedFrame() + self.assertEqual(frame4.GetDisplayFunctionName(), "main") + self.assertFalse(frame2.IsArtificial()) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_or_return/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_or_return/main.cpp new file mode 100644 index 00000000000..4a647031ef1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/thread_step_out_or_return/main.cpp @@ -0,0 +1,24 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) sink() { + x++; // break here +} + +void __attribute__((noinline)) func3() { sink(); /* tail */ } + +void __attribute__((disable_tail_calls, noinline)) func2() { func3(); /* regular */ } + +void __attribute__((noinline)) func1() { func2(); /* tail */ } + +int __attribute__((disable_tail_calls)) main() { + func1(); /* regular */ + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/unambiguous_sequence/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/unambiguous_sequence/Makefile new file mode 100644 index 00000000000..666a6c36554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/unambiguous_sequence/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -g -O2 -glldb +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/unambiguous_sequence/TestUnambiguousTailCalls.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/unambiguous_sequence/TestUnambiguousTailCalls.py new file mode 100644 index 00000000000..fbd629672be --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/unambiguous_sequence/TestUnambiguousTailCalls.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + [decorators.skipUnlessHasCallSiteInfo, + decorators.skipIf(dwarf_version=['<', '4'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/unambiguous_sequence/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/unambiguous_sequence/main.cpp new file mode 100644 index 00000000000..edfe59777c6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tail_call_frames/unambiguous_sequence/main.cpp @@ -0,0 +1,29 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +volatile int x; + +void __attribute__((noinline)) sink() { + x++; //% self.filecheck("bt", "main.cpp", "-implicit-check-not=artificial") + // CHECK: frame #0: 0x{{[0-9a-f]+}} a.out`sink() at main.cpp:[[@LINE-1]]:4 [opt] + // CHECK-NEXT: frame #1: 0x{{[0-9a-f]+}} a.out`func3{{.*}} [opt] [artificial] + // CHECK-NEXT: frame #2: 0x{{[0-9a-f]+}} a.out`func2{{.*}} [opt] + // CHECK-NEXT: frame #3: 0x{{[0-9a-f]+}} a.out`func1{{.*}} [opt] [artificial] + // CHECK-NEXT: frame #4: 0x{{[0-9a-f]+}} a.out`main{{.*}} [opt] +} + +void __attribute__((noinline)) func3() { sink(); /* tail */ } + +void __attribute__((disable_tail_calls, noinline)) func2() { func3(); /* regular */ } + +void __attribute__((noinline)) func1() { func2(); /* tail */ } + +int __attribute__((disable_tail_calls)) main() { + func1(); /* regular */ + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target-new-solib-notifications/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target-new-solib-notifications/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target-new-solib-notifications/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target-new-solib-notifications/TestModuleLoadedNotifys.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target-new-solib-notifications/TestModuleLoadedNotifys.py new file mode 100644 index 00000000000..b3db5f7a85d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target-new-solib-notifications/TestModuleLoadedNotifys.py @@ -0,0 +1,111 @@ +""" +Test how many times newly loaded binaries are notified; +they should be delivered in batches instead of one-by-one. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class ModuleLoadedNotifysTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + # DyanmicLoaderDarwin should batch up notifications about + # newly added/removed libraries. Other DynamicLoaders may + # not be written this way. + @skipUnlessDarwin + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// breakpoint') + + def test_launch_notifications(self): + """Test that lldb broadcasts newly loaded libraries in batches.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.dbg.SetAsync(False) + + listener = self.dbg.GetListener() + listener.StartListeningForEventClass( + self.dbg, + lldb.SBTarget.GetBroadcasterClassName(), + lldb.SBTarget.eBroadcastBitModulesLoaded | lldb.SBTarget.eBroadcastBitModulesUnloaded) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # break on main + breakpoint = target.BreakpointCreateByName('main', 'a.out') + + event = lldb.SBEvent() + # CreateTarget() generated modules-loaded events; consume them & toss + while listener.GetNextEvent(event): + True + + error = lldb.SBError() + process = target.Launch(listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error + + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + total_solibs_added = 0 + total_solibs_removed = 0 + total_modules_added_events = 0 + total_modules_removed_events = 0 + while listener.GetNextEvent(event): + if lldb.SBTarget.EventIsTargetEvent(event): + if event.GetType() == lldb.SBTarget.eBroadcastBitModulesLoaded: + solib_count = lldb.SBTarget.GetNumModulesFromEvent(event) + total_modules_added_events += 1 + total_solibs_added += solib_count + if self.TraceOn(): + # print all of the binaries that have been added + added_files = [] + i = 0 + while i < solib_count: + module = lldb.SBTarget.GetModuleAtIndexFromEvent(i, event) + added_files.append(module.GetFileSpec().GetFilename()) + i = i + 1 + print("Loaded files: %s" % (', '.join(added_files))) + + if event.GetType() == lldb.SBTarget.eBroadcastBitModulesUnloaded: + solib_count = lldb.SBTarget.GetNumModulesFromEvent(event) + total_modules_removed_events += 1 + total_solibs_removed += solib_count + if self.TraceOn(): + # print all of the binaries that have been removed + removed_files = [] + i = 0 + while i < solib_count: + module = lldb.SBTarget.GetModuleAtIndexFromEvent(i, event) + removed_files.append(module.GetFileSpec().GetFilename()) + i = i + 1 + print("Unloaded files: %s" % (', '.join(removed_files))) + + + # This is testing that we get back a small number of events with the loaded + # binaries in batches. Check that we got back more than 1 solib per event. + # In practice on Darwin today, we get back two events for a do-nothing c + # program: a.out and dyld, and then all the rest of the system libraries. + + avg_solibs_added_per_event = int(float(total_solibs_added) / float(total_modules_added_events)) + self.assertGreater(avg_solibs_added_per_event, 1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target-new-solib-notifications/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target-new-solib-notifications/main.cpp new file mode 100644 index 00000000000..00130c93b88 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target-new-solib-notifications/main.cpp @@ -0,0 +1,6 @@ +#include <stdio.h> +int main () +{ + puts("running"); // breakpoint here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/Makefile new file mode 100644 index 00000000000..806c96740af --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/Makefile @@ -0,0 +1,8 @@ +include Makefile.rules + +a.out: globals.ll + $(CC) $(CFLAGS) -g -c $^ -o globals.o + $(LD) $(LDFLAGS) -g globals.o -o $@ + +clean:: + rm -rf globals.o a.out *.dSYM diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/TestTargetVar.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/TestTargetVar.py new file mode 100644 index 00000000000..f8c2a690147 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/TestTargetVar.py @@ -0,0 +1,22 @@ +""" +Test that target var can resolve complex DWARF expressions. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class targetCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # needs x86_64 + @skipIf(debug_info="gmodules") # not relevant + @skipIf(compiler="clang", compiler_version=['<', '7.0']) + def testTargetVarExpr(self): + self.build() + lldbutil.run_to_name_breakpoint(self, 'main') + self.expect("target variable i", substrs=['i', '42']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/globals.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/globals.c new file mode 100644 index 00000000000..26619284964 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/globals.c @@ -0,0 +1,6 @@ +int i = 42; +int *p = &i; + +int main() { + return *p; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/globals.ll b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/globals.ll new file mode 100644 index 00000000000..192d4e12698 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/target_var/globals.ll @@ -0,0 +1,42 @@ +source_filename = "globals.c" +target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128" +target triple = "x86_64-apple-macosx10.14.0" + +@i = global i32 42, align 4 +@p = global i32* @i, align 8, !dbg !0, !dbg !6 + +; Function Attrs: noinline nounwind optnone ssp uwtable +define i32 @main() #0 !dbg !15 { +entry: + %retval = alloca i32, align 4 + store i32 0, i32* %retval, align 4 + %0 = load i32*, i32** @p, align 8, !dbg !18 + %1 = load i32, i32* %0, align 4, !dbg !18 + ret i32 %1, !dbg !18 +} + +attributes #0 = { noinline nounwind optnone ssp uwtable } + +!llvm.dbg.cu = !{!2} +!llvm.module.flags = !{!10, !11, !12, !13} +!llvm.ident = !{!14} + +!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression(DW_OP_deref)) +!1 = distinct !DIGlobalVariable(name: "i", scope: !2, file: !3, line: 1, type: !9, isLocal: false, isDefinition: true) +!2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3, emissionKind: FullDebug, globals: !5) +!3 = !DIFile(filename: "globals.c", directory: "/") +!4 = !{} +!5 = !{!0, !6} +!6 = !DIGlobalVariableExpression(var: !7, expr: !DIExpression()) +!7 = distinct !DIGlobalVariable(name: "p", scope: !2, file: !3, line: 2, type: !8, isLocal: false, isDefinition: true) +!8 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !9, size: 64) +!9 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) +!10 = !{i32 2, !"Dwarf Version", i32 4} +!11 = !{i32 2, !"Debug Info Version", i32 3} +!12 = !{i32 1, !"wchar_size", i32 4} +!13 = !{i32 7, !"PIC Level", i32 2} +!14 = !{!"clang version 8.0.0 (trunk 340838) (llvm/trunk 340843)"} +!15 = distinct !DISubprogram(name: "main", scope: !3, file: !3, line: 4, type: !16, isLocal: false, isDefinition: true, scopeLine: 4, isOptimized: false, unit: !2, retainedNodes: !4) +!16 = !DISubroutineType(types: !17) +!17 = !{!9} +!18 = !DILocation(line: 5, scope: !15) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/testid/TestTestId.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/testid/TestTestId.py new file mode 100644 index 00000000000..b3d331773f8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/testid/TestTestId.py @@ -0,0 +1,16 @@ +""" +Add a test to verify our test instance returns something non-None for +an id(). Other parts of the test running infrastructure are counting on this. +""" + +from lldbsuite.test.lldbtest import TestBase + +class TestIdTestCase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + def test_id_exists(self): + self.assertIsNotNone(self.id(), "Test instance should have an id()") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/Makefile new file mode 100644 index 00000000000..cd092b77256 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/Makefile @@ -0,0 +1,5 @@ +CXXFLAGS_EXTRAS := -std=c++11 +CXX_SOURCES := ParallelTask.cpp +ENABLE_THREADS := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/ParallelTask.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/ParallelTask.cpp new file mode 100644 index 00000000000..8e0f76f691b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/ParallelTask.cpp @@ -0,0 +1,152 @@ +#include <cstdint> +#include <thread> +#include <vector> +#include <queue> +#include <functional> +#include <future> +#include <iostream> +#include <cassert> + +class TaskPoolImpl +{ +public: + TaskPoolImpl(uint32_t num_threads) : + m_stop(false) + { + for (uint32_t i = 0; i < num_threads; ++i) + m_threads.emplace_back(Worker, this); + } + + ~TaskPoolImpl() + { + Stop(); + } + + template<typename F, typename... Args> + std::future<typename std::result_of<F(Args...)>::type> + AddTask(F&& f, Args&&... args) + { + auto task = std::make_shared<std::packaged_task<typename std::result_of<F(Args...)>::type()>>( + std::bind(std::forward<F>(f), std::forward<Args>(args)...)); + + std::unique_lock<std::mutex> lock(m_tasks_mutex); + assert(!m_stop && "Can't add task to TaskPool after it is stopped"); + m_tasks.emplace([task](){ (*task)(); }); + lock.unlock(); + m_tasks_cv.notify_one(); + + return task->get_future(); + } + + void + Stop() + { + std::unique_lock<std::mutex> lock(m_tasks_mutex); + m_stop = true; + m_tasks_mutex.unlock(); + m_tasks_cv.notify_all(); + for (auto& t : m_threads) + t.join(); + } + +private: + static void + Worker(TaskPoolImpl* pool) + { + while (true) + { + std::unique_lock<std::mutex> lock(pool->m_tasks_mutex); + if (pool->m_tasks.empty()) + pool->m_tasks_cv.wait(lock, [pool](){ return !pool->m_tasks.empty() || pool->m_stop; }); + if (pool->m_tasks.empty()) + break; + + std::function<void()> f = pool->m_tasks.front(); + pool->m_tasks.pop(); + lock.unlock(); + + f(); + } + } + + std::queue<std::function<void()>> m_tasks; + std::mutex m_tasks_mutex; + std::condition_variable m_tasks_cv; + bool m_stop; + std::vector<std::thread> m_threads; +}; + +class TaskPool +{ +public: + // Add a new task to the thread pool and return a std::future belongs for the newly created task. + // The caller of this function have to wait on the future for this task to complete. + template<typename F, typename... Args> + static std::future<typename std::result_of<F(Args...)>::type> + AddTask(F&& f, Args&&... args) + { + return GetImplementation().AddTask(std::forward<F>(f), std::forward<Args>(args)...); + } + + // Run all of the specified tasks on the thread pool and wait until all of them are finished + // before returning + template<typename... T> + static void + RunTasks(T&&... t) + { + RunTaskImpl<T...>::Run(std::forward<T>(t)...); + } + +private: + static TaskPoolImpl& + GetImplementation() + { + static TaskPoolImpl g_task_pool_impl(std::thread::hardware_concurrency()); + return g_task_pool_impl; + } + + template<typename... T> + struct RunTaskImpl; +}; + +template<typename H, typename... T> +struct TaskPool::RunTaskImpl<H, T...> +{ + static void + Run(H&& h, T&&... t) + { + auto f = AddTask(std::forward<H>(h)); + RunTaskImpl<T...>::Run(std::forward<T>(t)...); + f.wait(); + } +}; + +template<> +struct TaskPool::RunTaskImpl<> +{ + static void + Run() {} +}; + +int main() +{ + std::vector<std::future<uint32_t>> tasks; + for (int i = 0; i < 100000; ++i) + { + tasks.emplace_back(TaskPool::AddTask([](int i){ + uint32_t s = 0; + for (int j = 0; j <= i; ++j) + s += j; + return s; + }, + i)); + } + + for (auto& it : tasks) // Set breakpoint here + it.wait(); + + TaskPool::RunTasks( + []() { return 1; }, + []() { return "aaaa"; } + ); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py new file mode 100644 index 00000000000..870b6b223c8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py @@ -0,0 +1,65 @@ +""" +Test regression for Bug 25251. +""" + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BacktraceAllTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number for our breakpoint. + self.breakpoint = line_number( + 'ParallelTask.cpp', '// Set breakpoint here') + + # The android-arm compiler can't compile the inferior + @skipIfTargetAndroid(archs=["arm"]) + # because of an issue around std::future. + # TODO: Change the test to don't depend on std::future<T> + def test(self): + """Test breakpoint handling after a thread join.""" + self.build(dictionary=self.getBuildFlags()) + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint + lldbutil.run_break_set_by_file_and_line( + self, "ParallelTask.cpp", self.breakpoint, num_expected_locations=-1) + + # The breakpoint list should show 1 location. + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'ParallelTask.cpp', line = %d, exact_match = 0" % + self.breakpoint]) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This should not result in a segmentation fault + self.expect("thread backtrace all", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."]) + + # Run to completion + self.runCmd("continue") + +if __name__ == '__main__': + import atexit + lldb.SBDebugger.Initialize() + atexit.register(lambda: lldb.SBDebugger.Terminate()) + unittest2.main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_limit/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_limit/Makefile new file mode 100644 index 00000000000..5fd720c6d06 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_limit/Makefile @@ -0,0 +1,5 @@ +CXXFLAGS_EXTRAS := -std=c++11 +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_limit/TestBacktraceLimit.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_limit/TestBacktraceLimit.py new file mode 100644 index 00000000000..6dbb3e30ee7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_limit/TestBacktraceLimit.py @@ -0,0 +1,27 @@ +""" +Test that the target.process.thread.max-backtrace-depth setting works. +""" + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BacktraceLimitSettingTest(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_backtrace_depth(self): + """Test that the max-backtrace-depth setting limits backtraces.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.cpp") + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", self.main_source_file) + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + interp.HandleCommand("settings set target.process.thread.max-backtrace-depth 30", result) + self.assertEqual(True, result.Succeeded()) + self.assertEqual(30, thread.GetNumFrames()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_limit/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_limit/main.cpp new file mode 100644 index 00000000000..eca1eadc8e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/backtrace_limit/main.cpp @@ -0,0 +1,13 @@ +int bottom () { + return 1; // Set a breakpoint here +} +int foo(int in) { + if (in > 0) + return foo(--in) + 5; + else + return bottom(); +} +int main() +{ + return foo(500); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/Makefile new file mode 100644 index 00000000000..566938ca0cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py new file mode 100644 index 00000000000..391f9d96597 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py @@ -0,0 +1,93 @@ +""" +Test number of threads. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointAfterJoinTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number for our breakpoint. + self.breakpoint = line_number('main.cpp', '// Set breakpoint here') + + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained and <rdar://problem/28557237>") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureNetBSD + def test(self): + """Test breakpoint handling after a thread join.""" + self.build(dictionary=self.getBuildFlags()) + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint in the main thread. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) + + # The breakpoint list should show 1 location. + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.breakpoint]) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + # The exit probably occurred during breakpoint handling, but it isn't + # guaranteed. The main thing we're testing here is that the debugger + # handles this cleanly is some way. + + # Get the number of threads + num_threads = process.GetNumThreads() + + # Make sure we see at least six threads + self.assertTrue( + num_threads >= 6, + 'Number of expected threads and actual threads do not match.') + + # Make sure all threads are stopped + for i in range(0, num_threads): + self.assertTrue( + process.GetThreadAtIndex(i).IsStopped(), + "Thread {0} didn't stop during breakpoint.".format(i)) + + # Run to completion + self.runCmd("continue") + + # If the process hasn't exited, collect some information + if process.GetState() != lldb.eStateExited: + self.runCmd("thread list") + self.runCmd("process status") + + # At this point, the inferior process should have exited. + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/main.cpp new file mode 100644 index 00000000000..a589d979003 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/main.cpp @@ -0,0 +1,105 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test is intended to create a situation in which one thread will exit +// while a breakpoint is being handled in another thread. This may not always +// happen because it's possible that the exiting thread will exit before the +// breakpoint is hit. The test case should be flexible enough to treat that +// as success. + +#include "pseudo_barrier.h" +#include <chrono> +#include <thread> + +volatile int g_test = 0; + +// A barrier to synchronize all the threads. +pseudo_barrier_t g_barrier1; + +// A barrier to keep the threads from exiting until after the breakpoint has +// been passed. +pseudo_barrier_t g_barrier2; + +void * +break_thread_func () +{ + // Wait until all the threads are running + pseudo_barrier_wait(g_barrier1); + + // Wait for the join thread to join + std::this_thread::sleep_for(std::chrono::microseconds(50)); + + // Do something + g_test++; // Set breakpoint here + + // Synchronize after the breakpoint + pseudo_barrier_wait(g_barrier2); + + // Return + return NULL; +} + +void * +wait_thread_func () +{ + // Wait until the entire first group of threads is running + pseudo_barrier_wait(g_barrier1); + + // Wait until the breakpoint has been passed + pseudo_barrier_wait(g_barrier2); + + // Return + return NULL; +} + +void * +join_thread_func (void *input) +{ + std::thread *thread_to_join = (std::thread *)input; + + // Sync up with the rest of the threads. + pseudo_barrier_wait(g_barrier1); + + // Join the other thread + thread_to_join->join(); + + // Return + return NULL; +} + +int main () +{ + // The first barrier waits for the non-joining threads to start. + // This thread will also participate in that barrier. + // The idea here is to guarantee that the joining thread will be + // last in the internal list maintained by the debugger. + pseudo_barrier_init(g_barrier1, 5); + + // The second barrier keeps the waiting threads around until the breakpoint + // has been passed. + pseudo_barrier_init(g_barrier2, 4); + + // Create a thread to hit the breakpoint + std::thread thread_1(break_thread_func); + + // Create more threads to slow the debugger down during processing. + std::thread thread_2(wait_thread_func); + std::thread thread_3(wait_thread_func); + std::thread thread_4(wait_thread_func); + + // Create a thread to join the breakpoint thread + std::thread thread_5(join_thread_func, &thread_1); + + // Wait for the threads to finish + thread_5.join(); // implies thread_1 is already finished + thread_4.join(); + thread_3.join(); + thread_2.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/Makefile new file mode 100644 index 00000000000..c33ae5685ef --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +ENABLE_THREADS := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentBreakpointDelayBreakpointOneSignal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentBreakpointDelayBreakpointOneSignal.py new file mode 100644 index 00000000000..a0c1da8dad1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentBreakpointDelayBreakpointOneSignal.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentBreakpointDelayBreakpointOneSignal(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @expectedFailureNetBSD + def test(self): + """Test two threads that trigger a breakpoint (one with a 1 second delay) and one signal thread. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_breakpoint_threads=1, + num_delay_breakpoint_threads=1, + num_signal_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentBreakpointOneDelayBreakpointThreads.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentBreakpointOneDelayBreakpointThreads.py new file mode 100644 index 00000000000..bcee1c54e76 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentBreakpointOneDelayBreakpointThreads.py @@ -0,0 +1,21 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentBreakpointOneDelayBreakpointThreads(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + def test(self): + """Test threads that trigger a breakpoint where one thread has a 1 second delay. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_breakpoint_threads=1, + num_delay_breakpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentBreakpointsDelayedBreakpointOneWatchpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentBreakpointsDelayedBreakpointOneWatchpoint.py new file mode 100644 index 00000000000..dfe2cb7d23e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentBreakpointsDelayedBreakpointOneWatchpoint.py @@ -0,0 +1,24 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentBreakpointsDelayedBreakpointOneWatchpoint( + ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test a breakpoint, a delayed breakpoint, and one watchpoint thread. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_breakpoint_threads=1, + num_delay_breakpoint_threads=1, + num_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithBreak.py new file mode 100644 index 00000000000..9083c3838bc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithBreak.py @@ -0,0 +1,20 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentCrashWithBreak(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + def test(self): + """ Test a thread that crashes while another thread hits a breakpoint.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_crash_threads=1, num_breakpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithSignal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithSignal.py new file mode 100644 index 00000000000..37795be849d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithSignal.py @@ -0,0 +1,20 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentCrashWithSignal(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + def test(self): + """ Test a thread that crashes while another thread generates a signal.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_crash_threads=1, num_signal_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithWatchpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithWatchpoint.py new file mode 100644 index 00000000000..13f5b4ad35e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithWatchpoint.py @@ -0,0 +1,21 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentCrashWithWatchpoint(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """ Test a thread that crashes while another thread hits a watchpoint.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_crash_threads=1, num_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithWatchpointBreakpointSignal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithWatchpointBreakpointSignal.py new file mode 100644 index 00000000000..3de0850abe2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentCrashWithWatchpointBreakpointSignal.py @@ -0,0 +1,24 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentCrashWithWatchpointBreakpointSignal(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """ Test a thread that crashes while other threads generate a signal and hit a watchpoint and breakpoint. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_crash_threads=1, + num_breakpoint_threads=1, + num_signal_threads=1, + num_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelaySignalBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelaySignalBreak.py new file mode 100644 index 00000000000..af9c6c994ab --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelaySignalBreak.py @@ -0,0 +1,22 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentDelaySignalBreak(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + def test(self): + """Test (1-second delay) signal and a breakpoint in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_breakpoint_threads=1, + num_delay_signal_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelaySignalWatch.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelaySignalWatch.py new file mode 100644 index 00000000000..91358f34676 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelaySignalWatch.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentDelaySignalWatch(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test a watchpoint and a (1 second delay) signal in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_delay_signal_threads=1, + num_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelayWatchBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelayWatchBreak.py new file mode 100644 index 00000000000..8f7a8ba6a08 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelayWatchBreak.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentDelayWatchBreak(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test (1-second delay) watchpoint and a breakpoint in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_breakpoint_threads=1, + num_delay_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelayedCrashWithBreakpointSignal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelayedCrashWithBreakpointSignal.py new file mode 100644 index 00000000000..9c1ac90423c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelayedCrashWithBreakpointSignal.py @@ -0,0 +1,22 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentDelayedCrashWithBreakpointSignal(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + def test(self): + """ Test a thread with a delayed crash while other threads generate a signal and hit a breakpoint. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_delay_crash_threads=1, + num_breakpoint_threads=1, + num_signal_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelayedCrashWithBreakpointWatchpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelayedCrashWithBreakpointWatchpoint.py new file mode 100644 index 00000000000..12344ffb061 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentDelayedCrashWithBreakpointWatchpoint.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentDelayedCrashWithBreakpointWatchpoint(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """ Test a thread with a delayed crash while other threads hit a watchpoint and a breakpoint. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_delay_crash_threads=1, + num_breakpoint_threads=1, + num_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManyBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManyBreakpoints.py new file mode 100644 index 00000000000..bbbfbdb0958 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManyBreakpoints.py @@ -0,0 +1,20 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentManyBreakpoints(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @skipIfOutOfTreeDebugserver + def test(self): + """Test 100 breakpoints from 100 threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_breakpoint_threads=100) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManyCrash.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManyCrash.py new file mode 100644 index 00000000000..0530728b6ac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManyCrash.py @@ -0,0 +1,20 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentManyCrash(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @skipIfOutOfTreeDebugserver + def test(self): + """Test 100 threads that cause a segfault.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_crash_threads=100) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManySignals.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManySignals.py new file mode 100644 index 00000000000..ec06227ec54 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManySignals.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentManySignals(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + # This test is flaky on Darwin. + @skipIfDarwin + @expectedFailureNetBSD + @skipIfOutOfTreeDebugserver + def test(self): + """Test 100 signals from 100 threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_signal_threads=100) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManyWatchpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManyWatchpoints.py new file mode 100644 index 00000000000..2274fbb6d4a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentManyWatchpoints.py @@ -0,0 +1,21 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentManyWatchpoints(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + @skipIfOutOfTreeDebugserver + def test(self): + """Test 100 watchpoints from 100 threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_watchpoint_threads=100) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentNWatchNBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentNWatchNBreak.py new file mode 100644 index 00000000000..2c5205fc49f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentNWatchNBreak.py @@ -0,0 +1,22 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentNWatchNBreak(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test with 5 watchpoint and breakpoint threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_watchpoint_threads=5, + num_breakpoint_threads=5) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalBreak.py new file mode 100644 index 00000000000..6c18cb2e965 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalBreak.py @@ -0,0 +1,20 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentSignalBreak(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + def test(self): + """Test signal and a breakpoint in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_breakpoint_threads=1, num_signal_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalDelayBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalDelayBreak.py new file mode 100644 index 00000000000..e1779b44f7c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalDelayBreak.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentSignalDelayBreak(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @expectedFailureNetBSD + def test(self): + """Test signal and a (1 second delay) breakpoint in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_delay_breakpoint_threads=1, + num_signal_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalDelayWatch.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalDelayWatch.py new file mode 100644 index 00000000000..d932d5f847b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalDelayWatch.py @@ -0,0 +1,24 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentSignalDelayWatch(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @expectedFailureNetBSD + @add_test_categories(["watchpoint"]) + def test(self): + """Test a (1 second delay) watchpoint and a signal in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_signal_threads=1, + num_delay_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalNWatchNBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalNWatchNBreak.py new file mode 100644 index 00000000000..3b005e559a4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalNWatchNBreak.py @@ -0,0 +1,24 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentSignalNWatchNBreak(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @expectedFailureNetBSD + @add_test_categories(["watchpoint"]) + def test(self): + """Test one signal thread with 5 watchpoint and breakpoint threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_signal_threads=1, + num_watchpoint_threads=5, + num_breakpoint_threads=5) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalWatch.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalWatch.py new file mode 100644 index 00000000000..6cf26aea9e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalWatch.py @@ -0,0 +1,21 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentSignalWatch(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test a watchpoint and a signal in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_signal_threads=1, num_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalWatchBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalWatchBreak.py new file mode 100644 index 00000000000..38a51258853 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentSignalWatchBreak.py @@ -0,0 +1,24 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentSignalWatchBreak(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @expectedFailureNetBSD + @add_test_categories(["watchpoint"]) + def test(self): + """Test a signal/watchpoint/breakpoint in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_signal_threads=1, + num_watchpoint_threads=1, + num_breakpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointThreads.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointThreads.py new file mode 100644 index 00000000000..5ddc15bd964 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointThreads.py @@ -0,0 +1,20 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentTwoBreakpointThreads(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + def test(self): + """Test two threads that trigger a breakpoint. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_breakpoint_threads=2) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointsOneDelaySignal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointsOneDelaySignal.py new file mode 100644 index 00000000000..07f99b0f82e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointsOneDelaySignal.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentTwoBreakpointsOneDelaySignal(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @expectedFailureNetBSD + def test(self): + """Test two threads that trigger a breakpoint and one (1 second delay) signal thread. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_breakpoint_threads=2, + num_delay_signal_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointsOneSignal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointsOneSignal.py new file mode 100644 index 00000000000..1ad1c591c7e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointsOneSignal.py @@ -0,0 +1,21 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentTwoBreakpointsOneSignal(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @expectedFailureNetBSD + def test(self): + """Test two threads that trigger a breakpoint and one signal thread. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_breakpoint_threads=2, num_signal_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointsOneWatchpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointsOneWatchpoint.py new file mode 100644 index 00000000000..47e973a4871 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoBreakpointsOneWatchpoint.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentTwoBreakpointsOneWatchpoint(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test two threads that trigger a breakpoint and one watchpoint thread. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_breakpoint_threads=2, + num_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointThreads.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointThreads.py new file mode 100644 index 00000000000..bdc6f8ef87e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointThreads.py @@ -0,0 +1,21 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentTwoWatchpointThreads(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test two threads that trigger a watchpoint. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_watchpoint_threads=2) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointsOneBreakpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointsOneBreakpoint.py new file mode 100644 index 00000000000..163f76d189b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointsOneBreakpoint.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentTwoWatchpointsOneBreakpoint(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test two threads that trigger a watchpoint and one breakpoint thread. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_watchpoint_threads=2, + num_breakpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointsOneDelayBreakpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointsOneDelayBreakpoint.py new file mode 100644 index 00000000000..1ec5e065dc4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointsOneDelayBreakpoint.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentTwoWatchpointsOneDelayBreakpoint(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test two threads that trigger a watchpoint and one (1 second delay) breakpoint thread. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_watchpoint_threads=2, + num_delay_breakpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointsOneSignal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointsOneSignal.py new file mode 100644 index 00000000000..8f044badf5e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentTwoWatchpointsOneSignal.py @@ -0,0 +1,22 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentTwoWatchpointsOneSignal(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @expectedFailureNetBSD + @add_test_categories(["watchpoint"]) + def test(self): + """Test two threads that trigger a watchpoint and one signal thread. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_watchpoint_threads=2, num_signal_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchBreak.py new file mode 100644 index 00000000000..4a418082ff0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchBreak.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentWatchBreak(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test watchpoint and a breakpoint in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_breakpoint_threads=1, + num_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchBreakDelay.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchBreakDelay.py new file mode 100644 index 00000000000..2bc08399322 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchBreakDelay.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentWatchBreakDelay(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test watchpoint and a (1 second delay) breakpoint in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions( + num_delay_breakpoint_threads=1, + num_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchpointDelayWatchpointOneBreakpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchpointDelayWatchpointOneBreakpoint.py new file mode 100644 index 00000000000..dce84fed775 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchpointDelayWatchpointOneBreakpoint.py @@ -0,0 +1,23 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentWatchpointDelayWatchpointOneBreakpoint(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test two threads that trigger a watchpoint (one with a 1 second delay) and one breakpoint thread. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_watchpoint_threads=1, + num_delay_watchpoint_threads=1, + num_breakpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchpointWithDelayWatchpointThreads.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchpointWithDelayWatchpointThreads.py new file mode 100644 index 00000000000..87b8ea0d775 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentWatchpointWithDelayWatchpointThreads.py @@ -0,0 +1,22 @@ + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.concurrent_base import ConcurrentEventsBase +from lldbsuite.test.lldbtest import TestBase + + +@skipIfWindows +class ConcurrentWatchpointWithDelayWatchpointThreads(ConcurrentEventsBase): + + mydir = ConcurrentEventsBase.compute_mydir(__file__) + + @skipIfFreeBSD # timing out on buildbot + # Atomic sequences are not supported yet for MIPS in LLDB. + @skipIf(triple='^mips') + @add_test_categories(["watchpoint"]) + def test(self): + """Test two threads that trigger a watchpoint where one thread has a 1 second delay. """ + self.build(dictionary=self.getBuildFlags()) + self.do_thread_actions(num_watchpoint_threads=1, + num_delay_watchpoint_threads=1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/main.cpp new file mode 100644 index 00000000000..33ec8ad1f50 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/main.cpp @@ -0,0 +1,187 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test is intended to create a situation in which multiple events +// (breakpoints, watchpoints, crashes, and signal generation/delivery) happen +// from multiple threads. The test expects the debugger to set a breakpoint on +// the main thread (before any worker threads are spawned) and modify variables +// which control the number of threads that are spawned for each action. + +#include "pseudo_barrier.h" +#include <vector> +using namespace std; + +#include <pthread.h> + +#include <signal.h> +#include <sys/types.h> +#include <unistd.h> + +typedef std::vector<std::pair<unsigned, void*(*)(void*)> > action_counts; +typedef std::vector<pthread_t> thread_vector; + +pseudo_barrier_t g_barrier; +int g_breakpoint = 0; +int g_sigusr1_count = 0; +uint32_t g_watchme; + +struct action_args { + int delay; +}; + +// Perform any extra actions required by thread 'input' arg +void do_action_args(void *input) { + if (input) { + action_args *args = static_cast<action_args*>(input); + sleep(args->delay); + } +} + +void * +breakpoint_func (void *input) +{ + // Wait until all threads are running + pseudo_barrier_wait(g_barrier); + do_action_args(input); + + // Do something + g_breakpoint++; // Set breakpoint here + return 0; +} + +void * +signal_func (void *input) { + // Wait until all threads are running + pseudo_barrier_wait(g_barrier); + do_action_args(input); + + // Send a user-defined signal to the current process + //kill(getpid(), SIGUSR1); + // Send a user-defined signal to the current thread + pthread_kill(pthread_self(), SIGUSR1); + + return 0; +} + +void * +watchpoint_func (void *input) { + pseudo_barrier_wait(g_barrier); + do_action_args(input); + + g_watchme = 1; // watchpoint triggers here + return 0; +} + +void * +crash_func (void *input) { + pseudo_barrier_wait(g_barrier); + do_action_args(input); + + int *a = 0; + *a = 5; // crash happens here + return 0; +} + +void sigusr1_handler(int sig) { + if (sig == SIGUSR1) + g_sigusr1_count += 1; // Break here in signal handler +} + +/// Register a simple function for to handle signal +void register_signal_handler(int signal, void (*handler)(int)) +{ + sigset_t empty_sigset; + sigemptyset(&empty_sigset); + + struct sigaction action; + action.sa_sigaction = 0; + action.sa_mask = empty_sigset; + action.sa_flags = 0; + action.sa_handler = handler; + sigaction(SIGUSR1, &action, 0); +} + +void start_threads(thread_vector& threads, + action_counts& actions, + void* args = 0) { + action_counts::iterator b = actions.begin(), e = actions.end(); + for(action_counts::iterator i = b; i != e; ++i) { + for(unsigned count = 0; count < i->first; ++count) { + pthread_t t; + pthread_create(&t, 0, i->second, args); + threads.push_back(t); + } + } +} + +int dotest() +{ + g_watchme = 0; + + // Actions are triggered immediately after the thread is spawned + unsigned num_breakpoint_threads = 1; + unsigned num_watchpoint_threads = 0; + unsigned num_signal_threads = 1; + unsigned num_crash_threads = 0; + + // Actions below are triggered after a 1-second delay + unsigned num_delay_breakpoint_threads = 0; + unsigned num_delay_watchpoint_threads = 0; + unsigned num_delay_signal_threads = 0; + unsigned num_delay_crash_threads = 0; + + register_signal_handler(SIGUSR1, sigusr1_handler); // Break here and adjust num_[breakpoint|watchpoint|signal|crash]_threads + + unsigned total_threads = num_breakpoint_threads \ + + num_watchpoint_threads \ + + num_signal_threads \ + + num_crash_threads \ + + num_delay_breakpoint_threads \ + + num_delay_watchpoint_threads \ + + num_delay_signal_threads \ + + num_delay_crash_threads; + + // Don't let either thread do anything until they're both ready. + pseudo_barrier_init(g_barrier, total_threads); + + action_counts actions; + actions.push_back(std::make_pair(num_breakpoint_threads, breakpoint_func)); + actions.push_back(std::make_pair(num_watchpoint_threads, watchpoint_func)); + actions.push_back(std::make_pair(num_signal_threads, signal_func)); + actions.push_back(std::make_pair(num_crash_threads, crash_func)); + + action_counts delay_actions; + delay_actions.push_back(std::make_pair(num_delay_breakpoint_threads, breakpoint_func)); + delay_actions.push_back(std::make_pair(num_delay_watchpoint_threads, watchpoint_func)); + delay_actions.push_back(std::make_pair(num_delay_signal_threads, signal_func)); + delay_actions.push_back(std::make_pair(num_delay_crash_threads, crash_func)); + + // Create threads that handle instant actions + thread_vector threads; + start_threads(threads, actions); + + // Create threads that handle delayed actions + action_args delay_arg; + delay_arg.delay = 1; + start_threads(threads, delay_actions, &delay_arg); + + // Join all threads + typedef std::vector<pthread_t>::iterator thread_iterator; + for(thread_iterator t = threads.begin(); t != threads.end(); ++t) + pthread_join(*t, 0); + + return 0; +} + +int main () +{ + dotest(); + return 0; // Break here and verify one thread is active. +} + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/Makefile new file mode 100644 index 00000000000..3d0b98f13f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/Makefile @@ -0,0 +1,2 @@ +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py new file mode 100644 index 00000000000..3394bb2d6aa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py @@ -0,0 +1,61 @@ +""" +Test that step-inst over a crash behaves correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CrashDuringStepTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.breakpoint = line_number('main.cpp', '// Set breakpoint here') + + # IO error due to breakpoint at invalid address + @expectedFailureAll(triple=re.compile('^mips')) + def test_step_inst_with(self): + """Test thread creation during step-inst handling.""" + self.build(dictionary=self.getBuildFlags()) + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target and target.IsValid(), "Target is valid") + + self.bp_num = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) + + # Run the program. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) + + # The stop reason should be breakpoint. + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid(), STOPPED_DUE_TO_BREAKPOINT) + + # Keep stepping until the inferior crashes + while process.GetState() == lldb.eStateStopped and not lldbutil.is_thread_crashed(self, thread): + thread.StepInstruction(False) + + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + self.assertTrue( + lldbutil.is_thread_crashed( + self, + thread), + "Thread has crashed") + process.Kill() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/main.cpp new file mode 100644 index 00000000000..34cccf4dc2a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/main.cpp @@ -0,0 +1,15 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +void (*crash)() = nullptr; + +int main() +{ + crash(); // Set breakpoint here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/Makefile new file mode 100644 index 00000000000..566938ca0cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py new file mode 100644 index 00000000000..59fb3b6fd39 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py @@ -0,0 +1,128 @@ +""" +Test thread creation after process attach. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CreateAfterAttachTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfFreeBSD # Hangs. May be the same as Linux issue llvm.org/pr16229 but + # not yet investigated. Revisit once required functionality + # is implemented for FreeBSD. + # Occasionally hangs on Windows, may be same as other issues. + @skipIfWindows + @skipIfiOSSimulator + @expectedFailureNetBSD + def test_create_after_attach_with_popen(self): + """Test thread creation after process attach.""" + self.build(dictionary=self.getBuildFlags(use_cpp11=False)) + self.create_after_attach(use_fork=False) + + @skipIfFreeBSD # Hangs. Revisit once required functionality is implemented + # for FreeBSD. + @skipIfRemote + @skipIfWindows # Windows doesn't have fork. + @skipIfiOSSimulator + @expectedFailureNetBSD + def test_create_after_attach_with_fork(self): + """Test thread creation after process attach.""" + self.build(dictionary=self.getBuildFlags(use_cpp11=False)) + self.create_after_attach(use_fork=True) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers for our breakpoints. + self.break_1 = line_number('main.cpp', '// Set first breakpoint here') + self.break_2 = line_number('main.cpp', '// Set second breakpoint here') + self.break_3 = line_number('main.cpp', '// Set third breakpoint here') + + def create_after_attach(self, use_fork): + """Test thread creation after process attach.""" + + exe = self.getBuildArtifact("a.out") + + # Spawn a new process + if use_fork: + pid = self.forkSubprocess(exe) + else: + popen = self.spawnSubprocess(exe) + pid = popen.pid + self.addTearDownHook(self.cleanupSubprocesses) + + # Attach to the spawned process + self.runCmd("process attach -p " + str(pid)) + + target = self.dbg.GetSelectedTarget() + + process = target.GetProcess() + self.assertTrue(process, PROCESS_IS_VALID) + + # This should create a breakpoint in the main thread. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + + # This should create a breakpoint in the second child thread. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) + + # This should create a breakpoint in the first child thread. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_3, num_expected_locations=1) + + # Note: With std::thread, we cannot rely on particular thread numbers. Using + # std::thread may cause the program to spin up a thread pool (and it does on + # Windows), so the thread numbers are non-deterministic. + + # Run to the first breakpoint + self.runCmd("continue") + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + '* thread #', + 'main', + 'stop reason = breakpoint']) + + # Change a variable to escape the loop + self.runCmd("expression main_thread_continue = 1") + + # Run to the second breakpoint + self.runCmd("continue") + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + '* thread #', + 'thread_2_func', + 'stop reason = breakpoint']) + + # Change a variable to escape the loop + self.runCmd("expression child_thread_continue = 1") + + # Run to the third breakpoint + self.runCmd("continue") + + # The stop reason of the thread should be breakpoint. + # Thread 3 may or may not have already exited. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + '* thread #', + 'thread_1_func', + 'stop reason = breakpoint']) + + # Run to completion + self.runCmd("continue") + + # At this point, the inferior process should have exited. + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/main.cpp new file mode 100644 index 00000000000..d8f06e55a2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/main.cpp @@ -0,0 +1,61 @@ +#include <stdio.h> +#include <chrono> +#include <thread> + +using std::chrono::microseconds; + +volatile int g_thread_2_continuing = 0; + +void * +thread_1_func (void *input) +{ + // Waiting to be released by the debugger. + while (!g_thread_2_continuing) // Another thread will change this value + { + std::this_thread::sleep_for(microseconds(1)); + } + + // Return + return NULL; // Set third breakpoint here +} + +void * +thread_2_func (void *input) +{ + // Waiting to be released by the debugger. + int child_thread_continue = 0; + while (!child_thread_continue) // The debugger will change this value + { + std::this_thread::sleep_for(microseconds(1)); // Set second breakpoint here + } + + // Release thread 1 + g_thread_2_continuing = 1; + + // Return + return NULL; +} + +int main(int argc, char const *argv[]) +{ + lldb_enable_attach(); + + // Create a new thread + std::thread thread_1(thread_1_func, nullptr); + + // Waiting to be attached by the debugger. + int main_thread_continue = 0; + while (!main_thread_continue) // The debugger will change this value + { + std::this_thread::sleep_for(microseconds(1)); // Set first breakpoint here + } + + // Create another new thread + std::thread thread_2(thread_2_func, nullptr); + + // Wait for the threads to finish. + thread_1.join(); + thread_2.join(); + + printf("Exiting now\n"); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/Makefile new file mode 100644 index 00000000000..566938ca0cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py new file mode 100644 index 00000000000..fa8c943836f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py @@ -0,0 +1,154 @@ +""" +Test number of threads. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CreateDuringStepTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained, <rdar://problem/28557237>") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + @expectedFailureNetBSD + def test_step_inst(self): + """Test thread creation during step-inst handling.""" + self.build(dictionary=self.getBuildFlags()) + self.create_during_step_base( + "thread step-inst -m all-threads", + 'stop reason = instruction step') + + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained, <rdar://problem/28557237>") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + @expectedFailureNetBSD + def test_step_over(self): + """Test thread creation during step-over handling.""" + self.build(dictionary=self.getBuildFlags()) + self.create_during_step_base( + "thread step-over -m all-threads", + 'stop reason = step over') + + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="<rdar://problem/28574077>") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + @expectedFailureNetBSD + def test_step_in(self): + """Test thread creation during step-in handling.""" + self.build(dictionary=self.getBuildFlags()) + self.create_during_step_base( + "thread step-in -m all-threads", + 'stop reason = step in') + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break and continue. + self.breakpoint = line_number('main.cpp', '// Set breakpoint here') + self.continuepoint = line_number('main.cpp', '// Continue from here') + + def create_during_step_base(self, step_cmd, step_stop_reason): + """Test thread creation while using step-in.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Get the target process + target = self.dbg.GetSelectedTarget() + + # This should create a breakpoint in the stepping thread. + self.bkpt = target.BreakpointCreateByLocation("main.cpp", self.breakpoint) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + process = target.GetProcess() + + # The stop reason of the thread should be breakpoint. + stepping_thread = lldbutil.get_one_thread_stopped_at_breakpoint(process, self.bkpt) + self.assertTrue(stepping_thread.IsValid(), "We stopped at the right breakpoint") + + # Get the number of threads + num_threads = process.GetNumThreads() + + # Make sure we see only two threads + self.assertTrue( + num_threads == 2, + 'Number of expected threads and actual threads do not match.') + + # Get the thread objects + thread1 = process.GetThreadAtIndex(0) + thread2 = process.GetThreadAtIndex(1) + + current_line = self.breakpoint + # Keep stepping until we've reached our designated continue point + while current_line != self.continuepoint: + if stepping_thread != process.GetSelectedThread(): + process.SetSelectedThread(stepping_thread) + + self.runCmd(step_cmd) + + frame = stepping_thread.GetFrameAtIndex(0) + current_line = frame.GetLineEntry().GetLine() + + # Make sure we're still where we thought we were + self.assertTrue( + current_line >= self.breakpoint, + "Stepped to unexpected line, " + + str(current_line)) + self.assertTrue( + current_line <= self.continuepoint, + "Stepped to unexpected line, " + + str(current_line)) + + # Update the number of threads + num_threads = process.GetNumThreads() + + # Check to see that we increased the number of threads as expected + self.assertTrue( + num_threads == 3, + 'Number of expected threads and actual threads do not match after thread exit.') + + stop_reason = stepping_thread.GetStopReason() + self.assertEqual(stop_reason, lldb.eStopReasonPlanComplete, "Stopped for plan completion") + + # Run to completion + self.runCmd("process continue") + + # At this point, the inferior process should have exited. + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/main.cpp new file mode 100644 index 00000000000..d09bdb0ddfc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/main.cpp @@ -0,0 +1,78 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test is intended to create a situation in which one thread will be +// created while the debugger is stepping in another thread. + +#include "pseudo_barrier.h" +#include <thread> + +#define do_nothing() + +pseudo_barrier_t g_barrier; + +volatile int g_thread_created = 0; +volatile int g_test = 0; + +void * +step_thread_func () +{ + g_test = 0; // Set breakpoint here + + while (!g_thread_created) + g_test++; + + // One more time to provide a continue point + g_test++; // Continue from here + + // Return + return NULL; +} + +void * +create_thread_func (void *input) +{ + std::thread *step_thread = (std::thread*)input; + + // Wait until the main thread knows this thread is started. + pseudo_barrier_wait(g_barrier); + + // Wait until the other thread is done. + step_thread->join(); + + // Return + return NULL; +} + +int main () +{ + // Use a simple count to simulate a barrier. + pseudo_barrier_init(g_barrier, 2); + + // Create a thread to hit the breakpoint. + std::thread thread_1(step_thread_func); + + // Wait until the step thread is stepping + while (g_test < 1) + do_nothing(); + + // Create a thread to exit while we're stepping. + std::thread thread_2(create_thread_func, &thread_1); + + // Wait until that thread is started + pseudo_barrier_wait(g_barrier); + + // Let the stepping thread know the other thread is there + g_thread_created = 1; + + // Wait for the threads to finish. + thread_2.join(); + thread_1.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/Makefile new file mode 100644 index 00000000000..566938ca0cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py new file mode 100644 index 00000000000..130abfe8652 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py @@ -0,0 +1,63 @@ +""" +Test number of threads. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExitDuringBreakpointTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number for our breakpoint. + self.breakpoint = line_number('main.cpp', '// Set breakpoint here') + + def test(self): + """Test thread exit during breakpoint handling.""" + self.build(dictionary=self.getBuildFlags()) + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint in the main thread. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + # The exit probably occurred during breakpoint handling, but it isn't + # guaranteed. The main thing we're testing here is that the debugger + # handles this cleanly is some way. + + # Get the number of threads + num_threads = process.GetNumThreads() + + # Make sure we see at least five threads + self.assertTrue( + num_threads >= 5, + 'Number of expected threads and actual threads do not match.') + + # Run to completion + self.runCmd("continue") + + # At this point, the inferior process should have exited. + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/main.cpp new file mode 100644 index 00000000000..ec28678c5d6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/main.cpp @@ -0,0 +1,117 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test is intended to create a situation in which one thread will exit +// while a breakpoint is being handled in another thread. This may not always +// happen because it's possible that the exiting thread will exit before the +// breakpoint is hit. The test case should be flexible enough to treat that +// as success. + +#include "pseudo_barrier.h" +#include <chrono> +#include <thread> + +volatile int g_test = 0; + +// A barrier to synchronize all the threads except the one that will exit. +pseudo_barrier_t g_barrier1; + +// A barrier to synchronize all the threads including the one that will exit. +pseudo_barrier_t g_barrier2; + +// A barrier to keep the first group of threads from exiting until after the +// breakpoint has been passed. +pseudo_barrier_t g_barrier3; + +void * +break_thread_func () +{ + // Wait until the entire first group of threads is running + pseudo_barrier_wait(g_barrier1); + + // Wait for the exiting thread to start + pseudo_barrier_wait(g_barrier2); + + // Do something + g_test++; // Set breakpoint here + + // Synchronize after the breakpoint + pseudo_barrier_wait(g_barrier3); + + // Return + return NULL; +} + +void * +wait_thread_func () +{ + // Wait until the entire first group of threads is running + pseudo_barrier_wait(g_barrier1); + + // Wait for the exiting thread to start + pseudo_barrier_wait(g_barrier2); + + // Wait until the breakpoint has been passed + pseudo_barrier_wait(g_barrier3); + + // Return + return NULL; +} + +void * +exit_thread_func () +{ + // Sync up with the rest of the threads. + pseudo_barrier_wait(g_barrier2); + + // Try to make sure this thread doesn't exit until the breakpoint is hit. + std::this_thread::sleep_for(std::chrono::microseconds(1)); + + // Return + return NULL; +} + +int main () +{ + + // The first barrier waits for the non-exiting threads to start. + // This thread will also participate in that barrier. + // The idea here is to guarantee that the exiting thread will be + // last in the internal list maintained by the debugger. + pseudo_barrier_init(g_barrier1, 5); + + // The second break synchronizes thread execution with the breakpoint. + pseudo_barrier_init(g_barrier2, 5); + + // The third barrier keeps the waiting threads around until the breakpoint + // has been passed. + pseudo_barrier_init(g_barrier3, 4); + + // Create a thread to hit the breakpoint + std::thread thread_1(break_thread_func); + + // Create more threads to slow the debugger down during processing. + std::thread thread_2(wait_thread_func); + std::thread thread_3(wait_thread_func); + std::thread thread_4(wait_thread_func); + + // Wait for all these threads to get started. + pseudo_barrier_wait(g_barrier1); + + // Create a thread to exit during the breakpoint + std::thread thread_5(exit_thread_func); + + // Wait for the threads to finish + thread_5.join(); + thread_4.join(); + thread_3.join(); + thread_2.join(); + thread_1.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/Makefile new file mode 100644 index 00000000000..ebecfbf9241 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/Makefile @@ -0,0 +1,3 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py new file mode 100644 index 00000000000..d35bd45fe80 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py @@ -0,0 +1,150 @@ +""" +Test number of threads. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ExitDuringStepTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfFreeBSD # llvm.org/pr21411: test is hanging + @skipIfWindows # This is flakey on Windows: llvm.org/pr38373 + def test(self): + """Test thread exit during step handling.""" + self.build(dictionary=self.getBuildFlags()) + self.exit_during_step_base( + "thread step-inst -m all-threads", + 'stop reason = instruction step', + True) + + @skipIfFreeBSD # llvm.org/pr21411: test is hanging + @skipIfWindows # This is flakey on Windows: llvm.org/pr38373 + def test_step_over(self): + """Test thread exit during step-over handling.""" + self.build(dictionary=self.getBuildFlags()) + self.exit_during_step_base( + "thread step-over -m all-threads", + 'stop reason = step over', + False) + + @skipIfFreeBSD # llvm.org/pr21411: test is hanging + @skipIfWindows # This is flakey on Windows: llvm.org/pr38373 + def test_step_in(self): + """Test thread exit during step-in handling.""" + self.build(dictionary=self.getBuildFlags()) + self.exit_during_step_base( + "thread step-in -m all-threads", + 'stop reason = step in', + False) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break and continue. + self.breakpoint = line_number('main.cpp', '// Set breakpoint here') + self.continuepoint = line_number('main.cpp', '// Continue from here') + + def exit_during_step_base(self, step_cmd, step_stop_reason, by_instruction): + """Test thread exit during step handling.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint in the main thread. + self.bp_num = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) + + # The breakpoint list should show 1 location. + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.breakpoint]) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + num_threads = process.GetNumThreads() + # Make sure we see all three threads + self.assertGreaterEqual( + num_threads, + 3, + 'Number of expected threads and actual threads do not match.') + + stepping_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, self.bp_num) + self.assertIsNotNone( + stepping_thread, + "Could not find a thread stopped at the breakpoint") + + current_line = self.breakpoint + stepping_frame = stepping_thread.GetFrameAtIndex(0) + self.assertEqual( + current_line, + stepping_frame.GetLineEntry().GetLine(), + "Starting line for stepping doesn't match breakpoint line.") + + # Keep stepping until we've reached our designated continue point + while current_line != self.continuepoint: + # Since we're using the command interpreter to issue the thread command + # (on the selected thread) we need to ensure the selected thread is the + # stepping thread. + if stepping_thread != process.GetSelectedThread(): + process.SetSelectedThread(stepping_thread) + + self.runCmd(step_cmd) + + frame = stepping_thread.GetFrameAtIndex(0) + + current_line = frame.GetLineEntry().GetLine() + + if by_instruction and current_line == 0: + continue + + self.assertGreaterEqual( + current_line, + self.breakpoint, + "Stepped to unexpected line, " + + str(current_line)) + self.assertLessEqual( + current_line, + self.continuepoint, + "Stepped to unexpected line, " + + str(current_line)) + + self.runCmd("thread list") + + # Update the number of threads + new_num_threads = process.GetNumThreads() + + # Check to see that we reduced the number of threads as expected + self.assertEqual( + new_num_threads, + num_threads - 1, + 'Number of threads did not reduce by 1 after thread exit.') + + self.expect("thread list", 'Process state is stopped due to step', + substrs=['stopped', + step_stop_reason]) + + # Run to completion + self.runCmd("continue") + + # At this point, the inferior process should have exited. + self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/main.cpp new file mode 100644 index 00000000000..0e2ae00576c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/main.cpp @@ -0,0 +1,77 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test is intended to create a situation in which one thread will exit +// while the debugger is stepping in another thread. + +#include "pseudo_barrier.h" +#include <thread> + +#define do_nothing() + +// A barrier to synchronize thread start. +pseudo_barrier_t g_barrier; + +volatile int g_thread_exited = 0; + +volatile int g_test = 0; + +void * +step_thread_func () +{ + // Wait until both threads are started. + pseudo_barrier_wait(g_barrier); + + g_test = 0; // Set breakpoint here + + while (!g_thread_exited) + g_test++; + + // One more time to provide a continue point + g_test++; // Continue from here + + // Return + return NULL; +} + +void * +exit_thread_func () +{ + // Wait until both threads are started. + pseudo_barrier_wait(g_barrier); + + // Wait until the other thread is stepping. + while (g_test == 0) + do_nothing(); + + // Return + return NULL; +} + +int main () +{ + // Synchronize thread start so that doesn't happen during stepping. + pseudo_barrier_init(g_barrier, 2); + + // Create a thread to hit the breakpoint. + std::thread thread_1(step_thread_func); + + // Create a thread to exit while we're stepping. + std::thread thread_2(exit_thread_func); + + // Wait for the exit thread to finish. + thread_2.join(); + + // Let the stepping thread know the other thread is gone. + g_thread_exited = 1; + + // Wait for the stepping thread to finish. + thread_1.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/Makefile new file mode 100644 index 00000000000..6e962b97209 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/Makefile @@ -0,0 +1,3 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp other.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py new file mode 100644 index 00000000000..2035435442f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py @@ -0,0 +1,78 @@ +""" +Test jumping to different places. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ThreadJumpTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test(self): + """Test thread jump handling.""" + self.build(dictionary=self.getBuildFlags()) + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Find the line numbers for our breakpoints. + self.mark1 = line_number('main.cpp', '// 1st marker') + self.mark2 = line_number('main.cpp', '// 2nd marker') + self.mark3 = line_number('main.cpp', '// 3rd marker') + self.mark4 = line_number('main.cpp', '// 4th marker') + self.mark5 = line_number('other.cpp', '// other marker') + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.mark3, num_expected_locations=1) + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint 1. + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT + " 1", + substrs=[ + 'stopped', + 'main.cpp:{}'.format( + self.mark3), + 'stop reason = breakpoint 1']) + + # Try the int path, force it to return 'a' + self.do_min_test(self.mark3, self.mark1, "i", "4") + # Try the int path, force it to return 'b' + self.do_min_test(self.mark3, self.mark2, "i", "5") + # Try the double path, force it to return 'a' + self.do_min_test(self.mark4, self.mark1, "j", "7") + # Expected to fail on powerpc64le architecture + if not self.isPPC64le(): + # Try the double path, force it to return 'b' + self.do_min_test(self.mark4, self.mark2, "j", "8") + + # Try jumping to another function in a different file. + self.runCmd( + "thread jump --file other.cpp --line %i --force" % + self.mark5) + self.expect("process status", + substrs=["at other.cpp:%i" % self.mark5]) + + # Try jumping to another function (without forcing) + self.expect( + "j main.cpp:%i" % + self.mark1, + COMMAND_FAILED_AS_EXPECTED, + error=True, + substrs=["error"]) + + def do_min_test(self, start, jump, var, value): + # jump to the start marker + self.runCmd("j %i" % start) + self.runCmd("thread step-in") # step into the min fn + # jump to the branch we're interested in + self.runCmd("j %i" % jump) + self.runCmd("thread step-out") # return out + self.runCmd("thread step-over") # assign to the global + self.expect("expr %s" % var, substrs=[value]) # check it diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/main.cpp new file mode 100644 index 00000000000..e0580bd2542 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/main.cpp @@ -0,0 +1,34 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test verifies the correct handling of program counter jumps. + +int otherfn(); + +template<typename T> +T min(T a, T b) +{ + if (a < b) + { + return a; // 1st marker + } else { + return b; // 2nd marker + } +} + +int main () +{ + int i; + double j; + int min_i_a = 4, min_i_b = 5; + double min_j_a = 7.0, min_j_b = 8.0; + i = min(min_i_a, min_i_b); // 3rd marker + j = min(min_j_a, min_j_b); // 4th marker + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/other.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/other.cpp new file mode 100644 index 00000000000..3ce9ad6548b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/jump/other.cpp @@ -0,0 +1,12 @@ +//===-- other.cpp -----------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int otherfn() +{ + return 4; // other marker +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/Makefile new file mode 100644 index 00000000000..566938ca0cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py new file mode 100644 index 00000000000..20645fbc63e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py @@ -0,0 +1,90 @@ +""" +Test number of threads. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class MultipleBreakpointTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number for our breakpoint. + self.breakpoint = line_number('main.cpp', '// Set breakpoint here') + + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr15824 thread states not properly maintained and <rdar://problem/28557237>") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @skipIfWindows # This is flakey on Windows: llvm.org/pr24668, llvm.org/pr38373 + @expectedFailureNetBSD + def test(self): + """Test simultaneous breakpoints in multiple threads.""" + self.build(dictionary=self.getBuildFlags()) + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint in the main thread. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.breakpoint, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + # The breakpoint may be hit in either thread 2 or thread 3. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + # Get the number of threads + num_threads = process.GetNumThreads() + + # Make sure we see all three threads + self.assertTrue( + num_threads >= 3, + 'Number of expected threads and actual threads do not match.') + + # Get the thread objects + thread1 = process.GetThreadAtIndex(0) + thread2 = process.GetThreadAtIndex(1) + thread3 = process.GetThreadAtIndex(2) + + # Make sure both threads are stopped + self.assertTrue( + thread1.IsStopped(), + "Primary thread didn't stop during breakpoint") + self.assertTrue( + thread2.IsStopped(), + "Secondary thread didn't stop during breakpoint") + self.assertTrue( + thread3.IsStopped(), + "Tertiary thread didn't stop during breakpoint") + + # Delete the first breakpoint then continue + self.runCmd("breakpoint delete 1") + + # Run to completion + self.runCmd("continue") + + # At this point, the inferior process should have exited. + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/main.cpp new file mode 100644 index 00000000000..5f884d75866 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/multi_break/main.cpp @@ -0,0 +1,48 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test is intended to create a situation in which a breakpoint will be +// hit in two threads at nearly the same moment. The expected result is that +// the breakpoint in the second thread will be hit while the breakpoint handler +// in the first thread is trying to stop all threads. + +#include "pseudo_barrier.h" +#include <thread> + +pseudo_barrier_t g_barrier; + +volatile int g_test = 0; + +void * +thread_func () +{ + // Wait until both threads are running + pseudo_barrier_wait(g_barrier); + + // Do something + g_test++; // Set breakpoint here + + // Return + return NULL; +} + +int main () +{ + // Don't let either thread do anything until they're both ready. + pseudo_barrier_init(g_barrier, 2); + + // Create two threads + std::thread thread_1(thread_func); + std::thread thread_2(thread_func); + + // Wait for the threads to finish + thread_1.join(); + thread_2.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/num_threads/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/num_threads/Makefile new file mode 100644 index 00000000000..566938ca0cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/num_threads/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/num_threads/TestNumThreads.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/num_threads/TestNumThreads.py new file mode 100644 index 00000000000..cfd2941ad19 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/num_threads/TestNumThreads.py @@ -0,0 +1,123 @@ +""" +Test number of threads. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class NumberOfThreadsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers for our break points. + self.thread3_notify_all_line = line_number('main.cpp', '// Set thread3 break point on notify_all at this line.') + self.thread3_before_lock_line = line_number('main.cpp', '// thread3-before-lock') + + def test_number_of_threads(self): + """Test number of threads.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint with 1 location. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.thread3_notify_all_line, num_expected_locations=1) + + # The breakpoint list should show 1 location. + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.thread3_notify_all_line]) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Stopped once. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."]) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + # Get the number of threads + num_threads = process.GetNumThreads() + + # Using std::thread may involve extra threads, so we assert that there are + # at least 4 rather than exactly 4. + self.assertTrue( + num_threads >= 13, + 'Number of expected threads and actual threads do not match.') + + @skipIfDarwin # rdar://33462362 + @skipIfWindows # This is flakey on Windows: llvm.org/pr37658, llvm.org/pr38373 + @expectedFailureNetBSD + def test_unique_stacks(self): + """Test backtrace unique with multiple threads executing the same stack.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Set a break point on the thread3 notify all (should get hit on threads 4-13). + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.thread3_before_lock_line, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Stopped once. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint 1."]) + + process = self.process() + + # Get the number of threads + num_threads = process.GetNumThreads() + + # Using std::thread may involve extra threads, so we assert that there are + # at least 10 thread3's rather than exactly 10. + self.assertTrue( + num_threads >= 10, + 'Number of expected threads and actual threads do not match.') + + # Attempt to walk each of the thread's executing the thread3 function to + # the same breakpoint. + def is_thread3(thread): + for frame in thread: + if "thread3" in frame.GetFunctionName(): return True + return False + + expect_threads = "" + for i in range(num_threads): + thread = process.GetThreadAtIndex(i) + self.assertTrue(thread.IsValid()) + if not is_thread3(thread): + continue + + # If we aren't stopped out the thread breakpoint try to resume. + if thread.GetStopReason() != lldb.eStopReasonBreakpoint: + self.runCmd("thread continue %d"%(i+1)) + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonBreakpoint) + + expect_threads += " #%d"%(i+1) + + # Construct our expected back trace string + expect_string = "10 thread(s)%s" % (expect_threads) + + # Now that we are stopped, we should have 10 threads waiting in the + # thread3 function. All of these threads should show as one stack. + self.expect("thread backtrace unique", + "Backtrace with unique stack shown correctly", + substrs=[expect_string, + "main.cpp:%d"%self.thread3_before_lock_line]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/num_threads/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/num_threads/main.cpp new file mode 100644 index 00000000000..fdc060d135d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/num_threads/main.cpp @@ -0,0 +1,65 @@ +#include "pseudo_barrier.h" +#include <condition_variable> +#include <mutex> +#include <thread> +#include <vector> + +std::mutex mutex; +std::condition_variable cond; +pseudo_barrier_t thread3_barrier; + +void * +thread3(void *input) +{ + pseudo_barrier_wait(thread3_barrier); + + int dummy = 47; // thread3-before-lock + + std::unique_lock<std::mutex> lock(mutex); + cond.notify_all(); // Set thread3 break point on notify_all at this line. + return NULL; +} + +void * +thread2(void *input) +{ + std::unique_lock<std::mutex> lock(mutex); + cond.notify_all(); // release main thread + cond.wait(lock); + return NULL; +} + +void * +thread1(void *input) +{ + std::thread thread_2(thread2, nullptr); + thread_2.join(); + + return NULL; +} + +int main() +{ + std::unique_lock<std::mutex> lock(mutex); + + std::thread thread_1(thread1, nullptr); + cond.wait(lock); // wait for thread2 + + pseudo_barrier_init(thread3_barrier, 10); + + std::vector<std::thread> thread_3s; + for (int i = 0; i < 10; i++) { + thread_3s.push_back(std::thread(thread3, nullptr)); + } + + cond.wait(lock); // wait for thread_3s + + lock.unlock(); + + thread_1.join(); + for (auto &t : thread_3s){ + t.join(); + } + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/Makefile new file mode 100644 index 00000000000..3d0b98f13f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/Makefile @@ -0,0 +1,2 @@ +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py new file mode 100644 index 00000000000..60938088c9a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py @@ -0,0 +1,326 @@ +""" +Test thread states. +""" + + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ThreadStateTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr15824 thread states not properly maintained") + @skipIfDarwin # llvm.org/pr15824 thread states not properly maintained and <rdar://problem/28557237> + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18190 thread states not properly maintained") + @expectedFailureNetBSD + def test_state_after_breakpoint(self): + """Test thread state after breakpoint.""" + self.build(dictionary=self.getBuildFlags(use_cpp11=False)) + self.thread_state_after_breakpoint_test() + + @skipIfDarwin # 'llvm.org/pr23669', cause Python crash randomly + @expectedFailureAll( + oslist=lldbplatformutil.getDarwinOSTriples(), + bugnumber="llvm.org/pr23669") + @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr15824") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24660") + def test_state_after_continue(self): + """Test thread state after continue.""" + self.build(dictionary=self.getBuildFlags(use_cpp11=False)) + self.thread_state_after_continue_test() + + @skipIfDarwin # 'llvm.org/pr23669', cause Python crash randomly + @expectedFailureDarwin('llvm.org/pr23669') + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24660") + @expectedFailureNetBSD + # thread states not properly maintained + @unittest2.expectedFailure("llvm.org/pr16712") + def test_state_after_expression(self): + """Test thread state after expression.""" + self.build(dictionary=self.getBuildFlags(use_cpp11=False)) + self.thread_state_after_expression_test() + + # thread states not properly maintained + @unittest2.expectedFailure("llvm.org/pr15824 and <rdar://problem/28557237>") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + @skipIfDarwin # llvm.org/pr15824 thread states not properly maintained and <rdar://problem/28557237> + @expectedFailureNetBSD + def test_process_state(self): + """Test thread states (comprehensive).""" + self.build(dictionary=self.getBuildFlags(use_cpp11=False)) + self.thread_states_test() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers for our breakpoints. + self.break_1 = line_number('main.cpp', '// Set first breakpoint here') + self.break_2 = line_number('main.cpp', '// Set second breakpoint here') + + def thread_state_after_breakpoint_test(self): + """Test thread state after breakpoint.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint in the main thread. + bp = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # Make sure the thread is in the stopped state. + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' during breakpoint 1.") + self.assertFalse(thread.IsSuspended(), + "Thread state is \'suspended\' during breakpoint 1.") + + # Kill the process + self.runCmd("process kill") + + def wait_for_running_event(self, process): + listener = self.dbg.GetListener() + if lldb.remote_platform: + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateConnected]) + lldbutil.expect_state_changes( + self, listener, process, [ + lldb.eStateRunning]) + + def thread_state_after_continue_test(self): + """Test thread state after continue.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint in the main thread. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # Continue, the inferior will go into an infinite loop waiting for + # 'g_test' to change. + self.dbg.SetAsync(True) + self.runCmd("continue") + self.wait_for_running_event(process) + + # Check the thread state. It should be running. + self.assertFalse( + thread.IsStopped(), + "Thread state is \'stopped\' when it should be running.") + self.assertFalse( + thread.IsSuspended(), + "Thread state is \'suspended\' when it should be running.") + + # Go back to synchronous interactions + self.dbg.SetAsync(False) + + # Kill the process + self.runCmd("process kill") + + def thread_state_after_expression_test(self): + """Test thread state after expression.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint in the main thread. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # Get the inferior out of its loop + self.runCmd("expression g_test = 1") + + # Check the thread state + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' after expression evaluation.") + self.assertFalse( + thread.IsSuspended(), + "Thread state is \'suspended\' after expression evaluation.") + + # Let the process run to completion + self.runCmd("process continue") + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24668: Breakpoints not resolved correctly") + @skipIfDarwin # llvm.org/pr15824 thread states not properly maintained and <rdar://problem/28557237> + @no_debug_info_test + def test_process_interrupt(self): + """Test process interrupt and continue.""" + self.build(dictionary=self.getBuildFlags(use_cpp11=False)) + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint in the main thread. + bpno = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # Remove the breakpoint to avoid the single-step-over-bkpt dance in the + # "continue" below + self.assertTrue(target.BreakpointDelete(bpno)) + + # Continue, the inferior will go into an infinite loop waiting for + # 'g_test' to change. + self.dbg.SetAsync(True) + self.runCmd("continue") + self.wait_for_running_event(process) + + # Go back to synchronous interactions + self.dbg.SetAsync(False) + + # Stop the process + self.runCmd("process interrupt") + + self.assertEqual(thread.GetStopReason(), lldb.eStopReasonSignal) + + # Get the inferior out of its loop + self.runCmd("expression g_test = 1") + + # Run to completion + self.runCmd("continue") + + def thread_states_test(self): + """Test thread states (comprehensive).""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint in the main thread. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # Make sure the thread is in the stopped state. + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' during breakpoint 1.") + self.assertFalse(thread.IsSuspended(), + "Thread state is \'suspended\' during breakpoint 1.") + + # Continue, the inferior will go into an infinite loop waiting for + # 'g_test' to change. + self.dbg.SetAsync(True) + self.runCmd("continue") + self.wait_for_running_event(process) + + # Check the thread state. It should be running. + self.assertFalse( + thread.IsStopped(), + "Thread state is \'stopped\' when it should be running.") + self.assertFalse( + thread.IsSuspended(), + "Thread state is \'suspended\' when it should be running.") + + # Go back to synchronous interactions + self.dbg.SetAsync(False) + + # Stop the process + self.runCmd("process interrupt") + + self.assertEqual(thread.GetState(), lldb.eStopReasonSignal) + + # Check the thread state + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' after process stop.") + self.assertFalse(thread.IsSuspended(), + "Thread state is \'suspended\' after process stop.") + + # Get the inferior out of its loop + self.runCmd("expression g_test = 1") + + # Check the thread state + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' after expression evaluation.") + self.assertFalse( + thread.IsSuspended(), + "Thread state is \'suspended\' after expression evaluation.") + + self.assertEqual(thread.GetState(), lldb.eStopReasonSignal) + + # Run to breakpoint 2 + self.runCmd("continue") + + self.assertEqual(thread.GetState(), lldb.eStopReasonBreakpoint) + + # Make sure both threads are stopped + self.assertTrue( + thread.IsStopped(), + "Thread state isn't \'stopped\' during breakpoint 2.") + self.assertFalse(thread.IsSuspended(), + "Thread state is \'suspended\' during breakpoint 2.") + + # Run to completion + self.runCmd("continue") + + # At this point, the inferior process should have exited. + self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/main.cpp new file mode 100644 index 00000000000..63b50494bd0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/state/main.cpp @@ -0,0 +1,44 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test is intended to verify that thread states are properly maintained +// when transitional actions are performed in the debugger. Most of the logic +// is in the test script. This program merely provides places where the test +// can create the intended states. + +#include <chrono> +#include <thread> + +volatile int g_test = 0; + +int addSomething(int a) +{ + return a + g_test; +} + +int doNothing() +{ + int temp = 0; // Set first breakpoint here + + while (!g_test && temp < 5) + { + ++temp; + std::this_thread::sleep_for(std::chrono::seconds(2)); + } + + return temp; // Set second breakpoint here +} + +int main () +{ + int result = doNothing(); + + int i = addSomething(result); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/Makefile new file mode 100644 index 00000000000..c46619c6623 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py new file mode 100644 index 00000000000..2d9632eb2dd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py @@ -0,0 +1,156 @@ +""" +Test stepping out from a function in a multi-threaded program. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ThreadStepOutTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # Test occasionally times out on the Linux build bot + @skipIfLinux + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23477 Test occasionally times out on the Linux build bot") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr18066 inferior does not exit") + @skipIfWindows # This test will hang on windows llvm.org/pr21753 + @expectedFailureAll(oslist=["windows"]) + @expectedFailureNetBSD + def test_step_single_thread(self): + """Test thread step out on one thread via command interpreter. """ + self.build(dictionary=self.getBuildFlags()) + self.step_out_test(self.step_out_single_thread_with_cmd) + + # Test occasionally times out on the Linux build bot + @skipIfLinux + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23477 Test occasionally times out on the Linux build bot") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr19347 2nd thread stops at breakpoint") + @skipIfWindows # This test will hang on windows llvm.org/pr21753 + @expectedFailureAll(oslist=["windows"]) + @expectedFailureAll(oslist=["watchos"], archs=['armv7k'], bugnumber="rdar://problem/34674488") # stop reason is trace when it should be step-out + @expectedFailureNetBSD + def test_step_all_threads(self): + """Test thread step out on all threads via command interpreter. """ + self.build(dictionary=self.getBuildFlags()) + self.step_out_test(self.step_out_all_threads_with_cmd) + + # Test occasionally times out on the Linux build bot + @skipIfLinux + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23477 Test occasionally times out on the Linux build bot") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr19347 2nd thread stops at breakpoint") + @skipIfWindows # This test will hang on windows llvm.org/pr21753 + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24681") + @expectedFailureNetBSD + def test_python(self): + """Test thread step out on one thread via Python API (dwarf).""" + self.build(dictionary=self.getBuildFlags()) + self.step_out_test(self.step_out_with_python) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number for our breakpoint. + self.bkpt_string = '// Set breakpoint here' + self.breakpoint = line_number('main.cpp', self.bkpt_string) + + if "gcc" in self.getCompiler() or self.isIntelCompiler() or self.getArchitecture() in ['arm64', 'arm64e']: + self.step_out_destination = line_number( + 'main.cpp', '// Expect to stop here after step-out (icc and gcc; arm64)') + else: + self.step_out_destination = line_number( + 'main.cpp', '// Expect to stop here after step-out (clang)') + + def step_out_single_thread_with_cmd(self): + self.step_out_with_cmd("this-thread") + self.expect( + "thread backtrace all", + "Thread location after step out is correct", + substrs=[ + "main.cpp:%d" % + self.step_out_destination, + "main.cpp:%d" % + self.breakpoint]) + + def step_out_all_threads_with_cmd(self): + self.step_out_with_cmd("all-threads") + self.expect( + "thread backtrace all", + "Thread location after step out is correct", + substrs=[ + "main.cpp:%d" % + self.step_out_destination]) + + def step_out_with_cmd(self, run_mode): + self.runCmd("thread select %d" % self.step_out_thread.GetIndexID()) + self.runCmd("thread step-out -m %s" % run_mode) + self.expect("process status", "Expected stop reason to be step-out", + substrs=["stop reason = step out"]) + + self.expect( + "thread list", + "Selected thread did not change during step-out", + substrs=[ + "* thread #%d" % + self.step_out_thread.GetIndexID()]) + + def step_out_with_python(self): + self.step_out_thread.StepOut() + + reason = self.step_out_thread.GetStopReason() + self.assertEqual( + lldb.eStopReasonPlanComplete, + reason, + "Expected thread stop reason 'plancomplete', but got '%s'" % + lldbutil.stop_reason_to_str(reason)) + + # Verify location after stepping out + frame = self.step_out_thread.GetFrameAtIndex(0) + desc = lldbutil.get_description(frame.GetLineEntry()) + expect = "main.cpp:%d" % self.step_out_destination + self.assertTrue( + expect in desc, "Expected %s but thread stopped at %s" % + (expect, desc)) + + def step_out_test(self, step_out_func): + """Test single thread step out of a function.""" + (self.inferior_target, self.inferior_process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, self.bkpt_string, lldb.SBFileSpec('main.cpp'), only_one_thread = False) + + # We hit the breakpoint on at least one thread. If we hit it on both threads + # simultaneously, we can try the step out. Otherwise, suspend the thread + # that hit the breakpoint, and continue till the second thread hits + # the breakpoint: + + (breakpoint_threads, other_threads) = ([], []) + lldbutil.sort_stopped_threads(self.inferior_process, + breakpoint_threads=breakpoint_threads, + other_threads=other_threads) + if len(breakpoint_threads) == 1: + success = thread.Suspend() + self.assertTrue(success, "Couldn't suspend a thread") + bkpt_threads = lldbutil.continue_to_breakpoint(bkpt) + self.assertEqual(len(bkpt_threads), 1, "Second thread stopped") + success = thread.Resume() + self.assertTrue(success, "Couldn't resume a thread") + + self.step_out_thread = breakpoint_threads[0] + + # Step out of thread stopped at breakpoint + step_out_func() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/main.cpp new file mode 100644 index 00000000000..e7754d0ac74 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_out/main.cpp @@ -0,0 +1,50 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test is intended to create a situation in which two threads are stopped +// at a breakpoint and the debugger issues a step-out command. + +#include "pseudo_barrier.h" +#include <thread> + +pseudo_barrier_t g_barrier; + +volatile int g_test = 0; + +void step_out_of_here() { + g_test += 5; // Set breakpoint here +} + +void * +thread_func () +{ + // Wait until both threads are running + pseudo_barrier_wait(g_barrier); + + // Do something + step_out_of_here(); // Expect to stop here after step-out (clang) + + // Return + return NULL; // Expect to stop here after step-out (icc and gcc; arm64) +} + +int main () +{ + // Don't let either thread do anything until they're both ready. + pseudo_barrier_init(g_barrier, 2); + + // Create two threads + std::thread thread_1(thread_func); + std::thread thread_2(thread_func); + + // Wait for the threads to finish + thread_1.join(); + thread_2.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/.categories new file mode 100644 index 00000000000..c00c25822e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/.categories @@ -0,0 +1 @@ +basic_process diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/TestStepUntil.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/TestStepUntil.py new file mode 100644 index 00000000000..dd48ebaf8e1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/TestStepUntil.py @@ -0,0 +1,86 @@ +"""Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StepUntilTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers that we will step to in main: + self.main_source = "main.c" + self.less_than_two = line_number('main.c', 'Less than 2') + self.greater_than_two = line_number('main.c', 'Greater than or equal to 2.') + self.back_out_in_main = line_number('main.c', 'Back out in main') + + def do_until (self, args, until_lines, expected_linenum): + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + main_source_spec = lldb.SBFileSpec(self.main_source) + break_before = target.BreakpointCreateBySourceRegex( + 'At the start', + main_source_spec) + self.assertTrue(break_before, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + args, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_before) + + if len(threads) != 1: + self.fail("Failed to stop at first breakpoint in main.") + + thread = threads[0] + return thread + + thread = self.common_setup(None) + + cmd_interp = self.dbg.GetCommandInterpreter() + ret_obj = lldb.SBCommandReturnObject() + + cmd_line = "thread until" + for line_num in until_lines: + cmd_line += " %d"%(line_num) + + cmd_interp.HandleCommand(cmd_line, ret_obj) + self.assertTrue(ret_obj.Succeeded(), "'%s' failed: %s."%(cmd_line, ret_obj.GetError())) + + frame = thread.frames[0] + line = frame.GetLineEntry().GetLine() + self.assertEqual(line, expected_linenum, 'Did not get the expected stop line number') + + def test_hitting_one (self): + """Test thread step until - targeting one line and hitting it.""" + self.do_until(None, [self.less_than_two], self.less_than_two) + + def test_targetting_two_hitting_first (self): + """Test thread step until - targeting two lines and hitting one.""" + self.do_until(["foo", "bar", "baz"], [self.less_than_two, self.greater_than_two], self.greater_than_two) + + def test_targetting_two_hitting_second (self): + """Test thread step until - targeting two lines and hitting the other one.""" + self.do_until(None, [self.less_than_two, self.greater_than_two], self.less_than_two) + + def test_missing_one (self): + """Test thread step until - targeting one line and missing it.""" + self.do_until(["foo", "bar", "baz"], [self.less_than_two], self.back_out_in_main) + + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/main.c new file mode 100644 index 00000000000..e0b4d8ab951 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/step_until/main.c @@ -0,0 +1,20 @@ +#include <stdio.h> + +void call_me(int argc) +{ + printf ("At the start, argc: %d.\n", argc); + + if (argc < 2) + printf("Less than 2.\n"); + else + printf("Greater than or equal to 2.\n"); +} + +int +main(int argc, char **argv) +{ + call_me(argc); + printf("Back out in main.\n"); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/Makefile new file mode 100644 index 00000000000..ebecfbf9241 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/Makefile @@ -0,0 +1,3 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py new file mode 100644 index 00000000000..6bd55e1753f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py @@ -0,0 +1,121 @@ +""" +Test number of threads. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class ThreadExitTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers for our breakpoints. + self.break_1 = line_number('main.cpp', '// Set first breakpoint here') + self.break_2 = line_number('main.cpp', '// Set second breakpoint here') + self.break_3 = line_number('main.cpp', '// Set third breakpoint here') + self.break_4 = line_number('main.cpp', '// Set fourth breakpoint here') + + @skipIfWindows # This is flakey on Windows: llvm.org/pr38373 + def test(self): + """Test thread exit handling.""" + self.build(dictionary=self.getBuildFlags()) + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # This should create a breakpoint with 1 location. + bp1_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_1, num_expected_locations=1) + bp2_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_2, num_expected_locations=1) + bp3_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_3, num_expected_locations=1) + bp4_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.break_4, num_expected_locations=1) + + # The breakpoint list should show 1 locations. + self.expect( + "breakpoint list -f", + "Breakpoint location shown correctly", + substrs=[ + "1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.break_1, + "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.break_2, + "3: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.break_3, + "4: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % + self.break_4]) + + # Run the program. + self.runCmd("run", RUN_SUCCEEDED) + # Get the target process + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, bp1_id) + self.assertIsNotNone(stopped_thread, + "Process is not stopped at breakpoint 1") + + # Get the number of threads + num_threads = process.GetNumThreads() + self.assertGreaterEqual( + num_threads, + 2, + 'Number of expected threads and actual threads do not match at breakpoint 1.') + + # Run to the second breakpoint + self.runCmd("continue") + stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, bp2_id) + self.assertIsNotNone(stopped_thread, + "Process is not stopped at breakpoint 2") + + # Update the number of threads + new_num_threads = process.GetNumThreads() + self.assertEqual( + new_num_threads, + num_threads + 1, + 'Number of expected threads did not increase by 1 at bp 2.') + + # Run to the third breakpoint + self.runCmd("continue") + stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, bp3_id) + self.assertIsNotNone(stopped_thread, + "Process is not stopped at breakpoint 3") + + # Update the number of threads + new_num_threads = process.GetNumThreads() + self.assertEqual( + new_num_threads, + num_threads, + 'Number of expected threads is not equal to original number of threads at bp 3.') + + # Run to the fourth breakpoint + self.runCmd("continue") + stopped_thread = lldbutil.get_one_thread_stopped_at_breakpoint_id( + process, bp4_id) + self.assertIsNotNone(stopped_thread, + "Process is not stopped at breakpoint 4") + + # Update the number of threads + new_num_threads = process.GetNumThreads() + self.assertEqual( + new_num_threads, + num_threads - 1, + 'Number of expected threads did not decrease by 1 at bp 4.') + + # Run to completion + self.runCmd("continue") + + # At this point, the inferior process should have exited. + self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/main.cpp new file mode 100644 index 00000000000..7510dd3a7ff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/main.cpp @@ -0,0 +1,73 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This test verifies the correct handling of child thread exits. + +#include "pseudo_barrier.h" +#include <thread> + +pseudo_barrier_t g_barrier1; +pseudo_barrier_t g_barrier2; +pseudo_barrier_t g_barrier3; + +void * +thread1 () +{ + // Synchronize with the main thread. + pseudo_barrier_wait(g_barrier1); + + // Synchronize with the main thread and thread2. + pseudo_barrier_wait(g_barrier2); + + // Return + return NULL; // Set second breakpoint here +} + +void * +thread2 () +{ + // Synchronize with thread1 and the main thread. + pseudo_barrier_wait(g_barrier2); + + // Synchronize with the main thread. + pseudo_barrier_wait(g_barrier3); + + // Return + return NULL; +} + +int main () +{ + pseudo_barrier_init(g_barrier1, 2); + pseudo_barrier_init(g_barrier2, 3); + pseudo_barrier_init(g_barrier3, 2); + + // Create a thread. + std::thread thread_1(thread1); + + // Wait for thread1 to start. + pseudo_barrier_wait(g_barrier1); + + // Create another thread. + std::thread thread_2(thread2); // Set first breakpoint here + + // Wait for thread2 to start. + pseudo_barrier_wait(g_barrier2); + + // Wait for the first thread to finish + thread_1.join(); + + // Synchronize with the remaining thread + int dummy = 47; // Set third breakpoint here + pseudo_barrier_wait(g_barrier3); + + // Wait for the second thread to finish + thread_2.join(); + + return 0; // Set fourth breakpoint here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/Makefile new file mode 100644 index 00000000000..c46619c6623 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py new file mode 100644 index 00000000000..e5505e1943c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py @@ -0,0 +1,71 @@ +""" +Test that we obey thread conditioned breakpoints. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +def set_thread_id(thread, breakpoint): + id = thread.id + breakpoint.SetThreadID(id) + +def set_thread_name(thread, breakpoint): + breakpoint.SetThreadName("main-thread") + +class ThreadSpecificBreakTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + + @expectedFailureAll(oslist=['ios', 'watchos', 'tvos', 'bridgeos'], archs=['armv7', 'armv7k'], bugnumber='rdar://problem/34563920') # armv7 ios problem - breakpoint with tid qualifier isn't working + def test_thread_id(self): + self.do_test(set_thread_id) + + @skipUnlessDarwin + @expectedFailureAll(oslist=['ios', 'watchos', 'tvos', 'bridgeos'], archs=['armv7', 'armv7k'], bugnumber='rdar://problem/34563920') # armv7 ios problem - breakpoint with tid qualifier isn't working + def test_thread_name(self): + self.do_test(set_thread_name) + + def do_test(self, setter_method): + """Test that we obey thread conditioned breakpoints.""" + self.build() + main_source_spec = lldb.SBFileSpec("main.cpp") + (target, process, main_thread, main_breakpoint) = lldbutil.run_to_source_breakpoint(self, + "Set main breakpoint here", main_source_spec) + + thread_breakpoint = target.BreakpointCreateBySourceRegex( + "Set thread-specific breakpoint here", main_source_spec) + self.assertGreater( + thread_breakpoint.GetNumLocations(), + 0, + "thread breakpoint has no locations associated with it.") + + # Set the thread-specific breakpoint to stop only on the main thread + # before the secondary thread has a chance to execute it. The main + # thread joins the secondary thread, and then the main thread will + # execute the code at the breakpoint. If the thread-specific + # breakpoint works, the next stop will be on the main thread. + setter_method(main_thread, thread_breakpoint) + + process.Continue() + next_stop_state = process.GetState() + self.assertEqual( + next_stop_state, + lldb.eStateStopped, + "We should have stopped at the thread breakpoint.") + stopped_threads = lldbutil.get_threads_stopped_at_breakpoint( + process, thread_breakpoint) + self.assertEqual( + len(stopped_threads), + 1, + "thread breakpoint stopped at unexpected number of threads") + self.assertEqual( + stopped_threads[0].GetThreadID(), + main_thread.GetThreadID(), + "thread breakpoint stopped at the wrong thread") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/main.cpp new file mode 100644 index 00000000000..03e93bd4125 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/main.cpp @@ -0,0 +1,32 @@ +#include <chrono> +#include <thread> + +void +thread_function () +{ + // Set thread-specific breakpoint here. + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + // On Windows, a sleep_for of less than about 16 ms effectively calls + // Sleep(0). The MS standard thread implementation uses a system thread + // pool, which can deadlock on a Sleep(0), hanging not only the secondary + // thread but the entire test. I increased the delay to 20 ms to ensure + // Sleep is called with a delay greater than 0. The deadlock potential + // is described here: + // https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep#remarks +} + +int +main () +{ + // Set main breakpoint here. + + #ifdef __APPLE__ + pthread_setname_np("main-thread"); + #endif + + std::thread t(thread_function); + t.join(); + + thread_function(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/Makefile new file mode 100644 index 00000000000..c46619c6623 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py new file mode 100644 index 00000000000..126ad9e97ee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py @@ -0,0 +1,76 @@ +""" +Test that we obey thread conditioned breakpoints and expression +conditioned breakpoints simultaneously +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ThreadSpecificBreakPlusConditionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # test frequently times out or hangs + @skipIf(oslist=['windows', 'freebsd']) + @skipIfDarwin + # hits break in another thread in testrun + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr18522') + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=['ios', 'watchos', 'tvos', 'bridgeos'], archs=['armv7', 'armv7k'], bugnumber='rdar://problem/34563348') # Two threads seem to end up with the same my_value when built for armv7. + @expectedFailureNetBSD + def test_python(self): + """Test that we obey thread conditioned breakpoints.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + main_source_spec = lldb.SBFileSpec("main.cpp") + + # Set a breakpoint in the thread body, and make it active for only the + # first thread. + break_thread_body = target.BreakpointCreateBySourceRegex( + "Break here in thread body.", main_source_spec) + self.assertTrue( + break_thread_body.IsValid() and break_thread_body.GetNumLocations() > 0, + "Failed to set thread body breakpoint.") + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_thread_body) + + victim_thread = threads[0] + + # Pick one of the threads, and change the breakpoint so it ONLY stops for this thread, + # but add a condition that it won't stop for this thread's my_value. The other threads + # pass the condition, so they should stop, but if the thread-specification is working + # they should not stop. So nobody should hit the breakpoint anymore, and we should + # just exit cleanly. + + frame = victim_thread.GetFrameAtIndex(0) + value = frame.FindVariable("my_value").GetValueAsSigned(0) + self.assertTrue( + value > 0 and value < 11, + "Got a reasonable value for my_value.") + + cond_string = "my_value != %d" % (value) + + break_thread_body.SetThreadID(victim_thread.GetThreadID()) + break_thread_body.SetCondition(cond_string) + + process.Continue() + + next_stop_state = process.GetState() + self.assertTrue( + next_stop_state == lldb.eStateExited, + "We should have not hit the breakpoint again.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/main.cpp new file mode 100644 index 00000000000..af8ab84157f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/main.cpp @@ -0,0 +1,39 @@ +#include <chrono> +#include <thread> +#include <vector> + +void * +thread_function (void *thread_marker) +{ + int keep_going = 1; + int my_value = *((int *)thread_marker); + int counter = 0; + + while (counter < 20) + { + counter++; // Break here in thread body. + std::this_thread::sleep_for(std::chrono::microseconds(10)); + } + return NULL; +} + + +int +main () +{ + std::vector<std::thread> threads; + + int thread_value = 0; + int i; + + for (i = 0; i < 10; i++) + { + thread_value += 1; + threads.push_back(std::thread(thread_function, &thread_value)); + } + + for (i = 0; i < 10; i++) + threads[i].join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/Makefile new file mode 100644 index 00000000000..07133cff358 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=thread -g + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py new file mode 100644 index 00000000000..1b71de5d273 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/TestTsanBasic.py @@ -0,0 +1,135 @@ +""" +Tests basic ThreadSanitizer support (detecting a data race). +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import json + + +class TsanBasicTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @expectedFailureNetBSD + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @skipIfRemote + @skipUnlessThreadSanitizer + def test(self): + self.build() + self.tsan_tests() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.line_malloc = line_number('main.c', '// malloc line') + self.line_thread1 = line_number('main.c', '// thread1 line') + self.line_thread2 = line_number('main.c', '// thread2 line') + + def tsan_tests(self): + exe = self.getBuildArtifact("a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) + + self.runCmd("run") + + stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + if stop_reason == lldb.eStopReasonExec: + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. + self.runCmd("continue") + + # the stop reason of the thread should be breakpoint. + self.expect("thread list", "A data race should be detected", + substrs=['stopped', 'stop reason = Data race detected']) + + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), + lldb.eStopReasonInstrumentation) + + # test that the TSan dylib is present + self.expect( + "image lookup -n __tsan_get_current_report", + "__tsan_get_current_report should be present", + substrs=['1 match found']) + + # We should be stopped in __tsan_on_report + process = self.dbg.GetSelectedTarget().process + thread = process.GetSelectedThread() + frame = thread.GetSelectedFrame() + self.assertTrue("__tsan_on_report" in frame.GetFunctionName()) + + # The stopped thread backtrace should contain either line1 or line2 + # from main.c. + found = False + for i in range(0, thread.GetNumFrames()): + frame = thread.GetFrameAtIndex(i) + if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c": + if frame.GetLineEntry().GetLine() == self.line_thread1: + found = True + if frame.GetLineEntry().GetLine() == self.line_thread2: + found = True + self.assertTrue(found) + + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) + + output_lines = self.res.GetOutput().split('\n') + json_line = '\n'.join(output_lines[2:]) + data = json.loads(json_line) + self.assertEqual(data["instrumentation_class"], "ThreadSanitizer") + self.assertEqual(data["issue_type"], "data-race") + self.assertEqual(len(data["mops"]), 2) + + backtraces = thread.GetStopReasonExtendedBacktraces( + lldb.eInstrumentationRuntimeTypeAddressSanitizer) + self.assertEqual(backtraces.GetSize(), 0) + + backtraces = thread.GetStopReasonExtendedBacktraces( + lldb.eInstrumentationRuntimeTypeThreadSanitizer) + self.assertTrue(backtraces.GetSize() >= 2) + + # First backtrace is a memory operation + thread = backtraces.GetThreadAtIndex(0) + found = False + for i in range(0, thread.GetNumFrames()): + frame = thread.GetFrameAtIndex(i) + if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c": + if frame.GetLineEntry().GetLine() == self.line_thread1: + found = True + if frame.GetLineEntry().GetLine() == self.line_thread2: + found = True + self.assertTrue(found) + + # Second backtrace is a memory operation + thread = backtraces.GetThreadAtIndex(1) + found = False + for i in range(0, thread.GetNumFrames()): + frame = thread.GetFrameAtIndex(i) + if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c": + if frame.GetLineEntry().GetLine() == self.line_thread1: + found = True + if frame.GetLineEntry().GetLine() == self.line_thread2: + found = True + self.assertTrue(found) + + self.runCmd("continue") + + # the stop reason of the thread should be a SIGABRT. + self.expect("thread list", "We should be stopped due a SIGABRT", + substrs=['stopped', 'stop reason = signal SIGABRT']) + + # test that we're in pthread_kill now (TSan abort the process) + self.expect("thread list", "We should be stopped in pthread_kill", + substrs=['pthread_kill']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/main.c new file mode 100644 index 00000000000..108ae74d4aa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/basic/main.c @@ -0,0 +1,36 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> + +char *pointer; + +void *f1(void *p) { + pointer[0] = 'x'; // thread1 line + return NULL; +} + +void *f2(void *p) { + pointer[0] = 'y'; // thread2 line + return NULL; +} + +int main (int argc, char const *argv[]) +{ + pointer = (char *)malloc(10); // malloc line + + pthread_t t1, t2; + pthread_create(&t1, NULL, f1, NULL); + pthread_create(&t2, NULL, f2, NULL); + + pthread_join(t1, NULL); + pthread_join(t2, NULL); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/Makefile new file mode 100644 index 00000000000..5f671971d59 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp +CFLAGS_EXTRAS := -fsanitize=thread -g + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/TestTsanCPPGlobalLocation.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/TestTsanCPPGlobalLocation.py new file mode 100644 index 00000000000..407126d01d3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/TestTsanCPPGlobalLocation.py @@ -0,0 +1,64 @@ +""" +Tests that TSan correctly reports the filename and line number of a racy global C++ variable. +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import json + + +class TsanCPPGlobalLocationTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @expectedFailureNetBSD + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @skipIfRemote + @skipUnlessThreadSanitizer + def test(self): + self.build() + self.tsan_tests() + + def tsan_tests(self): + exe = self.getBuildArtifact("a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) + + self.runCmd("run") + + stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + if stop_reason == lldb.eStopReasonExec: + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. + self.runCmd("continue") + + # the stop reason of the thread should be breakpoint. + self.expect("thread list", "A data race should be detected", + substrs=['stopped', 'stop reason = Data race detected']) + + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) + + output_lines = self.res.GetOutput().split('\n') + json_line = '\n'.join(output_lines[2:]) + data = json.loads(json_line) + self.assertEqual(data["instrumentation_class"], "ThreadSanitizer") + self.assertEqual(data["issue_type"], "data-race") + + self.assertTrue(data["location_filename"].endswith("/main.cpp")) + self.assertEqual( + data["location_line"], + line_number( + 'main.cpp', + '// global variable')) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/main.cpp new file mode 100644 index 00000000000..04735ef86ff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/cpp_global_location/main.cpp @@ -0,0 +1,37 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +long my_global_variable; // global variable + +void *f1(void *p) { + my_global_variable = 42; + return NULL; +} + +void *f2(void *p) { + my_global_variable = 43; + return NULL; +} + +int main (int argc, char const *argv[]) +{ + pthread_t t1; + pthread_create(&t1, NULL, f1, NULL); + + pthread_t t2; + pthread_create(&t2, NULL, f2, NULL); + + pthread_join(t1, NULL); + pthread_join(t2, NULL); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/Makefile new file mode 100644 index 00000000000..07133cff358 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=thread -g + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/TestTsanGlobalLocation.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/TestTsanGlobalLocation.py new file mode 100644 index 00000000000..7bfd90b0af3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/TestTsanGlobalLocation.py @@ -0,0 +1,64 @@ +""" +Tests that TSan correctly reports the filename and line number of a racy global variable. +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import json + + +class TsanGlobalLocationTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @expectedFailureNetBSD + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @skipIfRemote + @skipUnlessThreadSanitizer + def test(self): + self.build() + self.tsan_tests() + + def tsan_tests(self): + exe = self.getBuildArtifact("a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) + + self.runCmd("run") + + stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + if stop_reason == lldb.eStopReasonExec: + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. + self.runCmd("continue") + + # the stop reason of the thread should be breakpoint. + self.expect("thread list", "A data race should be detected", + substrs=['stopped', 'stop reason = Data race detected']) + + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) + + output_lines = self.res.GetOutput().split('\n') + json_line = '\n'.join(output_lines[2:]) + data = json.loads(json_line) + self.assertEqual(data["instrumentation_class"], "ThreadSanitizer") + self.assertEqual(data["issue_type"], "data-race") + + self.assertTrue(data["location_filename"].endswith("/main.c")) + self.assertEqual( + data["location_line"], + line_number( + 'main.c', + '// global variable')) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/main.c new file mode 100644 index 00000000000..4c88d9f0cc0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/global_location/main.c @@ -0,0 +1,37 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +long my_global_variable; // global variable + +void *f1(void *p) { + my_global_variable = 42; + return NULL; +} + +void *f2(void *p) { + my_global_variable = 43; + return NULL; +} + +int main (int argc, char const *argv[]) +{ + pthread_t t1; + pthread_create(&t1, NULL, f1, NULL); + + pthread_t t2; + pthread_create(&t2, NULL, f2, NULL); + + pthread_join(t1, NULL); + pthread_join(t2, NULL); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/Makefile new file mode 100644 index 00000000000..07133cff358 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=thread -g + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/TestTsanMultiple.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/TestTsanMultiple.py new file mode 100644 index 00000000000..b40f950eda5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/TestTsanMultiple.py @@ -0,0 +1,81 @@ +""" +Test ThreadSanitizer when multiple different issues are found. +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import json + + +class TsanMultipleTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @expectedFailureNetBSD + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @skipIfRemote + @skipUnlessThreadSanitizer + def test(self): + self.build() + self.tsan_tests() + + def tsan_tests(self): + exe = self.getBuildArtifact("a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) + + self.runCmd("env TSAN_OPTIONS=abort_on_error=0") + + self.runCmd("run") + + stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + if stop_reason == lldb.eStopReasonExec: + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. + self.runCmd("continue") + + report_count = 0 + while self.dbg.GetSelectedTarget().process.GetSelectedThread( + ).GetStopReason() == lldb.eStopReasonInstrumentation: + report_count += 1 + + stop_description = self.dbg.GetSelectedTarget( + ).process.GetSelectedThread().GetStopDescription(100) + + self.assertTrue( + (stop_description == "Data race detected") or + (stop_description == "Use of deallocated memory detected") or + (stop_description == "Thread leak detected") or + (stop_description == "Use of an uninitialized or destroyed mutex detected") or + (stop_description == "Unlock of an unlocked mutex (or by a wrong thread) detected") + ) + + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) + + output_lines = self.res.GetOutput().split('\n') + json_line = '\n'.join(output_lines[2:]) + data = json.loads(json_line) + self.assertEqual(data["instrumentation_class"], "ThreadSanitizer") + + backtraces = self.dbg.GetSelectedTarget().process.GetSelectedThread( + ).GetStopReasonExtendedBacktraces(lldb.eInstrumentationRuntimeTypeThreadSanitizer) + self.assertTrue(backtraces.GetSize() >= 1) + + self.runCmd("continue") + + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetState(), + lldb.eStateExited, + PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/main.m new file mode 100644 index 00000000000..d15bdaa3300 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/multiple/main.m @@ -0,0 +1,137 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> +#import <pthread.h> + +long my_global; + +void *Thread1(void *arg) { + my_global = 42; + return NULL; +} + +void *Thread2(void *arg) { + my_global = 144; + return NULL; +} + +void TestDataRace1() { + pthread_t t1, t2; + pthread_create(&t1, NULL, Thread1, NULL); + pthread_create(&t2, NULL, Thread2, NULL); + + pthread_join(t1, NULL); + pthread_join(t2, NULL); +} + +void TestInvalidMutex() { + pthread_mutex_t m = {0}; + pthread_mutex_lock(&m); + + pthread_mutex_init(&m, NULL); + pthread_mutex_lock(&m); + pthread_mutex_unlock(&m); + pthread_mutex_destroy(&m); + pthread_mutex_lock(&m); +} + +void TestMutexWrongLock() { + pthread_mutex_t m = {0}; + pthread_mutex_init(&m, NULL); + pthread_mutex_unlock(&m); +} + +long some_global; + +void TestDataRaceBlocks1() { + dispatch_queue_t q = dispatch_queue_create("my.queue", DISPATCH_QUEUE_CONCURRENT); + + for (int i = 0; i < 2; i++) { + dispatch_async(q, ^{ + some_global++; // race 1 + + usleep(100000); // force the blocks to be on different threads + }); + } + + usleep(100000); + dispatch_barrier_sync(q, ^{ }); +} + +void TestDataRaceBlocks2() { + dispatch_queue_t q = dispatch_queue_create("my.queue2", DISPATCH_QUEUE_CONCURRENT); + + char *c; + + c = malloc((rand() % 1000) + 10); + for (int i = 0; i < 2; i++) { + dispatch_async(q, ^{ + c[0] = 'x'; // race 2 + fprintf(stderr, "tid: %p\n", pthread_self()); + usleep(100000); // force the blocks to be on different threads + }); + } + dispatch_barrier_sync(q, ^{ }); + + free(c); +} + +void TestUseAfterFree() { + char *c; + + c = malloc((rand() % 1000) + 10); + free(c); + c[0] = 'x'; +} + +void TestRacePipe() { + dispatch_queue_t q = dispatch_queue_create("my.queue3", DISPATCH_QUEUE_CONCURRENT); + + int a[2]; + pipe(a); + int fd = a[0]; + + for (int i = 0; i < 2; i++) { + dispatch_async(q, ^{ + write(fd, "abc", 3); + usleep(100000); // force the blocks to be on different threads + }); + dispatch_async(q, ^{ + close(fd); + usleep(100000); + }); + } + + dispatch_barrier_sync(q, ^{ }); +} + +void TestThreadLeak() { + pthread_t t1; + pthread_create(&t1, NULL, Thread1, NULL); +} + +int main(int argc, const char * argv[]) { + TestDataRace1(); + + TestInvalidMutex(); + + TestMutexWrongLock(); + + TestDataRaceBlocks1(); + + TestDataRaceBlocks2(); + + TestUseAfterFree(); + + TestRacePipe(); + + TestThreadLeak(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/Makefile new file mode 100644 index 00000000000..07133cff358 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=thread -g + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py new file mode 100644 index 00000000000..09704e40cd3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/TestTsanThreadLeak.py @@ -0,0 +1,46 @@ +""" +Tests ThreadSanitizer's support to detect a leaked thread. +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil + + +class TsanThreadLeakTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @expectedFailureNetBSD + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @skipIfRemote + @skipUnlessThreadSanitizer + def test(self): + self.build() + self.tsan_tests() + + def tsan_tests(self): + exe = self.getBuildArtifact("a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) + + self.runCmd("run") + + stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + if stop_reason == lldb.eStopReasonExec: + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. + self.runCmd("continue") + + # the stop reason of the thread should be breakpoint. + self.expect("thread list", "A thread leak should be detected", + substrs=['stopped', 'stop reason = Thread leak detected']) + + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), + lldb.eStopReasonInstrumentation) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/main.c new file mode 100644 index 00000000000..0c3a2cf84f5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_leak/main.c @@ -0,0 +1,23 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> + +void *f1(void *p) { + printf("hello\n"); + return NULL; +} + +int main (int argc, char const *argv[]) +{ + pthread_t t1; + pthread_create(&t1, NULL, f1, NULL); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/Makefile new file mode 100644 index 00000000000..07133cff358 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=thread -g + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/TestTsanThreadNumbers.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/TestTsanThreadNumbers.py new file mode 100644 index 00000000000..61870eac9c4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/TestTsanThreadNumbers.py @@ -0,0 +1,82 @@ +""" +Tests that TSan and LLDB have correct thread numbers. +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import json + + +class TsanThreadNumbersTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["linux"], + bugnumber="non-core functionality, need to reenable and fix later (DES 2014.11.07)") + @expectedFailureNetBSD + @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default + @skipIfRemote + @skipUnlessThreadSanitizer + def test(self): + self.build() + self.tsan_tests() + + def tsan_tests(self): + exe = self.getBuildArtifact("a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) + + self.runCmd("run") + + stop_reason = self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason() + if stop_reason == lldb.eStopReasonExec: + # On OS X 10.10 and older, we need to re-exec to enable + # interceptors. + self.runCmd("continue") + + # the stop reason of the thread should be breakpoint. + self.expect("thread list", "A data race should be detected", + substrs=['stopped', 'stop reason = Data race detected']) + + self.assertEqual( + self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), + lldb.eStopReasonInstrumentation) + + report_thread_id = self.dbg.GetSelectedTarget( + ).process.GetSelectedThread().GetIndexID() + + self.expect( + "thread info -s", + "The extended stop info should contain the TSan provided fields", + substrs=[ + "instrumentation_class", + "description", + "mops"]) + + output_lines = self.res.GetOutput().split('\n') + json_line = '\n'.join(output_lines[2:]) + data = json.loads(json_line) + self.assertEqual(data["instrumentation_class"], "ThreadSanitizer") + self.assertEqual(data["issue_type"], "data-race") + self.assertEqual(len(data["mops"]), 2) + + self.assertEqual(data["mops"][0]["thread_id"], report_thread_id) + + other_thread_id = data["mops"][1]["thread_id"] + self.assertTrue(other_thread_id != report_thread_id) + other_thread = self.dbg.GetSelectedTarget( + ).process.GetThreadByIndexID(other_thread_id) + self.assertTrue(other_thread.IsValid()) + + self.runCmd("thread select %d" % other_thread_id) + + self.expect( + "thread backtrace", + "The other thread should be stopped in f1 or f2", + substrs=[ + "a.out", + "main.c"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/main.c new file mode 100644 index 00000000000..5bc82131402 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tsan/thread_numbers/main.c @@ -0,0 +1,57 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +char *pointer; + +void *nothing(void *p) { + return NULL; +} + +void *f1(void *p) { + pointer[0] = 'x'; + sleep(100); + return NULL; +} + +void *f2(void *p) { + pointer[0] = 'y'; + sleep(100); + return NULL; +} + +int main (int argc, char const *argv[]) +{ + pointer = (char *)malloc(10); + + for (int i = 0; i < 3; i++) { + pthread_t t; + pthread_create(&t, NULL, nothing, NULL); + pthread_join(t, NULL); + } + + pthread_t t1; + pthread_create(&t1, NULL, f1, NULL); + + for (int i = 0; i < 3; i++) { + pthread_t t; + pthread_create(&t, NULL, nothing, NULL); + pthread_join(t, NULL); + } + + pthread_t t2; + pthread_create(&t2, NULL, f2, NULL); + + pthread_join(t1, NULL); + pthread_join(t2, NULL); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tty/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tty/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tty/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py new file mode 100644 index 00000000000..bf5f1200ace --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py @@ -0,0 +1,51 @@ +""" +Test lldb command aliases. +""" + +from __future__ import print_function + + +import unittest2 +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LaunchInTerminalTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # Darwin is the only platform that I know of that supports optionally launching + # a program in a separate terminal window. It would be great if other platforms + # added support for this. + @skipUnlessDarwin + # If the test is being run under sudo, the spawned terminal won't retain that elevated + # privilege so it can't open the socket to talk back to the test case + @unittest2.skipIf(hasattr(os, 'geteuid') and os.geteuid() + == 0, "test cannot be run as root") + # Do we need to disable this test if the testsuite is being run on a remote system? + # This env var is only defined when the shell is running in a local mac + # terminal window + @unittest2.skipUnless( + 'TERM_PROGRAM' in os.environ, + "test must be run on local system") + @no_debug_info_test + def test_launch_in_terminal(self): + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + launch_info = lldb.SBLaunchInfo(["-lAF", "/tmp/"]) + launch_info.SetLaunchFlags( + lldb.eLaunchFlagLaunchInTTY | lldb.eLaunchFlagCloseTTYOnExit) + error = lldb.SBError() + process = target.Launch(launch_info, error) + print("Error was: %s."%(error.GetCString())) + self.assertTrue( + error.Success(), + "Make sure launch happened successfully in a terminal window") + # Running in synchronous mode our process should have run and already + # exited by the time target.Launch() returns + self.assertTrue(process.GetState() == lldb.eStateExited) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tty/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tty/main.c new file mode 100644 index 00000000000..71c854b5bf4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/tty/main.c @@ -0,0 +1,10 @@ +#include <stdio.h> + +int +main(int argc, char** argv) +{ + for (int i = 0; i < argc; i++) { + printf("%d: %s.\n", i, argv[i]); + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py new file mode 100644 index 00000000000..fb0b1096f4d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py @@ -0,0 +1,155 @@ +""" +Check that types only get completed when necessary. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TypeCompletionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + compiler="icc", + bugnumber="often fails with 'NameAndAddress should be valid.") + # Fails with gcc 4.8.1 with llvm.org/pr15301 LLDB prints incorrect sizes + # of STL containers + def test_with_run_command(self): + """Check that types only get completed when necessary.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp( + self, "// Set break point at this line.") + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type category enable -l c++', check=False) + + self.runCmd('type category disable -l c++', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_type = p_vector.GetType() + self.assertFalse( + p_type.IsTypeComplete(), + 'vector<T> complete but it should not be') + + self.runCmd("continue") + + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_type = p_vector.GetType() + self.assertFalse( + p_type.IsTypeComplete(), + 'vector<T> complete but it should not be') + + self.runCmd("continue") + + self.runCmd("frame variable p --show-types") + + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_type = p_vector.GetType() + self.assertTrue( + p_type.IsTypeComplete(), + 'vector<T> should now be complete') + name_address_type = p_type.GetTemplateArgumentType(0) + self.assertTrue( + name_address_type.IsValid(), + 'NameAndAddress should be valid') + self.assertFalse( + name_address_type.IsTypeComplete(), + 'NameAndAddress complete but it should not be') + + self.runCmd("continue") + + self.runCmd("frame variable guy --show-types") + + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_type = p_vector.GetType() + self.assertTrue( + p_type.IsTypeComplete(), + 'vector<T> should now be complete') + name_address_type = p_type.GetTemplateArgumentType(0) + self.assertTrue( + name_address_type.IsValid(), + 'NameAndAddress should be valid') + self.assertTrue( + name_address_type.IsTypeComplete(), + 'NameAndAddress should now be complete') + field0 = name_address_type.GetFieldAtIndex(0) + self.assertTrue( + field0.IsValid(), + 'NameAndAddress::m_name should be valid') + string = field0.GetType().GetPointeeType() + self.assertTrue(string.IsValid(), 'CustomString should be valid') + self.assertFalse(string.IsTypeComplete(), + 'CustomString complete but it should not be') + + self.runCmd("continue") + + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_type = p_vector.GetType() + self.assertTrue( + p_type.IsTypeComplete(), + 'vector<T> should now be complete') + name_address_type = p_type.GetTemplateArgumentType(0) + self.assertTrue( + name_address_type.IsValid(), + 'NameAndAddress should be valid') + self.assertTrue( + name_address_type.IsTypeComplete(), + 'NameAndAddress should now be complete') + field0 = name_address_type.GetFieldAtIndex(0) + self.assertTrue( + field0.IsValid(), + 'NameAndAddress::m_name should be valid') + string = field0.GetType().GetPointeeType() + self.assertTrue(string.IsValid(), 'CustomString should be valid') + self.assertFalse(string.IsTypeComplete(), + 'CustomString complete but it should not be') + + self.runCmd('type category enable -l c++', check=False) + self.runCmd('frame variable guy --show-types --ptr-depth=1') + + p_vector = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('p') + p_type = p_vector.GetType() + self.assertTrue( + p_type.IsTypeComplete(), + 'vector<T> should now be complete') + name_address_type = p_type.GetTemplateArgumentType(0) + self.assertTrue( + name_address_type.IsValid(), + 'NameAndAddress should be valid') + self.assertTrue( + name_address_type.IsTypeComplete(), + 'NameAndAddress should now be complete') + field0 = name_address_type.GetFieldAtIndex(0) + self.assertTrue( + field0.IsValid(), + 'NameAndAddress::m_name should be valid') + string = field0.GetType().GetPointeeType() + self.assertTrue(string.IsValid(), 'CustomString should be valid') + self.assertTrue( + string.IsTypeComplete(), + 'CustomString should now be complete') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/main.cpp new file mode 100644 index 00000000000..a361df0849a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_completion/main.cpp @@ -0,0 +1,80 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <string.h> +#include <vector> +#include <iostream> + +class CustomString +{ +public: + CustomString (const char* buffer) : + m_buffer(nullptr) + { + if (buffer) + { + auto l = strlen(buffer); + m_buffer = new char[1 + l]; + strcpy(m_buffer, buffer); + } + } + + ~CustomString () + { + delete[] m_buffer; + } + + const char* + GetBuffer () + { + return m_buffer; + } + +private: + char *m_buffer; +}; + +class NameAndAddress + { + public: + CustomString& GetName() { return *m_name; } + CustomString& GetAddress() { return *m_address; } + NameAndAddress(const char* N, const char* A) : m_name(new CustomString(N)), m_address(new CustomString(A)) + { + } + ~NameAndAddress() + { + } + + private: + CustomString* m_name; + CustomString* m_address; +}; + +typedef std::vector<NameAndAddress> People; + +int main (int argc, const char * argv[]) +{ + People p; + p.push_back(NameAndAddress("Enrico","123 Main Street")); + p.push_back(NameAndAddress("Foo","10710 Johnson Avenue")); // Set break point at this line. + p.push_back(NameAndAddress("Arpia","6956 Florey Street")); + p.push_back(NameAndAddress("Apple","1 Infinite Loop")); // Set break point at this line. + p.push_back(NameAndAddress("Richard","9500 Gilman Drive")); + p.push_back(NameAndAddress("Bar","3213 Windsor Rd")); + + for (int j = 0; j<p.size(); j++) + { + NameAndAddress guy = p[j]; + std::cout << "Person " << j << " is named " << guy.GetName().GetBuffer() << " and lives at " << guy.GetAddress().GetBuffer() << std::endl; // Set break point at this line. + } + + return 0; + +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/Makefile new file mode 100644 index 00000000000..876340159d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/Makefile @@ -0,0 +1,8 @@ +OBJCXX_SOURCES := main.mm + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py new file mode 100644 index 00000000000..2257fd63063 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py @@ -0,0 +1,51 @@ +""" +Test type lookup command. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TypeLookupTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.mm', '// break here') + + @skipUnlessDarwin + @skipIf(archs=['i386']) + def test_type_lookup(self): + """Test type lookup command.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.mm", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect( + 'type lookup NoSuchType', + substrs=['@interface'], + matching=False) + self.expect('type lookup NSURL', substrs=['NSURL']) + self.expect('type lookup NSArray', substrs=['NSArray']) + self.expect('type lookup NSObject', substrs=['NSObject', 'isa']) + self.expect('type lookup PleaseDontBeARealTypeThatExists', substrs=[ + "no type was found matching 'PleaseDontBeARealTypeThatExists'"]) + self.expect('type lookup MyCPPClass', substrs=['setF', 'float getF']) + self.expect('type lookup MyClass', substrs=['setF', 'float getF']) + self.expect('type lookup MyObjCClass', substrs=['@interface MyObjCClass', 'int x', 'int y']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/main.mm new file mode 100644 index 00000000000..7b005a2086d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/type_lookup/main.mm @@ -0,0 +1,57 @@ +//===-- main.mm -----------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +class MyCPPClass { +public: + MyCPPClass(float f) : f(f) {} + + float setF(float f) { + float oldf = this->f; + this->f = f; + return oldf; + } + + float getF() { + return f; + } +private: + float f; +}; + +typedef MyCPPClass MyClass; + +@interface MyObjCClass : NSObject { + int x; +} +- (id)init; +- (int)read; +@end + +@implementation MyObjCClass { + int y; +} +- (id)init { + if (self = [super init]) { + self->x = 12; + self->y = 24; + } + return self; +} +- (int)read { + return self->x + self->y; +} +@end + +int main (int argc, const char * argv[]) +{ + MyClass my_cpp(3.1415); + return 0; // break here +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/basic/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/basic/Makefile new file mode 100644 index 00000000000..b27db90a40d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/basic/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=undefined -g + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/basic/TestUbsanBasic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/basic/TestUbsanBasic.py new file mode 100644 index 00000000000..76fdb33fd32 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/basic/TestUbsanBasic.py @@ -0,0 +1,89 @@ +""" +Tests basic UndefinedBehaviorSanitizer support (detecting an alignment error). +""" + +import os +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import json + + +class UbsanBasicTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessUndefinedBehaviorSanitizer + def test(self): + self.build() + self.ubsan_tests() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.line_align = line_number('main.c', '// align line') + + def ubsan_tests(self): + # Load the test + exe = self.getBuildArtifact("a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) + + self.runCmd("run") + + process = self.dbg.GetSelectedTarget().process + thread = process.GetSelectedThread() + frame = thread.GetSelectedFrame() + + # the stop reason of the thread should be breakpoint. + self.expect("thread list", "A ubsan issue should be detected", + substrs=['stopped', 'stop reason =']) + + stop_reason = thread.GetStopReason() + self.assertEqual(stop_reason, lldb.eStopReasonInstrumentation) + + # test that the UBSan dylib is present + self.expect( + "image lookup -n __ubsan_on_report", + "__ubsan_on_report should be present", + substrs=['1 match found']) + + # We should be stopped in __ubsan_on_report + self.assertTrue("__ubsan_on_report" in frame.GetFunctionName()) + + # The stopped thread backtrace should contain either 'align line' + found = False + for i in range(thread.GetNumFrames()): + frame = thread.GetFrameAtIndex(i) + if frame.GetLineEntry().GetFileSpec().GetFilename() == "main.c": + if frame.GetLineEntry().GetLine() == self.line_align: + found = True + self.assertTrue(found) + + backtraces = thread.GetStopReasonExtendedBacktraces( + lldb.eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer) + self.assertTrue(backtraces.GetSize() == 1) + + self.expect( + "thread info -s", + "The extended stop info should contain the UBSan provided fields", + substrs=[ + "instrumentation_class", + "memory_address", + "description", + "filename", + "line", + "col"]) + + output_lines = self.res.GetOutput().split('\n') + json_line = '\n'.join(output_lines[2:]) + data = json.loads(json_line) + + self.assertEqual(data["instrumentation_class"], "UndefinedBehaviorSanitizer") + self.assertEqual(data["description"], "misaligned-pointer-use") + self.assertEqual(os.path.basename(data["filename"]), "main.c") + self.assertEqual(data["line"], self.line_align) + + self.runCmd("continue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/basic/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/basic/main.c new file mode 100644 index 00000000000..4991fc074d0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/basic/main.c @@ -0,0 +1,4 @@ +int main() { + int data[4]; + return *(int *)(((char *)&data[0]) + 2); // align line +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/user-expression/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/user-expression/Makefile new file mode 100644 index 00000000000..b27db90a40d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/user-expression/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -fsanitize=undefined -g + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/user-expression/TestUbsanUserExpression.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/user-expression/TestUbsanUserExpression.py new file mode 100644 index 00000000000..68f8c0360ff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/user-expression/TestUbsanUserExpression.py @@ -0,0 +1,46 @@ +""" +Test that hitting a UBSan issue while running user expression doesn't break the evaluation. +""" + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil + + +class UbsanUserExpressionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessUndefinedBehaviorSanitizer + def test(self): + self.build() + self.ubsan_tests() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.line_breakpoint = line_number('main.c', '// breakpoint line') + + def ubsan_tests(self): + # Load the test + exe = self.getBuildArtifact("a.out") + self.expect( + "file " + exe, + patterns=["Current executable set to .*a.out"]) + + self.runCmd("breakpoint set -f main.c -l %d" % self.line_breakpoint) + + self.runCmd("run") + + process = self.dbg.GetSelectedTarget().process + thread = process.GetSelectedThread() + frame = thread.GetSelectedFrame() + + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect("p foo()", substrs=["(int) $0 = 42"]) + + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/user-expression/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/user-expression/main.c new file mode 100644 index 00000000000..4786aaa89b2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/ubsan/user-expression/main.c @@ -0,0 +1,9 @@ +int foo() { + int data[4]; + int x = *(int *)(((char *)&data[0]) + 2); + return 42; +} + +int main() { + return 0; // breakpoint line +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/Makefile new file mode 100644 index 00000000000..493ea3f7f68 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/Makefile @@ -0,0 +1,5 @@ +C_SOURCES := main.c + +CFLAGS ?= -g -fomit-frame-pointer + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/TestEhFrameUnwind.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/TestEhFrameUnwind.py new file mode 100644 index 00000000000..905543ff769 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/TestEhFrameUnwind.py @@ -0,0 +1,49 @@ +""" +Test that we can backtrace correctly from Non ABI functions on the stack +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class EHFrameBasedUnwind(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessPlatform(['linux']) + @skipIf(archs=["aarch64", "arm", "i386", "i686"]) + def test(self): + """Test that we can backtrace correctly from Non ABI functions on the stack""" + self.build() + self.setTearDownCleanup() + + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + + self.assertTrue(target, VALID_TARGET) + + lldbutil.run_break_set_by_symbol(self, "func") + + process = target.LaunchSimple( + ["abc", "xyz"], None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.Launch() failed") + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) + self.expect(stacktraces, exe=False, + substrs=['(int)argc=3']) + + self.runCmd("thread step-inst") + + stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) + self.expect(stacktraces, exe=False, + substrs=['(int)argc=3']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/main.c new file mode 100644 index 00000000000..46de1efe626 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/ehframe/main.c @@ -0,0 +1,58 @@ +void func() { + +#ifdef __powerpc64__ + __asm__ ( + "mflr 0;" + "std 0,16(1);" + "addi 1,1,-24;" + "mr 31,1;" + ".cfi_def_cfa_offset 24;" + "addi 0,0,0;" + "addi 1,1,24;" + "ld 0,16(1);" + ".cfi_def_cfa_offset 0;" + ); +#elif !defined __mips__ + __asm__ ( + "pushq $0x10;" + ".cfi_def_cfa_offset 16;" + "jmp label;" + "movq $0x48, %rax;" +"label: subq $0x38, %rax;" + "movq $0x48, %rcx;" + "movq $0x48, %rdx;" + "movq $0x48, %rax;" + "popq %rax;" + ); +#elif __mips64 + __asm__ ( + "daddiu $sp,$sp,-16;" + ".cfi_def_cfa_offset 16;" + "sd $ra,8($sp);" + ".cfi_offset 31, -8;" + "daddiu $ra,$zero,0;" + "ld $ra,8($sp);" + "daddiu $sp, $sp,16;" + ".cfi_restore 31;" + ".cfi_def_cfa_offset 0;" + ); +#else + // For MIPS32 + __asm__ ( + "addiu $sp,$sp,-8;" + ".cfi_def_cfa_offset 8;" + "sw $ra,4($sp);" + ".cfi_offset 31, -4;" + "addiu $ra,$zero,0;" + "lw $ra,4($sp);" + "addiu $sp,$sp,8;" + ".cfi_restore 31;" + ".cfi_def_cfa_offset 0;" + ); +#endif +} + +int main(int argc, char const *argv[]) +{ + func(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/Makefile new file mode 100644 index 00000000000..36cf5a296e5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/Makefile @@ -0,0 +1,5 @@ +C_SOURCES := main.c + +CFLAGS ?= -g -Os + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py new file mode 100644 index 00000000000..1086a34d3dd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py @@ -0,0 +1,85 @@ +""" +Test that we can backtrace correctly with 'noreturn' functions on the stack +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NoreturnUnwind(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipIfWindows # clang-cl does not support gcc style attributes. + # clang does not preserve LR in noreturn functions, making unwinding impossible + @skipIf(compiler="clang", archs=['arm'], oslist=['linux']) + @expectedFailureAll(bugnumber="llvm.org/pr33452", triple='^mips') + @expectedFailureNetBSD + def test(self): + """Test that we can backtrace correctly with 'noreturn' functions on the stack""" + self.build() + self.setTearDownCleanup() + + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.Launch() failed") + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + thread = process.GetThreadAtIndex(0) + abort_frame_number = 0 + for f in thread.frames: + # Some C libraries mangle the abort symbol into __GI_abort. + if f.GetFunctionName() in ["abort", "__GI_abort"]: + break + abort_frame_number = abort_frame_number + 1 + + if self.TraceOn(): + print("Backtrace once we're stopped:") + for f in thread.frames: + print(" %d %s" % (f.GetFrameID(), f.GetFunctionName())) + + # I'm going to assume that abort() ends up calling/invoking another + # function before halting the process. In which case if abort_frame_number + # equals 0, we didn't find abort() in the backtrace. + if abort_frame_number == len(thread.frames): + self.fail("Unable to find abort() in backtrace.") + + func_c_frame_number = abort_frame_number + 1 + if thread.GetFrameAtIndex( + func_c_frame_number).GetFunctionName() != "func_c": + self.fail("Did not find func_c() above abort().") + + # This depends on whether we see the func_b inlined function in the backtrace + # or not. I'm not interested in testing that aspect of the backtrace here + # right now. + + if thread.GetFrameAtIndex( + func_c_frame_number + + 1).GetFunctionName() == "func_b": + func_a_frame_number = func_c_frame_number + 2 + else: + func_a_frame_number = func_c_frame_number + 1 + + if thread.GetFrameAtIndex( + func_a_frame_number).GetFunctionName() != "func_a": + self.fail("Did not find func_a() above func_c().") + + main_frame_number = func_a_frame_number + 1 + + if thread.GetFrameAtIndex( + main_frame_number).GetFunctionName() != "main": + self.fail("Did not find main() above func_a().") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/main.c new file mode 100644 index 00000000000..4f6525fbf52 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/main.c @@ -0,0 +1,35 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +static void func_a (void) __attribute__((noinline)); +static void func_b (void) __attribute__((noreturn)); +static void func_c (void) __attribute__((noinline)); + +static void +func_c (void) +{ + abort (); +} + +static void +func_b (void) +{ + func_c (); + while (1) + ; +} + +static void +func_a (void) +{ + func_b (); +} + +int +main (int argc, char *argv[]) +{ + func_a (); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/module-end/TestNoReturnModuleEnd.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/module-end/TestNoReturnModuleEnd.py new file mode 100644 index 00000000000..cce485bd5a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/module-end/TestNoReturnModuleEnd.py @@ -0,0 +1,50 @@ +""" +Test that we properly display the backtrace when a noreturn function happens to +be at the end of the stack. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestNoreturnModuleEnd(TestBase): + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + super(TestNoreturnModuleEnd, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(TestNoreturnModuleEnd, self).tearDown() + + def test(self): + target = self.dbg.CreateTarget("test.out") + process = target.LoadCore("test.core") + self.assertTrue(process.IsValid(), PROCESS_IS_VALID) + self.assertEqual(process.GetNumThreads(), 1) + + thread = process.GetSelectedThread() + self.assertTrue(thread.IsValid()) + + backtrace = [ + ["func2", 3], + ["func1", 8], + ["_start", 8], + ] + self.assertEqual(thread.GetNumFrames(), len(backtrace)) + for i in range(len(backtrace)): + frame = thread.GetFrameAtIndex(i) + self.assertTrue(frame.IsValid()) + symbol = frame.GetSymbol() + self.assertTrue(symbol.IsValid()) + self.assertEqual(symbol.GetName(), backtrace[i][0]) + function_start = symbol.GetStartAddress().GetLoadAddress(target) + self.assertEquals(function_start + backtrace[i][1], frame.GetPC()) + + self.dbg.DeleteTarget(target) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/module-end/a.s b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/module-end/a.s new file mode 100644 index 00000000000..119465c132a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/module-end/a.s @@ -0,0 +1,35 @@ +# compile this with: +# as a.s -o a.o --32 && ld a.o -m elf_i386 +# generate core file with: +# ulimit -s 12 && ./a.out + +.text + +.globl func2 +.type func2, @function +func2: + pushl %ebp + movl %esp, %ebp + movl 0, %eax + popl %ebp + ret +.size func2, .-func2 + +.globl _start +.type _start, @function +_start: + pushl %ebp + movl %esp, %ebp + call func1 + popl %ebp + ret +.size _start, .-_start + +.globl func1 +.type func1, @function +func1: + pushl %ebp + movl %esp, %ebp + call func2 +.size func1, .-func1 + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/module-end/test.out b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/module-end/test.out Binary files differnew file mode 100755 index 00000000000..141c61ecbea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/module-end/test.out diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py new file mode 100644 index 00000000000..bf19cacac06 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py @@ -0,0 +1,93 @@ +""" +Test that we can backtrace correctly with 'sigtramp' functions on the stack +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SigtrampUnwind(TestBase): + mydir = TestBase.compute_mydir(__file__) + + # On different platforms the "_sigtramp" and "__kill" frames are likely to be different. + # This test could probably be adapted to run on linux/*bsd easily enough. + @skipUnlessDarwin + @expectedFailureAll(oslist=["ios", "watchos", "tvos", "bridgeos"], bugnumber="<rdar://problem/34006863>") # lldb skips 1 frame on arm64 above _sigtramp + def test(self): + """Test that we can backtrace correctly with _sigtramp on the stack""" + self.build() + self.setTearDownCleanup() + + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + lldbutil.run_break_set_by_file_and_line(self, "main.c", line_number( + 'main.c', '// Set breakpoint here'), num_expected_locations=1) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.Launch() failed") + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + self.expect( + "pro handle -n false -p true -s false SIGUSR1", + "Have lldb pass SIGUSR1 signals", + substrs=[ + "SIGUSR1", + "true", + "false", + "false"]) + + lldbutil.run_break_set_by_symbol( + self, + "handler", + num_expected_locations=1, + module_name="a.out") + + self.runCmd("continue") + + thread = process.GetThreadAtIndex(0) + + found_handler = False + found_sigtramp = False + found_kill = False + found_main = False + + for f in thread.frames: + if f.GetFunctionName() == "handler": + found_handler = True + if f.GetFunctionName() == "_sigtramp": + found_sigtramp = True + if f.GetFunctionName() == "__kill": + found_kill = True + if f.GetFunctionName() == "main": + found_main = True + + if self.TraceOn(): + print("Backtrace once we're stopped:") + for f in thread.frames: + print(" %d %s" % (f.GetFrameID(), f.GetFunctionName())) + + if not found_handler: + self.fail("Unable to find handler() in backtrace.") + + if not found_sigtramp: + self.fail("Unable to find _sigtramp() in backtrace.") + + if not found_kill: + self.fail("Unable to find kill() in backtrace.") + + if not found_main: + self.fail("Unable to find main() in backtrace.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/main.c new file mode 100644 index 00000000000..aaa03e7aa84 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/main.c @@ -0,0 +1,27 @@ +#include <stdlib.h> +#include <signal.h> +#include <stdio.h> +#include <unistd.h> + +void handler (int in) +{ + puts ("in handler routine"); + while (1) + ; +} + +void +foo () +{ + puts ("in foo ()"); + kill (getpid(), SIGUSR1); +} +int main () +{ + puts ("in main"); // Set breakpoint here + signal (SIGUSR1, handler); + puts ("signal handler set up"); + foo(); + puts ("exiting"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/Makefile new file mode 100644 index 00000000000..22f1051530f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/Makefile @@ -0,0 +1 @@ +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py new file mode 100644 index 00000000000..032b9e1aa61 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py @@ -0,0 +1,175 @@ +""" +Test that we can backtrace correctly from standard functions. + +This test suit is a collection of automatically generated tests from the source files in the +directory. Please DON'T add individual test cases to this file. + +To add a new test case to this test suit please create a simple C/C++ application and put the +source file into the directory of the test cases. The test suit will automatically pick the +file up and generate a test case from it in run time (with name test_standard_unwind_<file_name> +after escaping some special characters). +""" + +from __future__ import print_function + + +import unittest2 +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +test_source_dirs = ["."] + + +class StandardUnwindTest(TestBase): + mydir = TestBase.compute_mydir(__file__) + + def standard_unwind_tests(self): + # The following variables have to be defined for each architecture and OS we testing for: + # base_function_names: List of function names where we accept that the stack unwinding is + # correct if they are on the stack. It should include the bottom most + # function on the stack and a list of functions where we know we can't + # unwind for any reason (list of expected failure functions) + # no_step_function_names: The list of functions where we don't want to step through + # instruction by instruction for any reason. (A valid reason is if + # it is impossible to step through a function instruction by + # instruction because it is special for some reason.) For these + # functions we will immediately do a step-out when we hit them. + + triple = self.dbg.GetSelectedPlatform().GetTriple() + if re.match("arm-.*-.*-android", triple): + base_function_names = [ + "_start", # Base function on the stack + "__memcpy_base", # Function reached by a fall through from the previous function + "__memcpy_base_aligned", + # Function reached by a fall through from the previous function + ] + no_step_function_names = [ + "__sync_fetch_and_add_4", # Calls into a special SO where we can't set a breakpoint + "pthread_mutex_lock", + # Uses ldrex and strex what interferes with the software single + # stepping + "pthread_mutex_unlock", + # Uses ldrex and strex what interferes with the software single + # stepping + "pthread_once", + # Uses ldrex and strex what interferes with the software single + # stepping + ] + elif re.match("aarch64-.*-.*-android", triple): + base_function_names = [ + "do_arm64_start", # Base function on the stack + ] + no_step_function_names = [ + None, + "__cxa_guard_acquire", + # Uses ldxr and stxr what interferes with the software single + # stepping + "__cxa_guard_release", + # Uses ldxr and stxr what interferes with the software single + # stepping + "pthread_mutex_lock", + # Uses ldxr and stxr what interferes with the software single + # stepping + "pthread_mutex_unlock", + # Uses ldxr and stxr what interferes with the software single + # stepping + "pthread_once", + # Uses ldxr and stxr what interferes with the software single + # stepping + ] + else: + self.skipTest("No expectations for the current architecture") + + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + target.BreakpointCreateByName("main") + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process is not None, "SBTarget.Launch() failed") + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + "The process didn't hit main") + + index = 0 + while process.GetState() == lldb.eStateStopped: + index += 1 + if process.GetNumThreads() > 1: + # In case of a multi threaded inferior if one of the thread is stopped in a blocking + # syscall and we try to step it then + # SBThread::StepInstruction() will block forever + self.skipTest( + "Multi threaded inferiors are not supported by this test") + + thread = process.GetThreadAtIndex(0) + + if self.TraceOn(): + print("INDEX: %u" % index) + for f in thread.frames: + print(f) + + if thread.GetFrameAtIndex(0).GetFunctionName() is not None: + found_main = False + for f in thread.frames: + if f.GetFunctionName() in base_function_names: + found_main = True + break + self.assertTrue(found_main, + "Main function isn't found on the backtrace") + + if thread.GetFrameAtIndex( + 0).GetFunctionName() in no_step_function_names: + thread.StepOut() + else: + thread.StepInstruction(False) + +# Collect source files in the specified directories +test_source_files = set([]) +for d in test_source_dirs: + if os.path.isabs(d): + dirname = d + else: + dirname = os.path.join(os.path.dirname(__file__), d) + + for root, _, files in os.walk(dirname): + test_source_files = test_source_files | set( + os.path.abspath(os.path.join(root, f)) for f in files) + +# Generate test cases based on the collected source files +for f in test_source_files: + if f.endswith(".cpp") or f.endswith(".c"): + @skipIfWindows + @add_test_categories(["dwarf"]) + def test_function_dwarf(self, f=f): + if f.endswith(".cpp"): + d = {'CXX_SOURCES': f} + elif f.endswith(".c"): + d = {'C_SOURCES': f} + + # If we can't compile the inferior just skip the test instead of failing it. + # It makes the test suit more robust when testing on several different architecture + # avoid the hassle of skipping tests manually. + try: + self.buildDwarf(dictionary=d) + self.setTearDownCleanup(d) + except: + if self.TraceOn(): + print(sys.exc_info()[0]) + self.skipTest("Inferior not supported") + self.standard_unwind_tests() + + test_name = "test_unwind_" + str(f) + for c in ".=()/\\": + test_name = test_name.replace(c, '_') + + test_function_dwarf.__name__ = test_name + setattr( + StandardUnwindTest, + test_function_dwarf.__name__, + test_function_dwarf) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/divmod.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/divmod.cpp new file mode 100644 index 00000000000..b2da92e992e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/divmod.cpp @@ -0,0 +1,14 @@ +//===-- divmod.cpp ----------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int +main(int argc, char const *argv[]) +{ + signed long long a = 123456789, b = 12, c = a / b, d = a % b; + unsigned long long e = 123456789, f = 12, g = e / f, h = e % f; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/fprintf.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/fprintf.cpp new file mode 100644 index 00000000000..f8be1aa0d40 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/fprintf.cpp @@ -0,0 +1,15 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <cstdio> + +int +main(int argc, char const *argv[]) +{ + fprintf(stderr, "%d %p %s\n", argc, argv, argv[0]); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/new_delete.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/new_delete.cpp new file mode 100644 index 00000000000..b609ea366de --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/new_delete.cpp @@ -0,0 +1,14 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int +main(int argc, char const *argv[]) +{ + int* p = new int; + delete p; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py new file mode 100644 index 00000000000..04f25c586e6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py @@ -0,0 +1,52 @@ +""" +Verify that the hash computing logic for ValueObject's values can't crash us. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ValueMD5CrashTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// break here') + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24663") + def test_with_run_command(self): + """Verify that the hash computing logic for ValueObject's values can't crash us.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + value = self.frame().FindVariable("a") + value.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + + v = value.GetValue() + type_name = value.GetTypeName() + self.assertTrue(type_name == "B *", "a is a B*") + + self.runCmd("next") + self.runCmd("process kill") + + # now the process is dead, and value needs updating + v = value.GetValue() + + # if we are here, instead of crashed, the test succeeded diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/main.cpp new file mode 100644 index 00000000000..b641049f272 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/value_md5_crash/main.cpp @@ -0,0 +1,28 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +class A { +public: + virtual int foo() { return 1; } + virtual ~A () = default; + A() = default; +}; + +class B : public A { +public: + virtual int foo() { return 2; } + virtual ~B () = default; + B() = default; +}; + +int main() { + A* a = new B(); + a->foo(); // break here + return 0; // break here +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/var_path/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/var_path/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/var_path/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/var_path/TestVarPath.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/var_path/TestVarPath.py new file mode 100644 index 00000000000..faab8a7f612 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/var_path/TestVarPath.py @@ -0,0 +1,95 @@ +""" +Make sure the getting a variable path works and doesn't crash. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class TestVarPath(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def test_frame_var(self): + self.build() + self.do_test() + + def verify_point(self, frame, var_name, var_typename, x_value, y_value): + v = frame.GetValueForVariablePath(var_name) + self.assertTrue(v.GetError().Success(), "Make sure we find '%s'" % (var_name)) + self.assertTrue(v.GetType().GetName() == var_typename, + "Make sure '%s' has type '%s'" % (var_name, var_typename)) + + if '*' in var_typename: + valid_prefix = var_name + '->' + invalid_prefix = var_name + '.' + else: + valid_prefix = var_name + '.' + invalid_prefix = var_name + '->' + + valid_x_path = valid_prefix + 'x' + valid_y_path = valid_prefix + 'y' + invalid_x_path = invalid_prefix + 'x' + invalid_y_path = invalid_prefix + 'y' + invalid_m_path = invalid_prefix + 'm' + + v = frame.GetValueForVariablePath(valid_x_path) + self.assertTrue(v.GetError().Success(), "Make sure we find '%s'" % (valid_x_path)) + self.assertTrue(v.GetValue() == str(x_value), "Make sure '%s' has a value of %i" % (valid_x_path, x_value)) + self.assertTrue(v.GetType().GetName() == "int", "Make sure '%s' has type 'int'" % (valid_x_path)) + v = frame.GetValueForVariablePath(invalid_x_path) + self.assertTrue(v.GetError().Fail(), "Make sure we don't find '%s'" % (invalid_x_path)) + + v = frame.GetValueForVariablePath(valid_y_path) + self.assertTrue(v.GetError().Success(), "Make sure we find '%s'" % (valid_y_path)) + self.assertTrue(v.GetValue() == str(y_value), "Make sure '%s' has a value of %i" % (valid_y_path, y_value)) + self.assertTrue(v.GetType().GetName() == "int", "Make sure '%s' has type 'int'" % (valid_y_path)) + v = frame.GetValueForVariablePath(invalid_y_path) + self.assertTrue(v.GetError().Fail(), "Make sure we don't find '%s'" % (invalid_y_path)) + + v = frame.GetValueForVariablePath(invalid_m_path) + self.assertTrue(v.GetError().Fail(), "Make sure we don't find '%s'" % (invalid_m_path)) + + def do_test(self): + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Set a breakpoint here", lldb.SBFileSpec("main.cpp")) + + frame = thread.GetFrameAtIndex(0) + v = frame.GetValueForVariablePath('no_such_variable') + self.assertTrue(v.GetError().Fail(), "Make sure we don't find 'no_such_variable'") + + # Test an instance + self.verify_point(frame, 'pt', 'Point', 1, 2) + # Test a pointer + self.verify_point(frame, 'pt_ptr', 'Point *', 3030, 4040) + # Test using a pointer as an array + self.verify_point(frame, 'pt_ptr[-1]', 'Point', 1010, 2020) + self.verify_point(frame, 'pt_ptr[0]', 'Point', 3030, 4040) + self.verify_point(frame, 'pt_ptr[1]', 'Point', 5050, 6060) + # Test arrays + v = frame.GetValueForVariablePath('points') + self.assertTrue(v.GetError().Success(), + "Make sure we find 'points'") + self.verify_point(frame, 'points[0]', 'Point', 1010, 2020) + self.verify_point(frame, 'points[1]', 'Point', 3030, 4040) + self.verify_point(frame, 'points[2]', 'Point', 5050, 6060) + # Test a reference + self.verify_point(frame, 'pt_ref', 'Point &', 1, 2) + v = frame.GetValueForVariablePath('pt_sp') + self.assertTrue(v.GetError().Success(), "Make sure we find 'pt_sp'") + # Make sure we don't crash when looking for non existant child + # in type with synthetic children. This used to cause a crash. + v = frame.GetValueForVariablePath('pt_sp->not_valid_child') + self.assertTrue(v.GetError().Fail(), + "Make sure we don't find 'pt_sp->not_valid_child'") + + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/var_path/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/var_path/main.cpp new file mode 100644 index 00000000000..0ea19cfcfea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/var_path/main.cpp @@ -0,0 +1,15 @@ +#include <memory> + +struct Point { + int x, y; +}; + +int main() { + Point pt = { 1, 2 }; + Point points[] = {{1010,2020}, {3030,4040}, {5050,6060}}; + Point *pt_ptr = &points[1]; + Point &pt_ref = pt; + std::shared_ptr<Point> pt_sp(new Point{111,222}); + return 0; // Set a breakpoint here +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/wrong_commands/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/wrong_commands/.categories new file mode 100644 index 00000000000..3a3f4df6416 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/wrong_commands/.categories @@ -0,0 +1 @@ +cmdline diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/wrong_commands/TestWrongCommands.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/wrong_commands/TestWrongCommands.py new file mode 100644 index 00000000000..c722840b28f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/functionalities/wrong_commands/TestWrongCommands.py @@ -0,0 +1,36 @@ +""" +Test how lldb reacts to wrong commands +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class UnknownCommandTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test + def test_ambiguous_command(self): + command_interpreter = self.dbg.GetCommandInterpreter() + self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER) + result = lldb.SBCommandReturnObject() + + command_interpreter.HandleCommand("g", result) + self.assertFalse(result.Succeeded()) + self.assertRegexpMatches(result.GetError(), "Ambiguous command 'g'. Possible matches:") + self.assertRegexpMatches(result.GetError(), "gui") + self.assertRegexpMatches(result.GetError(), "gdb-remote") + self.assertEquals(1, result.GetError().count("gdb-remote")) + + @no_debug_info_test + def test_unknown_command(self): + command_interpreter = self.dbg.GetCommandInterpreter() + self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER) + result = lldb.SBCommandReturnObject() + + command_interpreter.HandleCommand("qbert", result) + self.assertFalse(result.Succeeded()) + self.assertEquals(result.GetError(), "error: 'qbert' is not a valid command.\n") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/iohandler/completion/TestIOHandlerCompletion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/iohandler/completion/TestIOHandlerCompletion.py new file mode 100644 index 00000000000..610bf019436 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/iohandler/completion/TestIOHandlerCompletion.py @@ -0,0 +1,56 @@ +""" +Test completion in our IOHandlers. +""" + +import os + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test.lldbpexpect import PExpectTest + +class IOHandlerCompletionTest(PExpectTest): + + mydir = TestBase.compute_mydir(__file__) + + # PExpect uses many timeouts internally and doesn't play well + # under ASAN on a loaded machine.. + @skipIfAsan + @skipIfEditlineSupportMissing + def test_completion(self): + self.launch(dimensions=(100,500)) + + # Start tab completion, go to the next page and then display all with 'a'. + self.child.send("\t\ta") + self.child.expect_exact("register") + + # Try tab completing regi to register. + self.child.send("regi\t") + self.child.expect_exact(self.PROMPT + "register") + self.child.send("\n") + self.expect_prompt() + + # Try tab completing directories and files. Also tests the partial + # completion where LLDB shouldn't print a space after the directory + # completion (as it didn't completed the full token). + dir_without_slashes = os.path.realpath(os.path.dirname(__file__)).rstrip("/") + self.child.send("file " + dir_without_slashes + "\t") + self.child.expect_exact("iohandler/completion/") + # If we get a correct partial completion without a trailing space, then this + # should complete the current test file. + self.child.send("TestIOHandler\t") + self.child.expect_exact("TestIOHandlerCompletion.py") + self.child.send("\n") + self.expect_prompt() + + # Start tab completion and abort showing more commands with 'n'. + self.child.send("\t") + self.child.expect_exact("More (Y/n/a)") + self.child.send("n") + self.expect_prompt() + + # Shouldn't crash or anything like that. + self.child.send("regoinvalid\t") + self.expect_prompt() + + self.quit() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/iohandler/completion/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/iohandler/completion/main.c new file mode 100644 index 00000000000..03350dd8299 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/iohandler/completion/main.c @@ -0,0 +1,5 @@ +int main(int argc, char **argv) { + lldb_enable_attach(); + int to_complete = 0; + return to_complete; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/iohandler/unicode/TestUnicode.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/iohandler/unicode/TestUnicode.py new file mode 100644 index 00000000000..c8ff9a6ab32 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/iohandler/unicode/TestUnicode.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +""" +Test unicode handling in LLDB. +""" + +import os + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test.lldbpexpect import PExpectTest + +class TestCase(PExpectTest): + + mydir = TestBase.compute_mydir(__file__) + + # PExpect uses many timeouts internally and doesn't play well + # under ASAN on a loaded machine.. + @skipIfAsan + def test_unicode_input(self): + self.launch() + + # Send some unicode input to LLDB. + # We should get back that this is an invalid command with our character as UTF-8. + self.expect(u'\u1234', substrs=[u"error: '\u1234' is not a valid command.".encode('utf-8')]) + + self.quit() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/README.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/README.txt new file mode 100644 index 00000000000..0f1ae7f0ecf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/README.txt @@ -0,0 +1,5 @@ +Tests in this directory are intentionally setup to +fail, error, timeout, etc. to verify that the buildbots +pick up errors. The tests in this directory will be +parked/removed/renamed after verifying they trigger +as expected. diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestExpectedTimeout.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestExpectedTimeout.py.park new file mode 100644 index 00000000000..67db8149f85 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestExpectedTimeout.py.park @@ -0,0 +1,20 @@ +"""Tests that a timeout is detected by the testbot.""" +from __future__ import print_function + +import time + +import lldbsuite.test.lldbtest as lldbtest + + +class ExpectedTimeoutTestCase(lldbtest.TestBase): + """Forces test timeout.""" + mydir = lldbtest.TestBase.compute_mydir(__file__) + + @lldbtest.expectedFailureAll() + def test_buildbot_sees_expected_timeout(self): + """Tests that expected timeout logic kicks in and is picked up.""" + while True: + try: + time.sleep(1) + except: + print("ignoring exception during sleep") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestFail.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestFail.py.park new file mode 100644 index 00000000000..fcdba39d7fe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestFail.py.park @@ -0,0 +1,15 @@ +"""Tests that a FAIL is detected by the testbot.""" + + +import lldbsuite.test.lldbtest as lldbtest + + +class FailTestCase(lldbtest.TestBase): + """Forces test failure.""" + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def test_buildbot_catches_failure(self): + """Issues a failing test assertion.""" + self.assertTrue( + False, + "This will always fail, buildbot should flag this.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestInvalidDecorator.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestInvalidDecorator.py.park new file mode 100644 index 00000000000..d5c8c58506f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestInvalidDecorator.py.park @@ -0,0 +1,12 @@ +from lldbsuite.test import lldbtest +from lldbsuite.test import decorators + + +class NonExistentDecoratorTestCase(lldbtest.TestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + @decorators.nonExistentDecorator(bugnumber="yt/1300") + def test(self): + """Verify non-existent decorators are picked up by test runner.""" + pass diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunFail.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunFail.py.park new file mode 100644 index 00000000000..8d1fc95502a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunFail.py.park @@ -0,0 +1,22 @@ +"""Tests that a flakey fail is rerun, and will pass on the rerun. +Run this test with --rerun-all-issues specified to test that +the tests fail on the first run, then pass on the second. +Do not mark them as flakey as, at this time, flakey tests will +run twice, thus causing the second run to succeed.""" + + +import rerun_base + +import lldbsuite.test.lldbtest as lldbtest + + +class RerunFailTestCase(rerun_base.RerunBaseTestCase): + """Forces test failure on first run, success on rerun.""" + @lldbtest.no_debug_info_test + def test_buildbot_catches_failure(self): + """Issues a failing test assertion.""" + if self.should_generate_issue(): + self.assertTrue( + False, + "This will fail on the first call, succeed on rerun, and " + "alternate thereafter.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunFileLevelTimeout.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunFileLevelTimeout.py.park new file mode 100644 index 00000000000..9422624207c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunFileLevelTimeout.py.park @@ -0,0 +1,33 @@ +"""Tests that a timeout is detected by the testbot.""" +from __future__ import print_function + +import atexit +import time + +from lldbsuite.test import decorators +import rerun_base + + +class RerunTimeoutTestCase(rerun_base.RerunBaseTestCase): + def maybe_do_timeout(self): + # Do the timeout here if we're going to time out. + if self.should_generate_issue(): + # We time out this time. + while True: + try: + time.sleep(1) + except: + print("ignoring exception during sleep") + + # call parent + super(RerunTimeoutTestCase, self).tearDown() + + @decorators.no_debug_info_test + def test_timeout_file_level_timeout_rerun_succeeds(self): + """Tests that file-level timeout is cleared on rerun.""" + + # This test just needs to pass. It is the exit hook (outside + # the test method) that will time out. + + # Add the exit handler that will time out the first time around. + atexit.register(RerunTimeoutTestCase.maybe_do_timeout, self) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunInline.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunInline.py.park new file mode 100644 index 00000000000..4c50495a2ec --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunInline.py.park @@ -0,0 +1,13 @@ +"""Tests that the rerun mechanism respects lldbinline-created tests. + +The current implementation of this test is expected to fail both on +the initial run and on the rerun, assuming --rerun-all-issues is provided +to the dotest.py run. + +This test could be improved by doing something in the test inferior +C++ program that could look for the "should an issue be raised" marker +file, and then really pass on the rerun. +""" +import lldbsuite.test.lldbinline as lldbinline + +lldbinline.MakeInlineTest(__file__, globals()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunTimeout.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunTimeout.py.park new file mode 100644 index 00000000000..a8f5542ae2f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestRerunTimeout.py.park @@ -0,0 +1,24 @@ +"""Tests that a timeout is detected by the testbot.""" +from __future__ import print_function + +import time + +import lldbsuite.test.decorators as decorators +import rerun_base + + +class RerunTimeoutTestCase(rerun_base.RerunBaseTestCase): + @decorators.no_debug_info_test + def test_timeout_rerun_succeeds(self): + """Tests that the timeout logic kicks in and that this timeout is picked up.""" + if not self.should_generate_issue(): + # We pass this time. + return + + # We time out this time. + while True: + # noinspection PyBroadException + try: + time.sleep(1) + except: + print("ignoring exception during sleep") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestSignal.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestSignal.py.park new file mode 100644 index 00000000000..5a34c096201 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestSignal.py.park @@ -0,0 +1,25 @@ +"""Tests that an exceptional exit is detected by the testbot.""" + + +import os +import signal +import time + +import lldbsuite.test.lldbtest as lldbtest + + +class ExceptionalExitTestCase(lldbtest.TestBase): + """Forces exceptional exit.""" + mydir = lldbtest.TestBase.compute_mydir(__file__) + + @lldbtest.skipIfWindows + def test_buildbot_catches_exceptional_exit(self): + """Force process to die with exceptional exit.""" + + # Sleep for a couple seconds + try: + time.sleep(5) + except: + pass + + os.kill(os.getpid(), signal.SIGKILL) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestSignalOutsideTestMethod.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestSignalOutsideTestMethod.py.park new file mode 100644 index 00000000000..425c5fe9077 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestSignalOutsideTestMethod.py.park @@ -0,0 +1,23 @@ +"""Tests that an exceptional exit is detected by the testbot.""" + + +import atexit +import os +import signal +import time + +import lldbsuite.test.lldbtest as lldbtest + + +class ExceptionalExitOutOfTestMethodTestCase(lldbtest.TestBase): + """Forces exceptional exit.""" + mydir = lldbtest.TestBase.compute_mydir(__file__) + + @lldbtest.skipIfWindows + def test_buildbot_catches_exceptional_exit(self): + pass + +def cleanup(): + os.kill(os.getpid(), signal.SIGKILL) + +atexit.register(cleanup) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestTimeout.py.park b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestTimeout.py.park new file mode 100644 index 00000000000..ba7be454f9a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/TestTimeout.py.park @@ -0,0 +1,19 @@ +"""Tests that a timeout is detected by the testbot.""" +from __future__ import print_function + +import time + +import lldbsuite.test.lldbtest as lldbtest + + +class TimeoutTestCase(lldbtest.TestBase): + """Forces test timeout.""" + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def test_buildbot_catches_timeout(self): + """Tests that timeout logic kicks in and is picked up.""" + while True: + try: + time.sleep(1) + except: + print("ignoring exception during sleep") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/disable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/disable.py new file mode 100755 index 00000000000..6d1f93e8b15 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/disable.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +"""Renames *.py files to *.py.park.""" +import os +import sys + + +def main(): + """Drives the main script behavior.""" + script_dir = os.path.dirname(os.path.realpath(__file__)) + for filename in os.listdir(script_dir): + basename, extension = os.path.splitext(filename) + if basename.startswith("Test") and extension == '.py': + source_path = os.path.join(script_dir, filename) + dest_path = source_path + ".park" + sys.stdout.write("renaming {} to {}\n".format( + source_path, dest_path)) + os.rename(source_path, dest_path) + +if __name__ == "__main__": + main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/enable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/enable.py new file mode 100755 index 00000000000..eb19276de1f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/enable.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +"""Renames *.py.park files to *.py.""" +import os +import sys + + +def main(): + """Drives the main script behavior.""" + script_dir = os.path.dirname(os.path.realpath(__file__)) + for filename in os.listdir(script_dir): + basename, extension = os.path.splitext(filename) + if basename.startswith("Test") and extension == '.park': + source_path = os.path.join(script_dir, filename) + dest_path = os.path.join(script_dir, basename) + sys.stdout.write("renaming {} to {}\n".format( + source_path, dest_path)) + os.rename(source_path, dest_path) + +if __name__ == "__main__": + main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/inline_rerun_inferior.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/inline_rerun_inferior.cpp new file mode 100644 index 00000000000..6d1e0236056 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/inline_rerun_inferior.cpp @@ -0,0 +1,13 @@ +//===-- main.cpp --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +typedef int Foo; + +int main() { + Foo array[3] = {1,2,3}; + return 0; //% self.expect("frame variable array --show-types --", substrs = ['(Foo [3]) wrong_type_here = {','(Foo) [0] = 1','(Foo) [1] = 2','(Foo) [2] = 3']) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/rerun_base.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/rerun_base.py new file mode 100644 index 00000000000..909b93b134c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/issue_verification/rerun_base.py @@ -0,0 +1,27 @@ + +import os + +import lldbsuite.test.lldbtest as lldbtest + + +# pylint: disable=too-few-public-methods +class RerunBaseTestCase(lldbtest.TestBase): + """Forces test failure.""" + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def should_generate_issue(self): + """Returns whether a test issue should be generated. + + @returns True on the first and every other call via a given + test method. + """ + should_pass_filename = "{}.{}.succeed-marker".format( + __file__, self.id()) + fail = not os.path.exists(should_pass_filename) + if fail: + # Create the marker so that next call to this passes. + open(should_pass_filename, 'w').close() + else: + # Delete the marker so next time we fail. + os.remove(should_pass_filename) + return fail diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py new file mode 100644 index 00000000000..69e23e3510b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py @@ -0,0 +1,170 @@ +"""Test that anonymous structs/unions are transparent to member access""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class AnonymousTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf( + compiler="icc", + bugnumber="llvm.org/pr15036: LLDB generates an incorrect AST layout for an anonymous struct when DWARF is generated by ICC") + def test_expr_nest(self): + self.build() + self.common_setup(self.line0) + + # These should display correctly. + self.expect("expression n->foo.d", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 4"]) + + self.expect("expression n->b", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 2"]) + + def test_expr_child(self): + self.build() + self.common_setup(self.line1) + + # These should display correctly. + self.expect("expression c->foo.d", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 4"]) + + self.expect( + "expression c->grandchild.b", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 2"]) + + @skipIf( + compiler="icc", + bugnumber="llvm.org/pr15036: This particular regression was introduced by r181498") + def test_expr_grandchild(self): + self.build() + self.common_setup(self.line2) + + # These should display correctly. + self.expect("expression g.child.foo.d", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 4"]) + + self.expect("expression g.child.b", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 2"]) + + def test_expr_parent(self): + self.build() + if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): + self.skipTest( + "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") + self.common_setup(self.line2) + + # These should display correctly. + self.expect("expression pz", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["(type_z *) $", " = 0x0000"]) + + self.expect("expression z.y", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["(type_y) $", "dummy = 2"]) + + def test_expr_null(self): + self.build() + self.common_setup(self.line2) + + # This should fail because pz is 0, but it succeeds on OS/X. + # This fails on Linux with an upstream error "Couldn't dematerialize struct", as does "p *n" with "int *n = 0". + # Note that this can also trigger llvm.org/pr15036 when run + # interactively at the lldb command prompt. + self.expect("expression *(type_z *)pz", error=True) + + def test_child_by_name(self): + self.build() + + # Set debugger into synchronous mode + self.dbg.SetAsync(False) + + # Create a target + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + break_in_main = target.BreakpointCreateBySourceRegex( + '// Set breakpoint 2 here.', lldb.SBFileSpec(self.source)) + self.assertTrue(break_in_main, VALID_BREAKPOINT) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_main) + if len(threads) != 1: + self.fail("Failed to stop at breakpoint in main.") + + thread = threads[0] + frame = thread.frames[0] + + if not frame.IsValid(): + self.fail("Failed to get frame 0.") + + var_n = frame.FindVariable("n") + if not var_n.IsValid(): + self.fail("Failed to get the variable 'n'") + + elem_a = var_n.GetChildMemberWithName("a") + if not elem_a.IsValid(): + self.fail("Failed to get the element a in n") + + error = lldb.SBError() + value = elem_a.GetValueAsSigned(error, 1000) + if not error.Success() or value != 0: + self.fail("failed to get the correct value for element a in n") + + def test_nest_flat(self): + self.build() + self.common_setup(self.line2) + + # These should display correctly. + self.expect('frame variable n --flat', + substrs=['n.a = 0', + 'n.b = 2', + 'n.foo.c = 0', + 'n.foo.d = 4']) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break in main.c. + self.source = 'main.c' + self.line0 = line_number(self.source, '// Set breakpoint 0 here.') + self.line1 = line_number(self.source, '// Set breakpoint 1 here.') + self.line2 = line_number(self.source, '// Set breakpoint 2 here.') + + def common_setup(self, line): + + # Set debugger into synchronous mode + self.dbg.SetAsync(False) + + # Create a target + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set breakpoints inside and outside methods that take pointers to the + # containing struct. + lldbutil.run_break_set_by_file_and_line( + self, self.source, line, num_expected_locations=1, loc_exact=True) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/main.c new file mode 100644 index 00000000000..58ac85b7d43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/anonymous/main.c @@ -0,0 +1,82 @@ +#include <stdio.h> + +struct anonymous_nest { + struct { + struct { + int a; + int b; + }; // anonymous + struct { + int c; + int d; + } foo; + }; // anonymous +}; + +struct anonymous_child { + struct { + struct { + int a; + int b; + } grandchild; + struct { + int c; + int d; + } foo; + }; // anonymous +}; + +struct anonymous_grandchild { + struct { + struct { + int a; + int b; + }; // anonymous + struct { + int c; + int d; + } foo; + } child; +}; + +int processor_nest (struct anonymous_nest *n) +{ + return n->foo.d + n->b; // Set breakpoint 0 here. +} + +int processor_child (struct anonymous_child *c) +{ + return c->foo.d + c->grandchild.b; // Set breakpoint 1 here. +} + +int processor_grandchild (struct anonymous_grandchild *g) +{ + return g->child.foo.d + g->child.b; +} + + + +typedef struct { + int dummy; +} type_y; + +typedef struct { + type_y y; +} type_z; + + + +int main() +{ + struct anonymous_nest n = { 0, 2, 0, 4 }; + struct anonymous_child c = { 0, 2, 0, 4 }; + struct anonymous_grandchild g = { 0, 2, 0, 4 }; + type_z *pz = 0; + type_z z = {{2}}; + + printf("%d\n", processor_nest(&n)); + printf("%d\n", processor_child(&c)); + printf("%d\n", processor_grandchild(&g)); // Set breakpoint 2 here. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py new file mode 100644 index 00000000000..cc9ae8edb6e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py @@ -0,0 +1,228 @@ +"""Test breakpoint by file/line number; and list variables with array types.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ArrayTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # 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.') + + def test_and_run_command(self): + """Test 'frame variable var_name' on some variables with array types.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=False) + + self.runCmd("run", RUN_SUCCEEDED) + + # The test suite sometimes shows that the process has exited without stopping. + # + # CC=clang ./dotest.py -v -t array_types + # ... + # Process 76604 exited with status = 0 (0x00000000) + self.runCmd("process status") + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=['resolved, hit count = 1']) + + # Issue 'variable list' command on several array-type variables. + + self.expect( + "frame variable --show-types strings", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(char *[4])', + substrs=[ + '(char *) [0]', + '(char *) [1]', + '(char *) [2]', + '(char *) [3]', + 'Hello', + 'Hola', + 'Bonjour', + 'Guten Tag']) + + self.expect( + "frame variable --show-types --raw -- char_16", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(char) [0]', + '(char) [15]']) + + self.expect( + "frame variable --show-types ushort_matrix", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(unsigned short [2][3])') + + self.expect( + "frame variable --show-types long_6", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(long [6])') + + @expectedFailureNetBSD + @add_test_categories(['pyapi']) + def test_and_python_api(self): + """Use Python APIs to inspect variables with array types.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.c", self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Sanity check the print representation of breakpoint. + bp = str(breakpoint) + self.expect(bp, msg="Breakpoint looks good", exe=False, + substrs=["file = 'main.c'", + "line = %d" % self.line, + "locations = 1"]) + self.expect( + bp, + msg="Breakpoint is not resolved as yet", + exe=False, + matching=False, + substrs=["resolved = 1"]) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Sanity check the print representation of process. + proc = str(process) + self.expect(proc, msg="Process looks good", exe=False, + substrs=["state = stopped", + "executable = a.out"]) + + # The stop reason of the thread should be breakpoint. + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # Sanity check the print representation of thread. + thr = str(thread) + # TODO(zturner): Whether the TID is printed in hex or decimal should be controlled by a setting, + # and this test should read the value of the setting. This check is currently hardcoded to + # match the check in Core/FormatEntity.cpp in the function FormatEntity::Format() for + # the Entry::Type::ThreadID case of the switch statement. + if self.getPlatform() == "linux" or self.getPlatform() == "freebsd": + tidstr = "tid = %u" % thread.GetThreadID() + else: + tidstr = "tid = 0x%4.4x" % thread.GetThreadID() + self.expect( + thr, + "Thread looks good with stop reason = breakpoint", + exe=False, + substrs=[tidstr]) + + # The breakpoint should have a hit count of 1. + self.assertEqual(breakpoint.GetHitCount(), 1, BREAKPOINT_HIT_ONCE) + + # The breakpoint should be resolved by now. + bp = str(breakpoint) + self.expect(bp, "Breakpoint looks good and is resolved", exe=False, + substrs=["file = 'main.c'", + "line = %d" % self.line, + "locations = 1"]) + + # Sanity check the print representation of frame. + frame = thread.GetFrameAtIndex(0) + frm = str(frame) + self.expect( + frm, + "Frame looks good with correct index %d" % + frame.GetFrameID(), + exe=False, + substrs=[ + "#%d" % + frame.GetFrameID()]) + + # Lookup the "strings" string array variable and sanity check its print + # representation. + variable = frame.FindVariable("strings") + var = str(variable) + self.expect( + var, + "Variable for 'strings' looks good with correct name", + exe=False, + substrs=[ + "%s" % + variable.GetName()]) + self.DebugSBValue(variable) + self.assertTrue(variable.GetNumChildren() == 4, + "Variable 'strings' should have 4 children") + byte_size = variable.GetByteSize() + self.assertTrue(byte_size >= 4*4 and byte_size <= 1024) + + child3 = variable.GetChildAtIndex(3) + self.DebugSBValue(child3) + self.assertTrue(child3.GetSummary() == '"Guten Tag"', + 'strings[3] == "Guten Tag"') + + # Lookup the "char_16" char array variable. + variable = frame.FindVariable("char_16") + self.DebugSBValue(variable) + self.assertTrue(variable.GetNumChildren() == 16, + "Variable 'char_16' should have 16 children") + + # Lookup the "ushort_matrix" ushort[] array variable. + # Notice the pattern of int(child0_2.GetValue(), 0). We pass a + # base of 0 so that the proper radix is determined based on the contents + # of the string. Same applies to long(). + variable = frame.FindVariable("ushort_matrix") + self.DebugSBValue(variable) + self.assertTrue(variable.GetNumChildren() == 2, + "Variable 'ushort_matrix' should have 2 children") + child0 = variable.GetChildAtIndex(0) + self.DebugSBValue(child0) + self.assertTrue(child0.GetNumChildren() == 3, + "Variable 'ushort_matrix[0]' should have 3 children") + child0_2 = child0.GetChildAtIndex(2) + self.DebugSBValue(child0_2) + self.assertTrue(int(child0_2.GetValue(), 0) == 3, + "ushort_matrix[0][2] == 3") + + # Lookup the "long_6" char array variable. + variable = frame.FindVariable("long_6") + self.DebugSBValue(variable) + self.assertTrue(variable.GetNumChildren() == 6, + "Variable 'long_6' should have 6 children") + child5 = variable.GetChildAtIndex(5) + self.DebugSBValue(child5) + self.assertTrue(int(child5.GetValue(), 0) == 6, + "long_6[5] == 6") + + # Last, check that "long_6" has a value type of eValueTypeVariableLocal + # and "argc" has eValueTypeVariableArgument. + from lldbsuite.test.lldbutil import value_type_to_str + self.assertTrue( + variable.GetValueType() == lldb.eValueTypeVariableLocal, + "Variable 'long_6' should have '%s' value type." % + value_type_to_str( + lldb.eValueTypeVariableLocal)) + argc = frame.FindVariable("argc") + self.DebugSBValue(argc) + self.assertTrue(argc.GetValueType() == lldb.eValueTypeVariableArgument, + "Variable 'argc' should have '%s' value type." % + value_type_to_str(lldb.eValueTypeVariableArgument)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/cmds.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/cmds.txt new file mode 100644 index 00000000000..8feebe21204 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/cmds.txt @@ -0,0 +1,3 @@ +break main.c:42 +continue +var diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/main.c new file mode 100644 index 00000000000..eda7dc3d6ac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/array_types/main.c @@ -0,0 +1,50 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +int main (int argc, char const *argv[]) +{ + struct point_tag { + int x; + int y; + }; + + struct rect_tag { + struct point_tag bottom_left; + struct point_tag top_right; + }; + char char_16[16] = "Hello World\n"; + char *strings[] = { "Hello", "Hola", "Bonjour", "Guten Tag" }; + char char_matrix[3][3] = {{'a', 'b', 'c' }, {'d', 'e', 'f' }, {'g', 'h', 'i' }}; + char char_matrix_matrix[3][2][3] = + { {{'a', 'b', 'c' }, {'d', 'e', 'f' }}, + {{'A', 'B', 'C' }, {'D', 'E', 'F' }}, + {{'1', '2', '3' }, {'4', '5', '6' }}}; + short short_4[4] = { 1,2,3,4 }; + short short_matrix[1][2] = { {1,2} }; + unsigned short ushort_4[4] = { 1,2,3,4 }; + unsigned short ushort_matrix[2][3] = { + { 1, 2, 3}, + {11,22,33} + }; + int int_2[2] = { 1, 2 }; + unsigned int uint_2[2] = { 1, 2 }; + long long_6[6] = { 1, 2, 3, 4, 5, 6 }; + unsigned long ulong_6[6] = { 1, 2, 3, 4, 5, 6 }; + struct point_tag points_2[2] = { + {1,2}, + {3,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}} + }; + struct rect_tag rects_2[2] = { + {{1,2}, {3,4}}, + {{5,6}, {7,8}} + }; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py new file mode 100644 index 00000000000..7b28a321ff6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py @@ -0,0 +1,220 @@ +"""Show bitfields and check that they display correctly.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BitfieldsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # 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.') + + # BitFields exhibit crashes in record layout on Windows + # (http://llvm.org/pr21800) + @skipIfWindows + def test_and_run_command(self): + """Test 'frame variable ...' on a variable with bitfields.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the main. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # This should display correctly. + self.expect( + "frame variable --show-types bits", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(uint32_t:1) b1 = 1', + '(uint32_t:2) b2 = 3', + '(uint32_t:3) b3 = 7', + '(uint32_t) 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 --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(uint32_t:1) b1 = 1', + '(uint32_t:2) b2 = 3', + '(uint32_t:3) b3 = 7', + '(uint32_t) b4 = 15', + '(uint32_t:5) b5 = 31', + '(uint32_t:6) b6 = 63', + '(uint32_t:7) b7 = 127', + '(uint32_t:4) four = 15']) + + self.expect("expr (bits.b1)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', '1']) + self.expect("expr (bits.b2)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', '3']) + self.expect("expr (bits.b3)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', '7']) + self.expect("expr (bits.b4)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', '15']) + self.expect("expr (bits.b5)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', '31']) + self.expect("expr (bits.b6)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', '63']) + self.expect("expr (bits.b7)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', '127']) + self.expect("expr (bits.four)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', '15']) + + self.expect( + "frame variable --show-types more_bits", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(uint32_t:3) a = 3', + '(uint8_t:1) b = \'\\0\'', + '(uint8_t:1) c = \'\\x01\'', + '(uint8_t:1) d = \'\\0\'']) + + self.expect("expr (more_bits.a)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', '3']) + self.expect("expr (more_bits.b)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint8_t', '\\0']) + self.expect("expr (more_bits.c)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint8_t', '\\x01']) + self.expect("expr (more_bits.d)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint8_t', '\\0']) + + self.expect("expr (packed.a)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['char', "'a'"]) + self.expect("expr (packed.b)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', "10"]) + self.expect("expr/x (packed.c)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint32_t', "7112233"]) + + for bit in range(1,18): + expected = "1" if bit in [1, 5, 7, 13] else "0" + self.expect("expr even_more_bits.b" + str(bit), VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint8_t', expected]) + + for bit in [3, 10, 14]: + self.expect("expr even_more_bits.b" + str(bit) + " = 1", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint8_t', "1"]) + + self.expect( + "frame variable --show-types even_more_bits", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(uint8_t:1) b1 = \'\\x01\'', + '(uint8_t:1) b2 = \'\\0\'', + '(uint8_t:1) b3 = \'\\x01\'', + '(uint8_t:1) b4 = \'\\0\'', + '(uint8_t:1) b5 = \'\\x01\'', + '(uint8_t:1) b6 = \'\\0\'', + '(uint8_t:1) b7 = \'\\x01\'', + '(uint8_t:1) b8 = \'\\0\'', + '(uint8_t:1) b9 = \'\\0\'', + '(uint8_t:1) b10 = \'\\x01\'', + '(uint8_t:1) b12 = \'\\0\'', + '(uint8_t:1) b13 = \'\\x01\'', + '(uint8_t:1) b14 = \'\\x01\'', + '(uint8_t:1) b15 = \'\\0\'', + '(uint8_t:1) b16 = \'\\0\'', + '(uint8_t:1) b17 = \'\\0\'', + ]) + + self.expect("v/x large_packed", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["a = 0x0000000cbbbbaaaa", "b = 0x0000000dffffeee"]) + + + @add_test_categories(['pyapi']) + # BitFields exhibit crashes in record layout on Windows + # (http://llvm.org/pr21800) + @skipIfWindows + def test_and_python_api(self): + """Use Python APIs to inspect a bitfields variable.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.c", self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # The breakpoint should have a hit count of 1. + self.assertEqual(breakpoint.GetHitCount(), 1, BREAKPOINT_HIT_ONCE) + + # Lookup the "bits" variable which contains 8 bitfields. + frame = thread.GetFrameAtIndex(0) + bits = frame.FindVariable("bits") + self.DebugSBValue(bits) + self.assertTrue( + bits.GetTypeName() == 'Bits', + "bits.GetTypeName() == 'Bits'") + self.assertTrue( + bits.GetNumChildren() == 10, + "bits.GetNumChildren() == 10") + test_compiler = self.getCompiler() + self.assertTrue(bits.GetByteSize() == 32, "bits.GetByteSize() == 32") + + # Notice the pattern of int(b1.GetValue(), 0). We pass a base of 0 + # so that the proper radix is determined based on the contents of the + # string. + b1 = bits.GetChildMemberWithName("b1") + self.DebugSBValue(b1) + self.assertTrue(b1.GetName() == "b1" and + b1.GetTypeName() == "uint32_t:1" and + b1.IsInScope() and + int(b1.GetValue(), 0) == 1, + 'bits.b1 has type uint32_t:1, is in scope, and == 1') + + b7 = bits.GetChildMemberWithName("b7") + self.DebugSBValue(b7) + self.assertTrue(b7.GetName() == "b7" and + b7.GetTypeName() == "uint32_t:7" and + b7.IsInScope() and + int(b7.GetValue(), 0) == 127, + 'bits.b7 has type uint32_t:7, is in scope, and == 127') + + four = bits.GetChildMemberWithName("four") + self.DebugSBValue(four) + self.assertTrue(four.GetName() == "four" and + four.GetTypeName() == "uint32_t:4" and + four.IsInScope() and + int(four.GetValue(), 0) == 15, + 'bits.four has type uint32_t:4, is in scope, and == 15') + + # Now kill the process, and we are done. + rc = target.GetProcess().Kill() + self.assertTrue(rc.Success()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/main.c new file mode 100644 index 00000000000..be3a1af76ba --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/bitfields/main.c @@ -0,0 +1,103 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdint.h> +#include <stdio.h> +#include <string.h> + +int main (int argc, char const *argv[]) +{ + struct Bits + { + uint32_t : 1, // Unnamed bitfield + b1 : 1, + b2 : 2, + : 2, // Unnamed bitfield + b3 : 3, + : 2, // Unnamed bitfield (this will get removed) + b4 __attribute__ ((aligned(16))), + b5 : 5, + b6 : 6, + b7 : 7, + four : 4; + }; + + printf("%lu", sizeof(struct Bits)); + + struct Bits bits; + int i; + for (i=0; i<(1<<1); i++) + bits.b1 = i; //// break $source:$line + for (i=0; i<(1<<2); i++) + bits.b2 = i; //// break $source:$line + for (i=0; i<(1<<3); i++) + bits.b3 = i; //// break $source:$line + for (i=0; i<(1<<4); i++) + bits.b4 = i; //// break $source:$line + for (i=0; i<(1<<5); i++) + bits.b5 = i; //// break $source:$line + for (i=0; i<(1<<6); i++) + bits.b6 = i; //// break $source:$line + for (i=0; i<(1<<7); i++) + bits.b7 = i; //// break $source:$line + for (i=0; i<(1<<4); i++) + bits.four = i; //// break $source:$line + + struct MoreBits + { + uint32_t a : 3; + uint8_t : 1; + uint8_t b : 1; + uint8_t c : 1; + uint8_t d : 1; + }; + + struct MoreBits more_bits; + + more_bits.a = 3; + more_bits.b = 0; + more_bits.c = 1; + more_bits.d = 0; + + struct EvenMoreBits + { + uint8_t b1 : 1, b2 : 1, b3 : 1, b4 : 1, b5 : 1, b6 : 1, + b7 : 1, b8 : 1, b9 : 1, b10 : 1, b11 : 1, b12 : 1, + b13 : 1, b14 : 1, b15 : 1, b16 : 1, b17 : 1; + }; + + struct EvenMoreBits even_more_bits; + memset(&even_more_bits, 0, sizeof(even_more_bits)); + even_more_bits.b1 = 1; + even_more_bits.b5 = 1; + even_more_bits.b7 = 1; + even_more_bits.b13 = 1; + +#pragma pack(1) + struct PackedBits + { + char a; + uint32_t b : 5, + c : 27; + }; +#pragma pack() + struct PackedBits packed; + packed.a = 'a'; + packed.b = 10; + packed.c = 0x7112233; + + struct LargePackedBits { + uint64_t a: 36; + uint64_t b: 36; + } __attribute__((packed)); + + struct LargePackedBits large_packed = + (struct LargePackedBits){ 0xcbbbbaaaa, 0xdffffeeee }; + + return 0; //// Set break point at this line. + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/blocks/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/blocks/Makefile new file mode 100644 index 00000000000..57083c95274 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/blocks/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -fblocks + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py new file mode 100644 index 00000000000..cd82d159248 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py @@ -0,0 +1,81 @@ +"""Test that lldb can invoke blocks and access variables inside them""" + + + +import unittest2 +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil + + +class BlocksTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + lines = [] + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break at. + self.lines.append(line_number('main.c', '// Set breakpoint 0 here.')) + self.lines.append(line_number('main.c', '// Set breakpoint 1 here.')) + + def launch_common(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + self.is_started = False + + # Break inside the foo function which takes a bar_ptr argument. + for line in self.lines: + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) + + self.wait_for_breakpoint() + + @skipUnlessDarwin + def test_expr(self): + self.launch_common() + + self.expect("expression a + b", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 7"]) + + self.expect("expression c", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 1"]) + + self.wait_for_breakpoint() + + # This should display correctly. + self.expect("expression (int)neg (-12)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 12"]) + + @skipUnlessDarwin + def test_define(self): + self.launch_common() + + self.runCmd( + "expression int (^$add)(int, int) = ^int(int a, int b) { return a + b; };") + self.expect( + "expression $add(2,3)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[" = 5"]) + + self.runCmd("expression int $a = 3") + self.expect( + "expression int (^$addA)(int) = ^int(int b) { return $a + b; };", + "Proper error is reported on capture", + error=True) + + def wait_for_breakpoint(self): + if not self.is_started: + self.is_started = True + self.runCmd("process launch", RUN_SUCCEEDED) + else: + self.runCmd("process continue", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/blocks/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/blocks/main.c new file mode 100644 index 00000000000..415e6c6d033 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/blocks/main.c @@ -0,0 +1,21 @@ +#include <stdio.h> + +int main() +{ + int c = 1; + + int (^add)(int, int) = ^int(int a, int b) + { + return a + b + c; // Set breakpoint 0 here. + }; + + int (^neg)(int) = ^int(int a) + { + return -a; + }; + + printf("%d\n", add(3, 4)); + printf("%d\n", neg(-5)); // Set breakpoint 1 here. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Makefile new file mode 100644 index 00000000000..59778ab5d9f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Makefile @@ -0,0 +1,14 @@ +LD_EXTRAS := -L. -LOne -l$(LIB_PREFIX)One -LTwo -l$(LIB_PREFIX)Two +C_SOURCES := main.c + +include Makefile.rules + +.PHONY: +a.out: lib_One lib_Two + +lib_%: + $(MAKE) VPATH=$(SRCDIR)/$* -I $(SRCDIR) -f $(SRCDIR)/$*.mk + +clean:: + $(MAKE) -f $(SRCDIR)/One.mk clean + $(MAKE) -f $(SRCDIR)/Two.mk clean diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One.mk b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One.mk new file mode 100644 index 00000000000..18f3725d22f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One.mk @@ -0,0 +1,8 @@ +DYLIB_NAME := One +DYLIB_C_SOURCES := One.c OneConstant.c +DYLIB_ONLY := YES + +include Makefile.rules + +OneConstant.o: OneConstant.c + $(CC) $(CFLAGS_NO_DEBUG) -c $< -o $@ diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One/One.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One/One.c new file mode 100644 index 00000000000..6bd729f6570 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One/One.c @@ -0,0 +1,6 @@ +#include "One.h" +#include <stdio.h> + +void one() { + printf("One\n"); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One/One.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One/One.h new file mode 100644 index 00000000000..aae27571bb9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One/One.h @@ -0,0 +1,4 @@ +#ifndef ONE_H +#define ONE_H +LLDB_TEST_API void one(); +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One/OneConstant.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One/OneConstant.c new file mode 100644 index 00000000000..8255c2fce99 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/One/OneConstant.c @@ -0,0 +1 @@ +int __attribute__ ((visibility("hidden"))) conflicting_symbol = 11111; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/TestConflictingSymbol.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/TestConflictingSymbol.py new file mode 100644 index 00000000000..9d088e308ed --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/TestConflictingSymbol.py @@ -0,0 +1,122 @@ +"""Test that conflicting symbols in different shared libraries work correctly""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestConflictingSymbols(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + TestBase.setUp(self) + lldbutil.mkdir_p(self.getBuildArtifact("One")) + lldbutil.mkdir_p(self.getBuildArtifact("Two")) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489") + @expectedFailureNetBSD + def test_conflicting_symbols(self): + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, ['One', 'Two']) + + lldbutil.run_break_set_by_source_regexp(self, '// break here', + extra_options='-f One.c', num_expected_locations=-2) + lldbutil.run_break_set_by_source_regexp(self, '// break here', + extra_options='-f Two.c', num_expected_locations=-2) + lldbutil.run_break_set_by_source_regexp(self, '// break here', + extra_options='-f main.c', num_expected_locations=1) + + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # This should display correctly. + self.expect( + "expr (unsigned long long)conflicting_symbol", + "Symbol from One should be found", + substrs=[ + "11111"]) + + self.runCmd("continue", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.expect( + "expr (unsigned long long)conflicting_symbol", + "Symbol from Two should be found", + substrs=[ + "22222"]) + + self.runCmd("continue", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.expect( + "expr (unsigned long long)conflicting_symbol", + "An error should be printed when symbols can't be ordered", + error=True, + substrs=[ + "Multiple internal symbols"]) + + @expectedFailureAll(bugnumber="llvm.org/pr35043") + @skipIfWindows # This test is "passing" on Windows, but it is a false positive. + def test_shadowed(self): + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, ['One', 'Two']) + + lldbutil.run_break_set_by_source_regexp(self, '// break here', + extra_options='-f main.c', num_expected_locations=1) + + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # As we are shadowing the conflicting symbol, there should be no + # ambiguity in this expression. + self.expect( + "expr int conflicting_symbol = 474747; conflicting_symbol", + substrs=[ "474747"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two.mk b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two.mk new file mode 100644 index 00000000000..79b256a0e85 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two.mk @@ -0,0 +1,8 @@ +DYLIB_NAME := Two +DYLIB_C_SOURCES := Two.c TwoConstant.c +DYLIB_ONLY := YES + +include Makefile.rules + +TwoConstant.o: TwoConstant.c + $(CC) $(CFLAGS_NO_DEBUG) -c $< -o $@ diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two/Two.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two/Two.c new file mode 100644 index 00000000000..8d8d668b8c3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two/Two.c @@ -0,0 +1,6 @@ +#include "Two.h" +#include <stdio.h> + +void two() { + printf("Two\n"); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two/Two.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two/Two.h new file mode 100644 index 00000000000..450fe5a3551 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two/Two.h @@ -0,0 +1,4 @@ +#ifndef TWO_H +#define TWO_H +LLDB_TEST_API void two(); +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two/TwoConstant.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two/TwoConstant.c new file mode 100644 index 00000000000..9fc7c4b7951 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/Two/TwoConstant.c @@ -0,0 +1 @@ +int __attribute__ ((visibility("hidden"))) conflicting_symbol = 22222; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/main.c new file mode 100644 index 00000000000..4dcd443c049 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/conflicting-symbol/main.c @@ -0,0 +1,11 @@ +#include "One/One.h" +#include "Two/Two.h" + +#include <stdio.h> + +int main() { + one(); + two(); + printf("main\n"); // break here + return(0); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/Makefile new file mode 100644 index 00000000000..325be90d17e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/Makefile @@ -0,0 +1,5 @@ +C_SOURCES := main.c functions.c + +CFLAGS_EXTRAS := -O3 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py new file mode 100644 index 00000000000..59fa6bcb0a1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py @@ -0,0 +1,68 @@ +"""Check that compiler-generated constant values work correctly""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ConstVariableTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["freebsd", "linux"], + compiler="clang", compiler_version=["<", "3.5"]) + @expectedFailureAll( + oslist=["freebsd", "linux"], + compiler="clang", compiler_version=["=", "3.7"]) + @expectedFailureAll( + oslist=["freebsd", "linux"], + compiler="clang", compiler_version=["=", "3.8"]) + @expectedFailureAll(oslist=["freebsd", "linux"], compiler="icc") + @expectedFailureAll(archs=['mips', 'mipsel', 'mips64', 'mips64el']) + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureNetBSD + def test_and_run_command(self): + """Test interpreted and JITted expressions on constant values.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the main. + lldbutil.run_break_set_by_symbol( + self, "main", num_expected_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=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.runCmd("next") + self.runCmd("next") + + # Try frame variable. + self.expect("frame variable index", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int32_t) index = 512']) + + # Try an interpreted expression. + self.expect("expr (index + 512)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['1024']) + + # Try a JITted expression. + self.expect( + "expr (int)getpid(); (index - 256)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['256']) + + self.runCmd("kill") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/functions.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/functions.c new file mode 100644 index 00000000000..c9ea63837c8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/functions.c @@ -0,0 +1,18 @@ +#include <stdio.h> + +void foo() +{ + printf("foo()\n"); +} + +int bar() +{ + int ret = 3; + printf("bar()->%d\n", ret); + return ret; +} + +void baaz(int i) +{ + printf("baaz(%d)\n", i); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/main.c new file mode 100644 index 00000000000..50a924e01d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/const_variables/main.c @@ -0,0 +1,23 @@ +#include <stdint.h> +#include <stdio.h> + +extern int foo(); +extern int bar(); +extern int baaz(int i); + +int main() +{ + int32_t index; + + foo(); + + index = 512; + + if (bar()) + { + printf("COMPILER PLEASE STOP HERE\n"); + index = 256; + } + + baaz(index); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py new file mode 100644 index 00000000000..af9b6fb8d46 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py @@ -0,0 +1,126 @@ +"""Look up enum type information and check for correct display.""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * + + +class EnumTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # 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.') + + def test(self): + """Test 'image lookup -t days' and check for correct display and enum value printing.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_to_source_breakpoint( + self, '// Breakpoint for bitfield', lldb.SBFileSpec("main.c")) + + self.expect("fr var a", DATA_TYPES_DISPLAYED_CORRECTLY, + patterns=[' = A$']) + self.expect("fr var b", DATA_TYPES_DISPLAYED_CORRECTLY, + patterns=[' = B$']) + self.expect("fr var c", DATA_TYPES_DISPLAYED_CORRECTLY, + patterns=[' = C$']) + self.expect("fr var ab", DATA_TYPES_DISPLAYED_CORRECTLY, + patterns=[' = AB$']) + self.expect("fr var ac", DATA_TYPES_DISPLAYED_CORRECTLY, + patterns=[' = A | C$']) + self.expect("fr var all", DATA_TYPES_DISPLAYED_CORRECTLY, + patterns=[' = ALL$']) + # Test that an enum that doesn't match the heuristic we use in + # ClangASTContext::DumpEnumValue, gets printed as a raw integer. + self.expect("fr var omega", DATA_TYPES_DISPLAYED_CORRECTLY, + patterns=[' = 7$']) + # Test the behavior in case have a variable of a type considered + # 'bitfield' by the heuristic, but the value isn't actually fully + # covered by the enumerators. + self.expect("p (enum bitfield)nonsense", DATA_TYPES_DISPLAYED_CORRECTLY, + patterns=[' = B | C | 0x10$']) + + # Break inside the main. + bkpt_id = lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + self.runCmd("c", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Look up information about the 'days' enum type. + # Check for correct display. + self.expect("image lookup -t days", DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=['enum days {', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday', + 'kNumDays', + '}']) + + enum_values = ['-4', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday', + 'kNumDays', + '5'] + + # Make sure a pointer to an anonymous enum type does crash LLDB and displays correctly using + # frame variable and expression commands + self.expect( + 'frame variable f.op', + DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=[ + 'ops *', + 'f.op'], + patterns=['0x0+$']) + self.expect( + 'frame variable *f.op', + DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=[ + 'ops', + '*f.op', + '<parent is NULL>']) + self.expect( + 'expr f.op', + DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=[ + 'ops *', + '$'], + patterns=['0x0+$']) + self.expect( + 'expr *f.op', + DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=['error:'], + error=True) + + bkpt = self.target().FindBreakpointByID(bkpt_id) + for enum_value in enum_values: + self.expect( + "frame variable day", + 'check for valid enumeration value', + substrs=[enum_value]) + lldbutil.continue_to_breakpoint(self.process(), bkpt) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/main.c new file mode 100644 index 00000000000..675af5ecec5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/enum_types/main.c @@ -0,0 +1,58 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +#include <stdio.h> + +// Forward declare an enumeration (only works in C, not C++) +typedef enum ops ops; + +struct foo { + ops *op; +}; + +int main (int argc, char const *argv[]) +{ + enum bitfield { + None = 0, + A = 1 << 0, + B = 1 << 1, + C = 1 << 2, + AB = A | B, + ALL = A | B | C, + }; + + enum non_bitfield { + Alpha = 3, + Beta = 4 + }; + + enum days { + Monday = -3, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, + Sunday, + kNumDays + }; + + enum bitfield a = A, b = B, c = C, ab = AB, ac = A | C, all = ALL; + int nonsense = a + b + c + ab + ac + all; + enum non_bitfield omega = Alpha | Beta; + + enum days day; + struct foo f; + f.op = NULL; // Breakpoint for bitfield + for (day = Monday - 1; day <= kNumDays + 1; day++) + { + printf("day as int is %i\n", (int)day); // Set break point at this line. + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/find_struct_type/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/find_struct_type/Makefile new file mode 100644 index 00000000000..c9319d6e688 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/find_struct_type/Makefile @@ -0,0 +1,2 @@ +C_SOURCES := main.c +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/find_struct_type/TestFindStructTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/find_struct_type/TestFindStructTypes.py new file mode 100644 index 00000000000..90d8530ff71 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/find_struct_type/TestFindStructTypes.py @@ -0,0 +1,59 @@ +""" +Make sure FindTypes finds struct types with the struct prefix. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class TestFindTypesOnStructType(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def test_find_types_struct_type(self): + """Make sure FindTypes actually finds 'struct typename' not just 'typename'.""" + self.build() + self.do_test() + + def do_test(self): + """Make sure FindTypes actually finds 'struct typename' not just 'typename'.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Make sure this works with struct + type_list = target.FindTypes("struct mytype") + self.assertEqual(type_list.GetSize(), 1, "Found one instance of the type with struct") + + # Make sure this works without the struct: + type_list = target.FindTypes("mytype") + self.assertEqual(type_list.GetSize(), 1, "Found one instance of the type without struct") + + # Make sure it works with union + type_list = target.FindTypes("union myunion") + self.assertEqual(type_list.GetSize(), 1, "Found one instance of the type with union") + + # Make sure this works without the union: + type_list = target.FindTypes("myunion") + self.assertEqual(type_list.GetSize(), 1, "Found one instance of the type without union") + + # Make sure it works with typedef + type_list = target.FindTypes("typedef MyType") + self.assertEqual(type_list.GetSize(), 1, "Found one instance of the type with typedef") + + # Make sure this works without the typedef: + type_list = target.FindTypes("MyType") + self.assertEqual(type_list.GetSize(), 1, "Found one instance of the type without typedef") + + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/find_struct_type/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/find_struct_type/main.c new file mode 100644 index 00000000000..fa009af27e1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/find_struct_type/main.c @@ -0,0 +1,25 @@ +#include <stdio.h> +#include <stdlib.h> +struct mytype { + int c; + int d; +}; + +union myunion { + int num; + char *str; +}; + +typedef struct mytype MyType; + +int main() +{ + struct mytype v; + MyType *v_ptr = &v; + + union myunion u = {5}; + v.c = u.num; + v.d = 10; + return v.c + v.d; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/Makefile new file mode 100644 index 00000000000..472e733aaad --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c foo.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/README.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/README.txt new file mode 100644 index 00000000000..b7b66f75162 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/README.txt @@ -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". diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py new file mode 100644 index 00000000000..9ea13612c07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py @@ -0,0 +1,65 @@ +"""Test that forward declaration of a data structure gets resolved correctly.""" + + + +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil + + +class ForwardDeclarationTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def do_test(self, dictionary=None): + """Display *bar_ptr when stopped on a function with forward declaration of struct bar.""" + self.build(dictionary=dictionary) + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_break_set_by_symbol( + self, "foo", num_expected_locations=1, sym_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", 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 --show-types *bar_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(bar) *bar_ptr = ', + '(int) a = 1', + '(int) b = 2']) + + # And so should this. + self.expect( + "expression --show-types -- *bar_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(bar)', + '(int) a = 1', + '(int) b = 2']) + + def test(self): + self.do_test() + + @no_debug_info_test + @skipIfDarwin + @skipIf(compiler=no_match("clang")) + @skipIf(compiler_version=["<", "7.0"]) + def test_debug_names(self): + """Test that we are able to find complete types when using DWARF v5 + accelerator tables""" + self.do_test(dict(CFLAGS_EXTRAS="-mllvm -accel-tables=Dwarf")) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/foo.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/foo.c new file mode 100644 index 00000000000..2e050e77778 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/foo.c @@ -0,0 +1,8 @@ +#include <stdio.h> +#include "foo.h" + +int +foo (struct bar *bar_ptr) +{ + return printf ("bar_ptr = %p\n", bar_ptr); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/foo.h new file mode 100644 index 00000000000..3040927cb47 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/foo.h @@ -0,0 +1,4 @@ + +struct bar; + +int foo (struct bar *bar_ptr); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/main.c new file mode 100644 index 00000000000..6f9787c30a3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/forward/main.c @@ -0,0 +1,18 @@ +#include <stdio.h> +#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; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/function_types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/function_types/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/function_types/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py new file mode 100644 index 00000000000..3753eab64ef --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py @@ -0,0 +1,83 @@ +"""Test variable with function ptr type and that break on the function works.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class FunctionTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # 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.') + + def test(self): + """Test 'callback' has function ptr type, then break on the function.""" + self.build() + self.runToBreakpoint() + + # Check that the 'callback' variable display properly. + self.expect( + "frame variable --show-types callback", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int (*)(const char *)) callback =') + + # And that we can break on the callback function. + lldbutil.run_break_set_by_symbol( + self, + "string_not_empty", + num_expected_locations=1, + sym_exact=True) + self.runCmd("continue") + + # Check that we do indeed stop on the string_not_empty function. + self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, + substrs=['a.out`string_not_empty', + 'stop reason = breakpoint']) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") + @expectedFailureNetBSD + def test_pointers(self): + """Test that a function pointer to 'printf' works and can be called.""" + self.build() + self.runToBreakpoint() + + self.expect("expr string_not_empty", + substrs=['(int (*)(const char *)) $0 = ', '(a.out`']) + + if self.platformIsDarwin(): + regexps = ['lib.*\.dylib`printf'] + else: + regexps = ['printf'] + self.expect("expr (int (*)(const char*, ...))printf", + substrs=['(int (*)(const char *, ...)) $1 = '], + patterns=regexps) + + self.expect("expr $1(\"Hello world\\n\")", + startstr='(int) $2 = 12') + + def runToBreakpoint(self): + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the main. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/function_types/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/function_types/main.c new file mode 100644 index 00000000000..f8710f67720 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/function_types/main.c @@ -0,0 +1,21 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int string_not_empty (const char *s) +{ + if (s && s[0]) + return 1; + return 0; +} + +int main (int argc, char const *argv[]) +{ + int (*callback)(const char *) = string_not_empty; + + return callback(0); // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/Makefile new file mode 100644 index 00000000000..7b94b6556f2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/Makefile @@ -0,0 +1,6 @@ +C_SOURCES := main.c + +DYLIB_NAME := a +DYLIB_C_SOURCES := a.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py new file mode 100644 index 00000000000..690d1abb3cf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py @@ -0,0 +1,123 @@ +"""Show global variables and check that they do indeed have global scopes.""" + + + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class GlobalVariablesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.c' + self.line = line_number( + self.source, '// Set break point at this line.') + self.shlib_names = ["a"] + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") + def test_without_process(self): + """Test that static initialized variables can be inspected without + process.""" + self.build() + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + + self.assertTrue(target, VALID_TARGET) + self.expect("target variable g_ptr", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int *)']) + self.expect("target variable *g_ptr", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['42']) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") + @expectedFailureNetBSD + def test_c_global_variables(self): + """Test 'frame variable --scope --no-args' which omits args and shows scopes.""" + self.build() + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Break inside the main. + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Test that the statically initialized variable can also be + # inspected *with* a process. + self.expect("target variable g_ptr", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int *)']) + self.expect("target variable *g_ptr", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['42']) + + # Check that GLOBAL scopes are indicated for the variables. + self.expect( + "frame variable --show-types --scope --show-globals --no-args", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'STATIC: (const int) g_file_static_int = 2', + 'STATIC: (const char *) g_func_static_cstr', + 'GLOBAL: (const char *) g_file_global_cstr', + '"g_file_global_cstr"', + 'GLOBAL: (int) g_file_global_int = 42', + 'GLOBAL: (int) g_common_1 = 21', + 'GLOBAL: (int *) g_ptr', + 'STATIC: (const char *) g_file_static_cstr', + '"g_file_static_cstr"' + ]) + + # 'frame variable' should support address-of operator. + self.runCmd("frame variable &g_file_global_int") + + # Exercise the 'target variable' command to display globals in a.c + # file. + self.expect("target variable g_a", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['g_a', '123']) + self.expect( + "target variable g_marked_spot.x", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'g_marked_spot.x', + '20']) + + # rdar://problem/9747668 + # runCmd: target variable g_marked_spot.y + # output: (int) g_marked_spot.y = <a.o[0x214] can't be resolved, in not currently loaded. + # > + self.expect( + "target variable g_marked_spot.y", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'g_marked_spot.y', + '21']) + self.expect( + "target variable g_marked_spot.y", + VARIABLES_DISPLAYED_CORRECTLY, + matching=False, + substrs=["can't be resolved"]) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/a.c new file mode 100644 index 00000000000..ce3e6f9a2d4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/a.c @@ -0,0 +1,14 @@ +//===-- a.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +int g_a = 123; +struct Point { + int x; + int y; +}; +struct Point g_marked_spot = { 20, 21 }; + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/cmds.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/cmds.txt new file mode 100644 index 00000000000..6906a0729ae --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/cmds.txt @@ -0,0 +1,3 @@ +break main.c:5 +continue +var -global g_a -global g_global_int diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/main.c new file mode 100644 index 00000000000..ea54eb927c0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/global_variables/main.c @@ -0,0 +1,24 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int g_common_1; // Not initialized on purpose to cause it to be undefined external in .o file +int g_file_global_int = 42; +static const int g_file_static_int = 2; +const char *g_file_global_cstr = "g_file_global_cstr"; +static const char *g_file_static_cstr = "g_file_static_cstr"; +int *g_ptr = &g_file_global_int; + +extern int g_a; +int main (int argc, char const *argv[]) +{ + g_common_1 = g_file_global_int / g_file_static_int; + static const char *g_func_static_cstr = "g_func_static_cstr"; + printf ("%s %s\n", g_file_global_cstr, g_file_static_cstr); + return g_file_global_int + g_a + g_common_1 + *g_ptr; // Set break point at this line. //// break $source:$line; continue; var -global g_a -global g_global_int +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/inlines/TestRedefinitionsInInlines.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/inlines/TestRedefinitionsInInlines.py new file mode 100644 index 00000000000..311c5ec8e12 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/inlines/TestRedefinitionsInInlines.py @@ -0,0 +1,9 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, + globals(), + [decorators.expectedFailureAll(compiler="clang", + compiler_version=["<", + "3.5"], + bugnumber="llvm.org/pr27845")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/inlines/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/inlines/main.c new file mode 100644 index 00000000000..8fe49180800 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/inlines/main.c @@ -0,0 +1,25 @@ +#include <stdio.h> + +inline void test1(int) __attribute__ ((always_inline)); +inline void test2(int) __attribute__ ((always_inline)); + +void test2(int b) { + printf("test2(%d)\n", b); //% self.expect("expression b", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["42"]) + { + int c = b * 2; + printf("c=%d\n", c); //% self.expect("expression b", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["42"]) + //% self.expect("expression c", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["84"]) + } +} + +void test1(int a) { + printf("test1(%d)\n", a); + test2(a+1);//% self.runCmd("step") + //% self.expect("expression b", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["24"]) +} + +int main() { + test2(42); + test1(23); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_types/TestUseClosestType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_types/TestUseClosestType.py new file mode 100644 index 00000000000..2b8307ace0f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_types/TestUseClosestType.py @@ -0,0 +1,48 @@ +""" +If there is a definition of a type in the current +Execution Context's CU, then we should use that type +even if there are other definitions of the type in other +CU's. Assert that that is true. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class TestUseClosestType(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @expectedFailureAll(bugnumber="<rdar://problem/53262085>") + def test_use_in_expr(self): + """Use the shadowed type directly, see if we get a conflicting type definition.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.c") + self.expr_test() + + def run_and_check_expr(self, num_children, child_type): + frame = self.thread.GetFrameAtIndex(0) + result = frame.EvaluateExpression("struct Foo *$mine = (struct Foo *) malloc(sizeof(struct Foo)); $mine") + self.assertTrue(result.GetError().Success(), "Failed to parse an expression using a multiply defined type: %s"%(result.GetError().GetCString()), ) + self.assertEqual(result.GetTypeName(), "struct Foo *", "The result has the right typename.") + self.assertEqual(result.GetNumChildren(), num_children, "Got the right number of children") + self.assertEqual(result.GetChildAtIndex(0).GetTypeName(), child_type, "Got the right type.") + + def expr_test(self): + """ Run to a breakpoint in main.c, check that an expression referring to Foo gets the + local three int version. Then run to a breakpoint in other.c and check that an + expression referring to Foo gets the two char* version. """ + + (target, process, self.thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint in main", self.main_source_file) + + self.run_and_check_expr(3, "int") + lldbutil.run_to_source_breakpoint(self, "Set a breakpoint in other", lldb.SBFileSpec("other.c")) + self.run_and_check_expr(2, "char *") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_types/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_types/main.c new file mode 100644 index 00000000000..321facfee21 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_types/main.c @@ -0,0 +1,16 @@ +extern int callme(int input); + +struct Foo { + int a; + int b; + int c; +}; + +int +main(int argc, char **argv) +{ + // Set a breakpoint in main + struct Foo mine = {callme(argc), 10, 20}; + return mine.a; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_types/other.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_types/other.c new file mode 100644 index 00000000000..24b72d45ea8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_types/other.c @@ -0,0 +1,11 @@ +struct Foo { + char *ptr1; + char *ptr2; +}; + +int +callme(int input) +{ + struct Foo myFoo = { "string one", "Set a breakpoint in other"}; + return myFoo.ptr1[0] + myFoo.ptr2[0] + input; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_variables/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_variables/Makefile new file mode 100644 index 00000000000..d3998eeef99 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_variables/Makefile @@ -0,0 +1,5 @@ +C_SOURCES := main.c + +CFLAGS_EXTRAS := -O1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_variables/TestLocalVariables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_variables/TestLocalVariables.py new file mode 100644 index 00000000000..381292a445b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_variables/TestLocalVariables.py @@ -0,0 +1,55 @@ +"""Show local variables and check that they can be inspected. + +This test was added after we made a change in clang to normalize +DW_OP_constu(X < 32) to DW_OP_litX which broke the debugger because +it didn't read the value as an unsigned. +""" + + + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LocalVariablesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.c' + self.line = line_number( + self.source, '// Set break point at this line.') + + @skipIfWindows + def test_c_local_variables(self): + """Test local variable value.""" + self.build() + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Break inside the main. + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.expect("frame variable i", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(unsigned int) i = 10']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_variables/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_variables/main.c new file mode 100644 index 00000000000..2ab579a71a7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/local_variables/main.c @@ -0,0 +1,19 @@ +#include <stdio.h> + +void bar(unsigned i) +{ + printf("%d\n", i); +} + +void foo(unsigned j) +{ + unsigned i = j; + bar(i); + i = 10; + bar(i); // Set break point at this line. +} + +int main(int argc, char** argv) +{ + foo(argc); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/modules/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/modules/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/modules/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py new file mode 100644 index 00000000000..948e8bed786 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py @@ -0,0 +1,91 @@ +"""Test that importing modules in C works as expected.""" + + + +import os + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CModulesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfFreeBSD + @expectedFailureAll( + oslist=["linux"], + bugnumber="http://llvm.org/pr23456 'fopen' has unknown return type") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureNetBSD + def test_expr(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Enable logging of the imported AST. + log_file = os.path.join(self.getBuildDir(), "lldb-ast-log.txt") + self.runCmd("log enable lldb ast -f '%s'" % log_file) + + self.expect( + "expr -l objc++ -- @import Darwin; 3", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "int", + "3"]) + + # This expr command imports __sFILE with definition + # (FILE is a typedef to __sFILE.) + self.expect( + "expr *fopen(\"/dev/zero\", \"w\")", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "FILE", + "_close"]) + + # Check that the AST log contains exactly one definition of __sFILE. + f = open(log_file) + log_lines = f.readlines() + f.close() + os.remove(log_file) + self.assertEqual(" ".join(log_lines).count("struct __sFILE definition"), + 1) + + self.expect("expr *myFile", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["a", "5", "b", "9"]) + + self.expect( + "expr MIN((uint64_t)2, (uint64_t)3)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "uint64_t", + "2"]) + + self.expect("expr stdin", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["(FILE *)", "0x"]) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.c', '// Set breakpoint 0 here.') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/modules/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/modules/main.c new file mode 100644 index 00000000000..df321a75faa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/modules/main.c @@ -0,0 +1,20 @@ +#include <stdlib.h> + +int printf(const char * __restrict format, ...); + +typedef struct { + int a; + int b; +} MYFILE; + +int main() +{ + MYFILE *myFile = malloc(sizeof(MYFILE)); + + myFile->a = 5; + myFile->b = 9; + + printf("%d\n", myFile->a + myFile->b); // Set breakpoint 0 here. + + free(myFile); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/offsetof/TestOffsetof.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/offsetof/TestOffsetof.py new file mode 100644 index 00000000000..cdfbaae0ce3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/offsetof/TestOffsetof.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), [decorators.no_debug_info_test]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/offsetof/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/offsetof/main.c new file mode 100644 index 00000000000..cbb4a144418 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/offsetof/main.c @@ -0,0 +1,12 @@ +#include <stdint.h> + +struct Foo { + int8_t a; + int16_t b; +}; + +int main (int argc, char const *argv[]) { + struct Foo f; + return f.a; //% self.expect("expr offsetof(Foo, a)", substrs = ['= 0']) + //% self.expect("expr offsetof(Foo, b)", substrs = ['= 2']) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/recurse/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/recurse/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/recurse/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/recurse/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/recurse/main.c new file mode 100644 index 00000000000..1159669ebf1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/recurse/main.c @@ -0,0 +1,28 @@ +#include <stdint.h> +#include <stdio.h> + +uint32_t +recurse_crash (uint32_t depth) +{ + if (depth > 0) + return recurse_crash (depth - 1); + return 0; +} + +int +main (int argc, char const *argv[]) +{ + // If we have more than one argument, then it should a depth to recurse to. + // If we have just the program name as an argument, use UINT32_MAX so we + // eventually crash the program by overflowing the stack + uint32_t depth = UINT32_MAX; + if (argc > 1) + { + char *end = NULL; + depth = strtoul (argv[1], &end, 0); + if (end == NULL || *end != '\0') + depth = UINT32_MAX; + } + recurse_crash (depth); + return 0; +}
\ No newline at end of file diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/Makefile new file mode 100644 index 00000000000..e4d42f6525d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/Makefile @@ -0,0 +1,5 @@ +C_SOURCES := test.c + +CFLAGS_EXTRAS := -O1 -D_FORTIFY_SOURCE=0 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py new file mode 100644 index 00000000000..af0ad2a0871 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py @@ -0,0 +1,204 @@ +"""Check that compiler-generated register values work correctly""" + +from __future__ import print_function + +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +# This method attempts to figure out if a given variable +# is in a register. +# +# Return: +# True if the value has a readable value and is in a register +# False otherwise + + +def is_variable_in_register(frame, var_name): + # Ensure we can lookup the variable. + var = frame.FindVariable(var_name) + # print("\nchecking {}...".format(var_name)) + if var is None or not var.IsValid(): + # print("{} cannot be found".format(var_name)) + return False + + # Check that we can get its value. If not, this + # may be a variable that is just out of scope at this point. + value = var.GetValue() + # print("checking value...") + if value is None: + # print("value is invalid") + return False + # else: + # print("value is {}".format(value)) + + # We have a variable and we can get its value. The variable is in + # a register if we cannot get an address for it, assuming it is + # not a struct pointer. (This is an approximation - compilers can + # do other things with spitting up a value into multiple parts of + # multiple registers, but what we're verifying here is much more + # than it was doing before). + var_addr = var.GetAddress() + # print("checking address...") + if var_addr.IsValid(): + # We have an address, it must not be in a register. + # print("var {} is not in a register: has a valid address {}".format(var_name, var_addr)) + return False + else: + # We don't have an address but we can read the value. + # It is likely stored in a register. + # print("var {} is in a register (we don't have an address for it)".format(var_name)) + return True + + +def is_struct_pointer_in_register(frame, var_name, trace): + # Ensure we can lookup the variable. + var = frame.FindVariable(var_name) + if trace: + print("\nchecking {}...".format(var_name)) + + if var is None or not var.IsValid(): + # print("{} cannot be found".format(var_name)) + return False + + # Check that we can get its value. If not, this + # may be a variable that is just out of scope at this point. + value = var.GetValue() + # print("checking value...") + if value is None: + if trace: + print("value is invalid") + return False + else: + if trace: + print("value is {}".format(value)) + + var_loc = var.GetLocation() + if trace: + print("checking location: {}".format(var_loc)) + if var_loc is None or var_loc.startswith("0x"): + # The frame var is not in a register but rather a memory location. + # print("frame var {} is not in a register".format(var_name)) + return False + else: + # print("frame var {} is in a register".format(var_name)) + return True + + +def re_expr_equals(val_type, val): + # Match ({val_type}) ${sum_digits} = {val} + return re.compile(r'\(' + val_type + '\) \$\d+ = ' + str(val)) + + +class RegisterVariableTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(compiler="clang", compiler_version=['<', '3.5']) + @expectedFailureAll(compiler="gcc", compiler_version=[ + '>=', '4.8.2'], archs=["i386"]) + @expectedFailureAll(compiler="gcc", compiler_version=[ + '<', '4.9'], archs=["x86_64"]) + def test_and_run_command(self): + """Test expressions on register values.""" + + # This test now ensures that each probable + # register variable location is actually a register, and + # if so, whether we can print out the variable there. + # It only requires one of them to be handled in a non-error + # way. + register_variables_count = 0 + + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the main. + lldbutil.run_break_set_by_source_regexp( + self, "break", num_expected_locations=3) + + #################### + # First breakpoint + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Try some variables that should be visible + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() + if is_variable_in_register(frame, 'a'): + register_variables_count += 1 + self.expect("expr a", VARIABLES_DISPLAYED_CORRECTLY, + patterns=[re_expr_equals('int', 2)]) + + if is_struct_pointer_in_register(frame, 'b', self.TraceOn()): + register_variables_count += 1 + self.expect("expr b->m1", VARIABLES_DISPLAYED_CORRECTLY, + patterns=[re_expr_equals('int', 3)]) + + ##################### + # Second breakpoint + + self.runCmd("continue") + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Try some variables that should be visible + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() + if is_struct_pointer_in_register(frame, 'b', self.TraceOn()): + register_variables_count += 1 + self.expect("expr b->m2", VARIABLES_DISPLAYED_CORRECTLY, + patterns=[re_expr_equals('int', 5)]) + + if is_variable_in_register(frame, 'c'): + register_variables_count += 1 + self.expect("expr c", VARIABLES_DISPLAYED_CORRECTLY, + patterns=[re_expr_equals('int', 5)]) + + ##################### + # Third breakpoint + + self.runCmd("continue") + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Try some variables that should be visible + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() + if is_variable_in_register(frame, 'f'): + register_variables_count += 1 + self.expect("expr f", VARIABLES_DISPLAYED_CORRECTLY, + patterns=[re_expr_equals('float', '3.1')]) + + # Validate that we verified at least one register variable + self.assertTrue( + register_variables_count > 0, + "expected to verify at least one variable in a register") + # print("executed {} expressions with values in registers".format(register_variables_count)) + + self.runCmd("kill") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/test.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/test.c new file mode 100644 index 00000000000..2c69039d40a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/register_variables/test.c @@ -0,0 +1,44 @@ +#include <stdio.h> + +#if defined(__arm__) || defined(__aarch64__) || defined (__mips__) || defined(__powerpc64__) +// Clang does not accept regparm attribute on these platforms. +// Fortunately, the default calling convention passes arguments in registers +// anyway. +#define REGPARM(N) +#else +#define REGPARM(N) __attribute__((regparm(N))) +#endif + +struct bar { + int m1; + int m2; +}; + +void f1(int a, struct bar *b) __attribute__((noinline)) REGPARM(2); +void f1(int a, struct bar *b) +{ + b->m2 = b->m1 + a; // set breakpoint here +} + +void f2(struct bar *b) __attribute__((noinline)) REGPARM(1); +void f2(struct bar *b) +{ + int c = b->m2; + printf("%d\n", c); // set breakpoint here +} + +float f3() __attribute__((noinline)); +float f3() { + return 3.14f; +} + +int main() +{ + struct bar myBar = { 3, 4 }; + f1(2, &myBar); + f2(&myBar); + + float f = f3(); + printf("%f\n", f); // set breakpoint here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/set_values/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/set_values/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/set_values/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py new file mode 100644 index 00000000000..f16d554b815 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py @@ -0,0 +1,139 @@ +"""Test settings and readings of program variables.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SetValuesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # 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.') + 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 test(self): + """Test settings and readings of program variables.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Set breakpoints on several places to set program variables. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line1, num_expected_locations=1, loc_exact=True) + + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line2, num_expected_locations=1, loc_exact=True) + + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line3, num_expected_locations=1, loc_exact=True) + + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line4, num_expected_locations=1, loc_exact=True) + + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line5, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # main.c:15 + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(char) i = 'a'") + + # Now set variable 'i' and check that it is correctly displayed. + self.runCmd("expression i = 'b'") + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(char) i = 'b'") + + self.runCmd("continue") + + # main.c:36 + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + patterns=["\((short unsigned int|unsigned short)\) i = 33"]) + + # Now set variable 'i' and check that it is correctly displayed. + self.runCmd("expression i = 333") + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + patterns=["\((short unsigned int|unsigned short)\) i = 333"]) + + self.runCmd("continue") + + # main.c:57 + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(long) i = 33") + + # Now set variable 'i' and check that it is correctly displayed. + self.runCmd("expression i = 33333") + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(long) i = 33333") + + self.runCmd("continue") + + # main.c:78 + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(double) i = 2.25") + + # Now set variable 'i' and check that it is correctly displayed. + self.runCmd("expression i = 1.5") + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(double) i = 1.5") + + self.runCmd("continue") + + # main.c:85 + # Check that 'frame variable --show-types' displays the correct data + # type and value. + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(long double) i = 2.25") + + # Now set variable 'i' and check that it is correctly displayed. + self.runCmd("expression i = 1.5") + self.expect( + "frame variable --show-types", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(long double) i = 1.5") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/set_values/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/set_values/main.c new file mode 100644 index 00000000000..64bc95fb5a8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/set_values/main.c @@ -0,0 +1,115 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +void set_char(void) +{ + char i = 'a'; + printf("before (char) i = %c\n", i); + printf("after (char) i = %c\n", i); // Set break point #1. //// break $source:$line +} + +void set_uchar(void) +{ + unsigned char i = 'a'; + printf("before (unsigned char) i = %c\n", i); + printf("after (unsigned char) i = %c\n", i); //// break $source:$line +} + +void set_short(void) +{ + short i = 33; + printf("before (short) i = %i\n", i); + printf("after (short) i = %i\n", i); //// break $source:$line +} + +void set_ushort(void) +{ + unsigned short i = 33; + printf("before (unsigned short) i = %i\n", i); + printf("after (unsigned short) i = %i\n", i); // Set break point #2. //// break $source:$line +} + +void set_int(void) +{ + int i = 33; + printf("before (int) i = %i\n", i); + printf("after (int) i = %i\n", i); //// break $source:$line +} + +void set_uint(void) +{ + unsigned int i = 33; + printf("before (unsigned int) i = %u\n", i); + printf("after (unsigned int) i = %u\n", i); //// break $source:$line +} + +void set_long(void) +{ + long i = 33; + printf("before (long) i = %li\n", i); + printf("after (long) i = %li\n", i); // Set break point #3. //// break $source:$line +} + +void set_ulong(void) +{ + unsigned long i = 33; + printf("before (unsigned long) i = %lu\n", i); + printf("after (unsigned long) i = %lu\n", i); //// break $source:$line +} + +void set_float(void) +{ + float i = 2.25; + printf("before (float) i = %g\n", i); + printf("after (float) i = %g\n", i); //// break $source:$line +} + +void set_double(void) +{ + double i = 2.25; + printf("before (double) i = %g\n", i); + printf("after (double) i = %g\n", i); // Set break point #4. //// break $source:$line +} + +void set_long_double(void) +{ + long double i = 2.25; + printf("before (long double) i = %Lg\n", i); + printf("after (long double) i = %Lg\n", i); // Set break point #5. //// break $source:$line +} + +void set_point (void) +{ + struct point_tag { + int x; + int y; + }; + struct point_tag points_2[2] = { + {1,2}, + {3,4} + }; +} + +int main (int argc, char const *argv[]) +{ + // Continue to the breakpoint in set_char() + set_char(); //// continue; var i; val -set 99 1 + set_uchar(); //// continue; var i; val -set 99 2 + set_short(); //// continue; var i; val -set -42 3 + set_ushort(); //// continue; var i; val -set 42 4 + set_int(); //// continue; var i; val -set -42 5 + set_uint(); //// continue; var i; val -set 42 6 + set_long(); //// continue; var i; val -set -42 7 + set_ulong(); //// continue; var i; val -set 42 8 + set_float(); //// continue; var i; val -set 123.456 9 + set_double(); //// continue; var i; val -set 123.456 10 + set_long_double(); //// continue; var i; val -set 123.456 11 + set_point (); //// continue + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/Makefile new file mode 100644 index 00000000000..5e26f2748c0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/Makefile @@ -0,0 +1,5 @@ +DYLIB_NAME := foo +DYLIB_C_SOURCES := foo.c +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py new file mode 100644 index 00000000000..789939b29e7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py @@ -0,0 +1,101 @@ +"""Test that types defined in shared libraries work correctly.""" + + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class SharedLibTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def common_test_expr(self, preload_symbols): + if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): + self.skipTest( + "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") + + self.build() + self.common_setup(preload_symbols) + + # This should display correctly. + self.expect( + "expression --show-types -- *my_foo_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(foo)", + "(sub_foo)", + "other_element = 3"]) + + self.expect( + "expression GetMeASubFoo(my_foo_ptr)", + startstr="(sub_foo *) $") + + @expectedFailureNetBSD + def test_expr(self): + """Test that types work when defined in a shared library and forward-declared in the main executable""" + self.common_test_expr(True) + + @expectedFailureNetBSD + def test_expr_no_preload(self): + """Test that types work when defined in a shared library and forward-declared in the main executable, but with preloading disabled""" + self.common_test_expr(False) + + @unittest2.expectedFailure("llvm.org/PR36712") + def test_frame_variable(self): + """Test that types work when defined in a shared library and forward-declared in the main executable""" + self.build() + self.common_setup() + + # This should display correctly. + self.expect( + "frame variable --show-types -- *my_foo_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(foo)", + "(sub_foo)", + "other_element = 3"]) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.c' + self.line = line_number(self.source, '// Set breakpoint 0 here.') + self.shlib_names = ["foo"] + + def common_setup(self, preload_symbols = True): + # Run in synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + self.runCmd("settings set target.preload-symbols " + str(preload_symbols).lower()) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.c new file mode 100644 index 00000000000..6431bc496c3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.c @@ -0,0 +1,22 @@ +#include "foo.h" +#include <stdlib.h> + +struct foo +{ + struct sub_foo sub_element; + int other_element; +}; + +struct foo * +GetMeAFoo() +{ + struct foo *ret_val = (struct foo *) malloc (sizeof (struct foo)); + ret_val->other_element = 3; + return ret_val; +} + +struct sub_foo * +GetMeASubFoo (struct foo *in_foo) +{ + return &(in_foo->sub_element); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.h new file mode 100644 index 00000000000..78b9e3f9c0d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.h @@ -0,0 +1,10 @@ +struct foo; + +struct sub_foo +{ + int sub_1; + char *sub_2; +}; + +LLDB_TEST_API struct foo *GetMeAFoo(); +LLDB_TEST_API struct sub_foo *GetMeASubFoo(struct foo *in_foo); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/main.c new file mode 100644 index 00000000000..b4377de18c1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib/main.c @@ -0,0 +1,13 @@ +#include <stdio.h> +#include "foo.h" + +int +main () +{ + struct foo *my_foo_ptr; + my_foo_ptr = GetMeAFoo(); + + printf ("My sub foo has: %d.\n", GetMeASubFoo(my_foo_ptr)->sub_1); // Set breakpoint 0 here. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/Makefile new file mode 100644 index 00000000000..f3285de39e0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/Makefile @@ -0,0 +1,7 @@ +DYLIB_NAME := foo +DYLIB_C_SOURCES := foo.c +C_SOURCES := main.c + +SPLIT_DEBUG_SYMBOLS = YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py new file mode 100644 index 00000000000..8858f67cd18 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py @@ -0,0 +1,88 @@ +"""Test that types defined in shared libraries with stripped symbols work correctly.""" + + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SharedLibStrippedTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"]) + def test_expr(self): + """Test that types work when defined in a shared library and forwa/d-declared in the main executable""" + if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): + self.skipTest( + "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") + + self.build() + self.common_setup() + + # This should display correctly. + self.expect( + "expression --show-types -- *my_foo_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(foo)", + "(sub_foo)", + "other_element = 3"]) + + @expectedFailureAll(oslist=["windows"]) + @unittest2.expectedFailure("llvm.org/PR36712") + def test_frame_variable(self): + """Test that types work when defined in a shared library and forward-declared in the main executable""" + self.build() + self.common_setup() + + # This should display correctly. + self.expect( + "frame variable --show-types -- *my_foo_ptr", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(foo)", + "(sub_foo)", + "other_element = 3"]) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.c' + self.line = line_number(self.source, '// Set breakpoint 0 here.') + self.shlib_names = ["foo"] + + def common_setup(self): + # Run in synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.c new file mode 100644 index 00000000000..6431bc496c3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.c @@ -0,0 +1,22 @@ +#include "foo.h" +#include <stdlib.h> + +struct foo +{ + struct sub_foo sub_element; + int other_element; +}; + +struct foo * +GetMeAFoo() +{ + struct foo *ret_val = (struct foo *) malloc (sizeof (struct foo)); + ret_val->other_element = 3; + return ret_val; +} + +struct sub_foo * +GetMeASubFoo (struct foo *in_foo) +{ + return &(in_foo->sub_element); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.h new file mode 100644 index 00000000000..78b3c124538 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.h @@ -0,0 +1,12 @@ +struct foo; + +struct sub_foo +{ + int sub_1; + char *sub_2; +}; + +struct foo *GetMeAFoo(); +struct sub_foo *GetMeASubFoo (struct foo *in_foo); + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/main.c new file mode 100644 index 00000000000..b4377de18c1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/main.c @@ -0,0 +1,13 @@ +#include <stdio.h> +#include "foo.h" + +int +main () +{ + struct foo *my_foo_ptr; + my_foo_ptr = GetMeAFoo(); + + printf ("My sub foo has: %d.\n", GetMeASubFoo(my_foo_ptr)->sub_1); // Set breakpoint 0 here. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/.categories new file mode 100644 index 00000000000..c00c25822e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/.categories @@ -0,0 +1 @@ +basic_process diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/TestStepTarget.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/TestStepTarget.py new file mode 100644 index 00000000000..7665b2f73b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/TestStepTarget.py @@ -0,0 +1,122 @@ +"""Test the 'step target' feature.""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestStepTarget(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers that we will step to in main: + self.main_source = "main.c" + self.end_line = line_number(self.main_source, "All done") + + @add_test_categories(['pyapi']) + def get_to_start(self): + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + break_in_main = target.BreakpointCreateBySourceRegex( + 'Break here to try targetted stepping', self.main_source_spec) + self.assertTrue(break_in_main, VALID_BREAKPOINT) + self.assertGreater(break_in_main.GetNumLocations(), 0, "Has locations.") + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_main) + + if len(threads) != 1: + self.fail("Failed to stop at first breakpoint in main.") + + thread = threads[0] + return thread + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr32343") + def test_with_end_line(self): + """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" + + thread = self.get_to_start() + + error = lldb.SBError() + thread.StepInto("lotsOfArgs", self.end_line, error) + frame = thread.frames[0] + + self.assertEqual(frame.name, "lotsOfArgs", "Stepped to lotsOfArgs.") + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr32343") + def test_with_end_line_bad_name(self): + """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" + + thread = self.get_to_start() + + error = lldb.SBError() + thread.StepInto("lotsOfArgssss", self.end_line, error) + frame = thread.frames[0] + self.assertEqual(frame.line_entry.line, self.end_line, + "Stepped to the block end.") + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr32343") + def test_with_end_line_deeper(self): + """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" + + thread = self.get_to_start() + + error = lldb.SBError() + thread.StepInto("modifyInt", self.end_line, error) + frame = thread.frames[0] + self.assertEqual(frame.name, "modifyInt", "Stepped to modifyInt.") + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr32343") + def test_with_command_and_block(self): + """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" + + thread = self.get_to_start() + + result = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand( + 'thread step-in -t "lotsOfArgs" -e block', result) + self.assertTrue( + result.Succeeded(), + "thread step-in command succeeded.") + + frame = thread.frames[0] + self.assertEqual(frame.name, "lotsOfArgs", "Stepped to lotsOfArgs.") + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr32343") + def test_with_command_and_block_and_bad_name(self): + """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" + + thread = self.get_to_start() + + result = lldb.SBCommandReturnObject() + self.dbg.GetCommandInterpreter().HandleCommand( + 'thread step-in -t "lotsOfArgsssss" -e block', result) + self.assertTrue( + result.Succeeded(), + "thread step-in command succeeded.") + + frame = thread.frames[0] + + self.assertEqual(frame.name, "main", "Stepped back out to main.") + # end_line is set to the line after the containing block. Check that + # we got there: + self.assertEqual(frame.line_entry.line, self.end_line, + "Got out of the block") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/main.c new file mode 100644 index 00000000000..86a26c4d47a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step-target/main.c @@ -0,0 +1,40 @@ +#include <stdio.h> + +void +lotsOfArgs +( + int firstArg, + int secondArg, + int thirdArg, + int fourthArg +) +{ + printf ("First: %d Second: %d Third: %d Fourth: %d.\n", + firstArg, + secondArg, + thirdArg, + fourthArg); +} + +int +modifyInt(int incoming) +{ + return incoming % 2; +} + +int +main (int argc, char **argv) +{ + if (argc > 0) + { + int var_makes_block = argc + 1; + printf ("Break here to try targetted stepping.\n"); + lotsOfArgs(var_makes_block, + modifyInt(20), + 30, + modifyInt(40)); + printf ("Done calling lotsOfArgs."); + } + printf ("All done.\n"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step_over_no_deadlock/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step_over_no_deadlock/Makefile new file mode 100644 index 00000000000..4b3467bc4e8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step_over_no_deadlock/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := locking.cpp +CXXFLAGS_EXTRAS := -std=c++11 +ENABLE_THREADS := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step_over_no_deadlock/TestStepOverDoesntBlock.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step_over_no_deadlock/TestStepOverDoesntBlock.py new file mode 100644 index 00000000000..988d90a7bb3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step_over_no_deadlock/TestStepOverDoesntBlock.py @@ -0,0 +1,30 @@ +""" +Test that step over will let other threads run when necessary +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StepOverDoesntDeadlockTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_step_over(self): + """Test that when step over steps over a function it lets other threads run.""" + self.build() + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "without running the first thread at least somewhat", + lldb.SBFileSpec("locking.cpp")) + # This is just testing that the step over actually completes. + # If the test fails this step never return, so failure is really + # signaled by the test timing out. + + thread.StepOver() + state = process.GetState() + self.assertEqual(state, lldb.eStateStopped) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step_over_no_deadlock/locking.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step_over_no_deadlock/locking.cpp new file mode 100644 index 00000000000..8288a668fe8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/step_over_no_deadlock/locking.cpp @@ -0,0 +1,78 @@ +#include <stdio.h> +#include <thread> +#include <mutex> +#include <condition_variable> + +std::mutex contended_mutex; + +std::mutex control_mutex; +std::condition_variable control_condition; + +std::mutex thread_started_mutex; +std::condition_variable thread_started_condition; + +// This function runs in a thread. The locking dance is to make sure that +// by the time the main thread reaches the pthread_join below, this thread +// has for sure acquired the contended_mutex. So then the call_me_to_get_lock +// function will block trying to get the mutex, and only succeed once it +// signals this thread, then lets it run to wake up from the cond_wait and +// release the mutex. + +void +lock_acquirer_1 (void) +{ + std::unique_lock<std::mutex> contended_lock(contended_mutex); + + // Grab this mutex, that will ensure that the main thread + // is in its cond_wait for it (since that's when it drops the mutex. + + thread_started_mutex.lock(); + thread_started_mutex.unlock(); + + // Now signal the main thread that it can continue, we have the contended lock + // so the call to call_me_to_get_lock won't make any progress till this + // thread gets a chance to run. + + std::unique_lock<std::mutex> control_lock(control_mutex); + + thread_started_condition.notify_all(); + + control_condition.wait(control_lock); + +} + +int +call_me_to_get_lock (int ret_val) +{ + control_condition.notify_all(); + contended_mutex.lock(); + return ret_val; +} + +int +get_int() { + return 567; +} + +int main () +{ + std::unique_lock<std::mutex> thread_started_lock(thread_started_mutex); + + std::thread thread_1(lock_acquirer_1); + + thread_started_condition.wait(thread_started_lock); + + control_mutex.lock(); + control_mutex.unlock(); + + // Break here. At this point the other thread will have the contended_mutex, + // and be sitting in its cond_wait for the control condition. So there is + // no way that our by-hand calling of call_me_to_get_lock will proceed + // without running the first thread at least somewhat. + + int result = call_me_to_get_lock(get_int()); + thread_1.join(); + + return 0; + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py new file mode 100644 index 00000000000..c20e443b683 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py @@ -0,0 +1,296 @@ +"""Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestCStepping(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers that we will step to in main: + self.main_source = "main.c" + + @add_test_categories(['pyapi', 'basic_process']) + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr17932') + @expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr14437") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24777") + @expectedFailureNetBSD + def test_and_python_api(self): + """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + breakpoints_to_disable = [] + + break_1_in_main = target.BreakpointCreateBySourceRegex( + '// frame select 2, thread step-out while stopped at .c.1..', + self.main_source_spec) + self.assertTrue(break_1_in_main, VALID_BREAKPOINT) + breakpoints_to_disable.append(break_1_in_main) + + break_in_a = target.BreakpointCreateBySourceRegex( + '// break here to stop in a before calling b', self.main_source_spec) + self.assertTrue(break_in_a, VALID_BREAKPOINT) + breakpoints_to_disable.append(break_in_a) + + break_in_b = target.BreakpointCreateBySourceRegex( + '// thread step-out while stopped at .c.2..', self.main_source_spec) + self.assertTrue(break_in_b, VALID_BREAKPOINT) + breakpoints_to_disable.append(break_in_b) + + break_in_c = target.BreakpointCreateBySourceRegex( + '// Find the line number of function .c. here.', self.main_source_spec) + self.assertTrue(break_in_c, VALID_BREAKPOINT) + breakpoints_to_disable.append(break_in_c) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_1_in_main) + + if len(threads) != 1: + self.fail("Failed to stop at first breakpoint in main.") + + thread = threads[0] + + # Get the stop id and for fun make sure it increases: + old_stop_id = process.GetStopID() + + # Now step over, which should cause us to hit the breakpoint in "a" + thread.StepOver() + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_a) + if len(threads) != 1: + self.fail("Failed to stop at breakpoint in a.") + + # Check that the stop ID increases: + new_stop_id = process.GetStopID() + self.assertTrue( + new_stop_id > old_stop_id, + "Stop ID increases monotonically.") + + thread = threads[0] + + # Step over, and we should hit the breakpoint in b: + thread.StepOver() + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_b) + if len(threads) != 1: + self.fail("Failed to stop at breakpoint in b.") + thread = threads[0] + + # Now try running some function, and make sure that we still end up in the same place + # and with the same stop reason. + frame = thread.GetFrameAtIndex(0) + current_line = frame.GetLineEntry().GetLine() + current_file = frame.GetLineEntry().GetFileSpec() + current_bp = [] + current_bp.append(thread.GetStopReasonDataAtIndex(0)) + current_bp.append(thread.GetStopReasonDataAtIndex(1)) + + stop_id_before_expression = process.GetStopID() + stop_id_before_including_expressions = process.GetStopID(True) + + frame.EvaluateExpression("(int) printf (print_string)") + + frame = thread.GetFrameAtIndex(0) + self.assertTrue( + current_line == frame.GetLineEntry().GetLine(), + "The line stayed the same after expression.") + self.assertTrue( + current_file == frame.GetLineEntry().GetFileSpec(), + "The file stayed the same after expression.") + self.assertTrue( + thread.GetStopReason() == lldb.eStopReasonBreakpoint, + "We still say we stopped for a breakpoint.") + self.assertTrue(thread.GetStopReasonDataAtIndex(0) == current_bp[ + 0] and thread.GetStopReasonDataAtIndex(1) == current_bp[1], "And it is the same breakpoint.") + + # Also make sure running the expression didn't change the public stop id + # but did change if we are asking for expression stops as well. + stop_id_after_expression = process.GetStopID() + stop_id_after_including_expressions = process.GetStopID(True) + + self.assertTrue( + stop_id_before_expression == stop_id_after_expression, + "Expression calling doesn't change stop ID") + + self.assertTrue( + stop_id_after_including_expressions > stop_id_before_including_expressions, + "Stop ID including expressions increments over expression call.") + + # Do the same thing with an expression that's going to crash, and make + # sure we are still unchanged. + + frame.EvaluateExpression("((char *) 0)[0] = 'a'") + + frame = thread.GetFrameAtIndex(0) + self.assertTrue( + current_line == frame.GetLineEntry().GetLine(), + "The line stayed the same after expression.") + self.assertTrue( + current_file == frame.GetLineEntry().GetFileSpec(), + "The file stayed the same after expression.") + self.assertTrue( + thread.GetStopReason() == lldb.eStopReasonBreakpoint, + "We still say we stopped for a breakpoint.") + self.assertTrue(thread.GetStopReasonDataAtIndex(0) == current_bp[ + 0] and thread.GetStopReasonDataAtIndex(1) == current_bp[1], "And it is the same breakpoint.") + + # Now continue and make sure we just complete the step: + # Disable all our breakpoints first - sometimes the compiler puts two line table entries in for the + # breakpoint a "b" and we don't want to hit that. + for bkpt in breakpoints_to_disable: + bkpt.SetEnabled(False) + + process.Continue() + + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "a") + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) + + # And one more time should get us back to main: + process.Continue() + + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "main") + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) + + # Now make sure we can call a function, break in the called function, + # then have "continue" get us back out again: + frame = thread.GetFrameAtIndex(0) + frame = thread.GetFrameAtIndex(0) + current_line = frame.GetLineEntry().GetLine() + current_file = frame.GetLineEntry().GetFileSpec() + + break_in_b.SetEnabled(True) + options = lldb.SBExpressionOptions() + options.SetIgnoreBreakpoints(False) + options.SetFetchDynamicValue(False) + options.SetUnwindOnError(False) + frame.EvaluateExpression("b (4)", options) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, break_in_b) + + if len(threads) != 1: + self.fail("Failed to stop at breakpoint in b when calling b.") + thread = threads[0] + + # So do a step over here to make sure we can still do that: + + thread.StepOver() + + # See that we are still in b: + func_name = thread.GetFrameAtIndex(0).GetFunctionName() + self.assertTrue( + func_name == "b", + "Should be in 'b', were in %s" % + (func_name)) + + # Okay, now if we continue, we will finish off our function call and we + # should end up back in "a" as if nothing had happened: + process.Continue() + + self.assertTrue(thread.GetFrameAtIndex( + 0).GetLineEntry().GetLine() == current_line) + self.assertTrue(thread.GetFrameAtIndex( + 0).GetLineEntry().GetFileSpec() == current_file) + + # Now we are going to test step in targeting a function: + + break_in_b.SetEnabled(False) + + break_before_complex_1 = target.BreakpointCreateBySourceRegex( + '// Stop here to try step in targeting b.', self.main_source_spec) + self.assertTrue(break_before_complex_1, VALID_BREAKPOINT) + + break_before_complex_2 = target.BreakpointCreateBySourceRegex( + '// Stop here to try step in targeting complex.', self.main_source_spec) + self.assertTrue(break_before_complex_2, VALID_BREAKPOINT) + + break_before_complex_3 = target.BreakpointCreateBySourceRegex( + '// Stop here to step targeting b and hitting breakpoint.', self.main_source_spec) + self.assertTrue(break_before_complex_3, VALID_BREAKPOINT) + + break_before_complex_4 = target.BreakpointCreateBySourceRegex( + '// Stop here to make sure bogus target steps over.', self.main_source_spec) + self.assertTrue(break_before_complex_4, VALID_BREAKPOINT) + + threads = lldbutil.continue_to_breakpoint( + process, break_before_complex_1) + self.assertTrue(len(threads) == 1) + thread = threads[0] + break_before_complex_1.SetEnabled(False) + + thread.StepInto("b") + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "b") + + # Now continue out and stop at the next call to complex. This time + # step all the way into complex: + threads = lldbutil.continue_to_breakpoint( + process, break_before_complex_2) + self.assertTrue(len(threads) == 1) + thread = threads[0] + break_before_complex_2.SetEnabled(False) + + thread.StepInto("complex") + self.assertTrue(thread.GetFrameAtIndex( + 0).GetFunctionName() == "complex") + + # Now continue out and stop at the next call to complex. This time + # enable breakpoints in a and c and then step targeting b: + threads = lldbutil.continue_to_breakpoint( + process, break_before_complex_3) + self.assertTrue(len(threads) == 1) + thread = threads[0] + break_before_complex_3.SetEnabled(False) + + break_at_start_of_a = target.BreakpointCreateByName('a') + break_at_start_of_c = target.BreakpointCreateByName('c') + + thread.StepInto("b") + threads = lldbutil.get_stopped_threads( + process, lldb.eStopReasonBreakpoint) + + self.assertTrue(len(threads) == 1) + thread = threads[0] + stop_break_id = thread.GetStopReasonDataAtIndex(0) + self.assertTrue(stop_break_id == break_at_start_of_a.GetID() + or stop_break_id == break_at_start_of_c.GetID()) + + break_at_start_of_a.SetEnabled(False) + break_at_start_of_c.SetEnabled(False) + + process.Continue() + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "b") + + # Now continue out and stop at the next call to complex. This time + # enable breakpoints in a and c and then step targeting b: + threads = lldbutil.continue_to_breakpoint( + process, break_before_complex_4) + self.assertTrue(len(threads) == 1) + thread = threads[0] + break_before_complex_4.SetEnabled(False) + + thread.StepInto("NoSuchFunction") + self.assertTrue(thread.GetFrameAtIndex(0).GetFunctionName() == "main") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py new file mode 100644 index 00000000000..43ed10d8b1a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py @@ -0,0 +1,83 @@ +""" +Test thread stepping features in combination with frame select. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class ThreadSteppingTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to of function 'c'. + self.line1 = line_number( + 'main.c', '// Find the line number of function "c" here.') + self.line2 = line_number( + 'main.c', '// frame select 2, thread step-out while stopped at "c(1)"') + self.line3 = line_number( + 'main.c', '// thread step-out while stopped at "c(2)"') + self.line4 = line_number( + 'main.c', '// frame select 1, thread step-out while stopped at "c(3)"') + + def test_step_out_with_run_command(self): + """Exercise thread step-out and frame select followed by thread step-out.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Create a breakpoint inside function 'c'. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line1, num_expected_locations=1, loc_exact=True) + + # Now run the program. + self.runCmd("run", RUN_SUCCEEDED) + + # The process should be stopped at this point. + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* stopped']) + + # The frame #0 should correspond to main.c:32, the executable statement + # in function name 'c'. And frame #3 should point to main.c:37. + self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint"], + patterns=["frame #0.*main.c:%d" % self.line1, + "frame #3.*main.c:%d" % self.line2]) + + # We want to move the pc to frame #3. This can be accomplished by + # 'frame select 2', followed by 'thread step-out'. + self.runCmd("frame select 2") + self.runCmd("thread step-out") + self.expect("thread backtrace", STEP_OUT_SUCCEEDED, + substrs=["stop reason = step out"], + patterns=["frame #0.*main.c:%d" % self.line2]) + + # Let's move on to a single step-out case. + self.runCmd("process continue") + + # The process should be stopped at this point. + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* stopped']) + self.runCmd("thread step-out") + self.expect("thread backtrace", STEP_OUT_SUCCEEDED, + substrs=["stop reason = step out"], + patterns=["frame #0.*main.c:%d" % self.line3]) + + # Do another frame selct, followed by thread step-out. + self.runCmd("process continue") + + # The process should be stopped at this point. + self.expect("process status", PROCESS_STOPPED, + patterns=['Process .* stopped']) + self.runCmd("frame select 1") + self.runCmd("thread step-out") + self.expect("thread backtrace", STEP_OUT_SUCCEEDED, + substrs=["stop reason = step out"], + patterns=["frame #0.*main.c:%d" % self.line4]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/main.c new file mode 100644 index 00000000000..fce61bfd93e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/stepping/main.c @@ -0,0 +1,68 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int a(int); +int b(int); +int c(int); +const char *print_string = "aaaaaaaaaa\n"; + +int a(int val) +{ + int return_value = val; // basic break at the start of b + + if (val <= 1) + { + return_value = b(val); // break here to stop in a before calling b + } + else if (val >= 3) + { + return_value = c(val); + } + + return return_value; +} + +int b(int val) +{ + int rc = c(val); // thread step-out while stopped at "c(2)" + return rc; +} + +int c(int val) +{ + return val + 3; // Find the line number of function "c" here. +} + +int complex (int first, int second, int third) +{ + return first + second + third; // Step in targeting complex should stop here +} + +int main (int argc, char const *argv[]) +{ + int A1 = a(1); // frame select 2, thread step-out while stopped at "c(1)" + printf("a(1) returns %d\n", A1); + + int B2 = b(2); + printf("b(2) returns %d\n", B2); + + int A3 = a(3); // frame select 1, thread step-out while stopped at "c(3)" + printf("a(3) returns %d\n", A3); + + int A4 = complex (a(1), b(2), c(3)); // Stop here to try step in targeting b. + + int A5 = complex (a(2), b(3), c(4)); // Stop here to try step in targeting complex. + + int A6 = complex (a(4), b(5), c(6)); // Stop here to step targeting b and hitting breakpoint. + + int A7 = complex (a(5), b(6), c(7)); // Stop here to make sure bogus target steps over. + + printf ("I am using print_string: %s.\n", print_string); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/strings/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/strings/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/strings/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py new file mode 100644 index 00000000000..597a247178e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py @@ -0,0 +1,56 @@ +""" +Tests that C strings work as expected in expressions +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CStringsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """Tests that C strings work as expected in expressions""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + line = line_number('main.c', '// breakpoint 1') + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line, num_expected_locations=1, loc_exact=True) + + self.runCmd("process launch", RUN_SUCCEEDED) + + self.expect("expression -- a[2]", + patterns=["\((const )?char\) \$0 = 'c'"]) + + self.expect("expression -- z[2]", + startstr="(const char) $1 = 'x'") + + # On Linux, the expression below will test GNU indirect function calls. + self.expect("expression -- (int)strlen(\"hello\")", + startstr="(int) $2 = 5") + + self.expect("expression -- \"world\"[2]", + startstr="(const char) $3 = 'r'") + + self.expect("expression -- \"\"[0]", + startstr="(const char) $4 = '\\0'") + + self.expect("expr --raw -- \"hello\"", + substrs=['[0] = \'h\'', + '[5] = \'\\0\'']) + + self.expect("p \"hello\"", + substrs=['[6]) $', 'hello']) + + self.expect("p (char*)\"hello\"", + substrs=['(char *) $', ' = 0x', + 'hello']) + + self.expect("p (int)strlen(\"\")", + substrs=['(int) $', ' = 0']) + + self.expect("expression !z", + substrs=['false']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/strings/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/strings/main.c new file mode 100644 index 00000000000..3e7ead08478 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/strings/main.c @@ -0,0 +1,17 @@ +//===-- main.c ----------------------------------------------------*- C -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +int main() +{ + const char a[] = "abcde"; + const char *z = "vwxyz"; + + printf("%s %s", a, z); // breakpoint 1 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py new file mode 100644 index 00000000000..c8308c16011 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/main.c new file mode 100644 index 00000000000..356f139c0b2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/struct_types/main.c @@ -0,0 +1,46 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +struct things_to_sum { + int a; + int b; + int c; +}; + +int sum_things(struct things_to_sum tts) +{ + return tts.a + tts.b + tts.c; +} + +int main (int argc, char const *argv[]) +{ + struct point_tag { + int x; + int y; + char padding[0]; + }; //% self.expect("frame variable pt.padding[0]", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["pt.padding[0] = "]) + //% self.expect("frame variable pt.padding[1]", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["pt.padding[1] = "]) + //% self.expect("expression -- (pt.padding[0])", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["(char)", " = "]) + //% self.expect("image lookup -t point_tag", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ['padding[]']) + + struct {} empty; + //% self.expect("frame variable empty", substrs = ["empty = {}"]) + //% self.expect("expression -- sizeof(empty)", substrs = ["= 0"]) + + struct rect_tag { + struct point_tag bottom_left; + struct point_tag top_right; + }; + struct point_tag pt = { 2, 3, {} }; + struct rect_tag rect = {{1, 2, {}}, {3, 4, {}}}; + struct things_to_sum tts = { 2, 3, 4 }; + + int sum = sum_things(tts); //% self.expect("expression -- &pt == (struct point_tag*)0", substrs = ['false']) + //% self.expect("expression -- sum_things(tts)", substrs = ['9']) + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/Makefile new file mode 100644 index 00000000000..b26ce5c8b14 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/Makefile @@ -0,0 +1,8 @@ +C_SOURCES := main.c + +DYLIB_NAME := a +DYLIB_C_SOURCES := a.c + +ENABLE_THREADS := YES + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py new file mode 100644 index 00000000000..b1fd2b8d031 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py @@ -0,0 +1,95 @@ +"""Test that thread-local storage can be read correctly.""" + + + +import unittest2 +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TlsGlobalTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + + if self.getPlatform() == "freebsd" or self.getPlatform() == "linux": + # LD_LIBRARY_PATH must be set so the shared libraries are found on + # startup + if "LD_LIBRARY_PATH" in os.environ: + self.runCmd( + "settings set target.env-vars " + + self.dylibPath + + "=" + + os.environ["LD_LIBRARY_PATH"] + + ":" + + self.getBuildDir()) + else: + self.runCmd("settings set target.env-vars " + + self.dylibPath + "=" + self.getBuildDir()) + self.addTearDownHook( + lambda: self.runCmd( + "settings remove target.env-vars " + + self.dylibPath)) + + # TLS works differently on Windows, this would need to be implemented + # separately. + @skipIfWindows + @expectedFailureAll( + bugnumber="llvm.org/pr28392", + oslist=no_match( + lldbplatformutil.getDarwinOSTriples())) + def test(self): + """Test thread-local storage.""" + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + if self.platformIsDarwin(): + self.registerSharedLibrariesWithTarget(target, ['liba.dylib']) + + line1 = line_number('main.c', '// thread breakpoint') + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line1, num_expected_locations=1, loc_exact=True) + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.runCmd("process status", "Get process status") + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # BUG: sometimes lldb doesn't change threads to the stopped thread. + # (unrelated to this test). + self.runCmd("thread select 2", "Change thread") + + # Check that TLS evaluates correctly within the thread. + self.expect("expr var_static", VARIABLES_DISPLAYED_CORRECTLY, + patterns=["\(int\) \$.* = 88"]) + self.expect("expr var_shared", VARIABLES_DISPLAYED_CORRECTLY, + patterns=["\(int\) \$.* = 66"]) + + # Continue on the main thread + line2 = line_number('main.c', '// main breakpoint') + lldbutil.run_break_set_by_file_and_line( + self, "main.c", line2, num_expected_locations=1, loc_exact=True) + self.runCmd("continue", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.runCmd("process status", "Get process status") + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # BUG: sometimes lldb doesn't change threads to the stopped thread. + # (unrelated to this test). + self.runCmd("thread select 1", "Change thread") + + # Check that TLS evaluates correctly within the main thread. + self.expect("expr var_static", VARIABLES_DISPLAYED_CORRECTLY, + patterns=["\(int\) \$.* = 44"]) + self.expect("expr var_shared", VARIABLES_DISPLAYED_CORRECTLY, + patterns=["\(int\) \$.* = 33"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/a.c new file mode 100644 index 00000000000..00803964e61 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/a.c @@ -0,0 +1,23 @@ +//===-- a.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <unistd.h> + +__thread int var_shared = 33; + +int +touch_shared() +{ + return var_shared; +} + +void shared_check() +{ + var_shared *= 2; + usleep(1); // shared thread breakpoint +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/main.c new file mode 100644 index 00000000000..c9c1e681dc0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/tls_globals/main.c @@ -0,0 +1,41 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <pthread.h> +#include <unistd.h> + +void shared_check(); +// On some OS's (darwin) you must actually access a thread local variable +// before you can read it +int +touch_shared(); + +// Create some TLS storage within the static executable. +__thread int var_static = 44; + +void *fn_static(void *param) +{ + var_static *= 2; + shared_check(); + usleep(1); // thread breakpoint + for(;;) + usleep(1); +} + +int main (int argc, char const *argv[]) +{ + pthread_t handle; + pthread_create(&handle, NULL, &fn_static, NULL); + touch_shared(); + for (; var_static;) + { + usleep(1); // main breakpoint + } + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py new file mode 100644 index 00000000000..cbbb6362381 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py @@ -0,0 +1,52 @@ +"""Look up type information for typedefs of same name at different lexical scope and check for correct display.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TypedefTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(compiler="clang", bugnumber="llvm.org/pr19238") + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr25626 expectedFailureClang fails on FreeBSD") + def test_typedef(self): + """Test 'image lookup -t a' and check for correct display at different scopes.""" + self.build() + self.image_lookup_for_multiple_typedefs() + + def image_lookup_for_multiple_typedefs(self): + """Test 'image lookup -t a' at different scopes and check for correct display.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + typearray = ( + "float", + "float", + "char", + "double *", + "float", + "int", + "double", + "float", + "float") + arraylen = len(typearray) + 1 + for i in range(1, arraylen): + loc_line = line_number( + 'main.c', '// Set break point ' + str(i) + '.') + lldbutil.run_break_set_by_file_and_line( + self, "main.c", loc_line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + for t in typearray: + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + self.expect("image lookup -t a", DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=['name = "' + t + '"']) + self.runCmd("continue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/typedef/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/typedef/main.c new file mode 100644 index 00000000000..467612e9b37 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/typedef/main.c @@ -0,0 +1,45 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +void test() +{ + typedef double * a; + a b = 0; // Set break point 4. +} +int main (int argc, char const *argv[]) +{ + typedef float a; + int i = 0; // Set break point 1. + i++; + a floatvariable = 2.7; // Set break point 2. + { + typedef char a; + i++; + a charvariable = 'a'; // Set break point 3. + test(); + } + { + int c = 0; + c++; // Set break point 5. + for(i = 0 ; i < 1 ; i++) + { + typedef int a; + a b; + b = 7; // Set break point 6. + } + for(i = 0 ; i < 1 ; i++) + { + typedef double a; + a b; + b = 3.14; // Set break point 7. + } + c = 1; // Set break point 8. + } + floatvariable = 2.5; + floatvariable = 2.8; // Set break point 9. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unicode/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unicode/Makefile new file mode 100644 index 00000000000..a40a666476c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unicode/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -finput-charset=UTF-8 -fextended-identifiers -std=c99 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unicode/TestUnicodeSymbols.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unicode/TestUnicodeSymbols.py new file mode 100644 index 00000000000..9eb25e4d105 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unicode/TestUnicodeSymbols.py @@ -0,0 +1,21 @@ +# coding=utf8 +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * + + +class TestUnicodeSymbols(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(compiler="clang", compiler_version=['<', '7.0']) + def test_union_members(self): + self.build() + spec = lldb.SBModuleSpec() + spec.SetFileSpec(lldb.SBFileSpec(self.getBuildArtifact("a.out"))) + module = lldb.SBModule(spec) + self.assertTrue(module.IsValid()) + mytype = module.FindFirstType("foobár") + self.assertTrue(mytype.IsValid()) + self.assertTrue(mytype.IsPointerType()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unicode/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unicode/main.c new file mode 100644 index 00000000000..ae44dd0edfa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unicode/main.c @@ -0,0 +1,5 @@ +typedef void *foob\u00E1r; +foob\u00E1r X = 0; +int main() { + return (long)X; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unions/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unions/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unions/TestUnionMembers.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unions/TestUnionMembers.py new file mode 100644 index 00000000000..4965df2d809 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unions/TestUnionMembers.py @@ -0,0 +1,52 @@ +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class TestUnionMembers(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_union_members(self): + self._load_exe() + + # Set breakpoints + bp = self.target.BreakpointCreateBySourceRegex( + "Break here", self.src_file_spec) + self.assertTrue( + bp.IsValid() and bp.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Launch the process + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(self.process.IsValid(), PROCESS_IS_VALID) + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid()) + frame = thread.GetSelectedFrame() + self.assertTrue(frame.IsValid()) + + val = frame.EvaluateExpression("u") + self.assertTrue(val.IsValid()) + val = frame.EvaluateExpression("u.s") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetNumChildren(), 2) + + def _load_exe(self): + self.build() + + src_file = os.path.join(self.getSourceDir(), "main.c") + self.src_file_spec = lldb.SBFileSpec(src_file) + self.assertTrue(self.src_file_spec.IsValid(), "breakpoint file") + + # Get the path of the executable + exe_path = self.getBuildArtifact("a.out") + + # Load the executable + self.target = self.dbg.CreateTarget(exe_path) + self.assertTrue(self.target.IsValid(), VALID_TARGET) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unions/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unions/main.c new file mode 100644 index 00000000000..2c6a7d1e782 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/unions/main.c @@ -0,0 +1,18 @@ +#include <stdint.h> + +union S +{ + int32_t n; // occupies 4 bytes + uint16_t s[2]; // occupies 4 bytes + uint8_t c; // occupies 1 byte +}; // the whole union occupies 4 bytes + +int main() +{ + union S u; + + u.s[0] = 1234; + u.s[1] = 4321; + + return 0; // Break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/vla/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/vla/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/vla/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/vla/TestVLA.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/vla/TestVLA.py new file mode 100644 index 00000000000..09439e2bc4b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/vla/TestVLA.py @@ -0,0 +1,45 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil + + +class TestVLA(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(compiler="clang", compiler_version=['<', '8.0']) + def test_variable_list(self): + self.build() + _, process, _, _ = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec('main.c')) + + # Make sure no helper expressions show up in frame variable. + var_opts = lldb.SBVariablesOptions() + var_opts.SetIncludeArguments(False) + var_opts.SetIncludeLocals(True) + var_opts.SetInScopeOnly(True) + var_opts.SetIncludeStatics(False) + var_opts.SetIncludeRuntimeSupportValues(False) + var_opts.SetUseDynamic(lldb.eDynamicCanRunTarget) + all_locals = self.frame().GetVariables(var_opts) + for value in all_locals: + self.assertFalse("vla_expr" in value.name) + + @decorators.skipIf(compiler="clang", compiler_version=['<', '8.0']) + def test_vla(self): + self.build() + _, process, _, _ = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec('main.c')) + + def test(a, array): + for i in range(a): + self.expect("fr v vla[%d]"%i, substrs=["int", "%d"%(a-i)]) + self.expect("expr vla[%d]"%i, substrs=["int", "%d"%(a-i)]) + self.expect("fr v vla", substrs=array) + self.expect("expr vla", error=True, substrs=["incomplete"]) + + test(2, ["int []", "[0] = 2, [1] = 1"]) + process.Continue() + test(4, ["int []", "[0] = 4, [1] = 3, [2] = 2, [3] = 1"]) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/vla/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/vla/main.c new file mode 100644 index 00000000000..ba9cc185560 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/c/vla/main.c @@ -0,0 +1,15 @@ +void pause() {} + +int foo(int a) { + int vla[a]; + + for (int i = 0; i < a; ++i) + vla[i] = a-i; + + pause(); // break here + return vla[a-1]; +} + +int main (void) { + return foo(2) + foo(4); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/Makefile new file mode 100644 index 00000000000..4c053a09c75 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/Makefile @@ -0,0 +1,7 @@ +# There is no guaranteed order in which the linker will order these +# files, so we just have a lot of them to make it unlikely that we hit +# the right one first by pure luck. + +CXX_SOURCES := main.cpp a.cpp b.cpp c.cpp d.cpp e.cpp f.cpp g.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/TestCPPAccelerator.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/TestCPPAccelerator.py new file mode 100644 index 00000000000..3705e95c600 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/TestCPPAccelerator.py @@ -0,0 +1,31 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CPPAcceleratorTableTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIf(debug_info=no_match(["dwarf"])) + def test(self): + """Test that type lookups fail early (performance)""" + self.build() + logfile = self.getBuildArtifact('dwarf.log') + self.expect('log enable dwarf lookups -f' + logfile) + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, 'break here', lldb.SBFileSpec('main.cpp')) + # Pick one from the middle of the list to have a high chance + # of it not being in the first file looked at. + self.expect('frame variable inner_d') + + log = open(logfile, 'r') + n = 0 + for line in log: + if re.findall(r'[abcdefg]\.o: FindByNameAndTag\(\)', line): + self.assertTrue("d.o" in line) + n += 1 + + self.assertEqual(n, 1, log) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/a.cpp new file mode 100644 index 00000000000..d9f758e1991 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/a.cpp @@ -0,0 +1,2 @@ +#include "source.h" +CLASS(A) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/b.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/b.cpp new file mode 100644 index 00000000000..a0cdffa14f1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/b.cpp @@ -0,0 +1,2 @@ +#include "source.h" +CLASS(B) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/c.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/c.cpp new file mode 100644 index 00000000000..1bd7172b771 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/c.cpp @@ -0,0 +1,2 @@ +#include "source.h" +CLASS(C) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/d.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/d.cpp new file mode 100644 index 00000000000..e43c2ad05aa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/d.cpp @@ -0,0 +1,2 @@ +#include "source.h" +CLASS(D) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/e.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/e.cpp new file mode 100644 index 00000000000..a3008f71f65 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/e.cpp @@ -0,0 +1,2 @@ +#include "source.h" +CLASS(E) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/f.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/f.cpp new file mode 100644 index 00000000000..77df296183e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/f.cpp @@ -0,0 +1,2 @@ +#include "source.h" +CLASS(F) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/g.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/g.cpp new file mode 100644 index 00000000000..e1446918891 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/g.cpp @@ -0,0 +1,2 @@ +#include "source.h" +CLASS(G) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/main.cpp new file mode 100644 index 00000000000..b7eb252bad8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/main.cpp @@ -0,0 +1,28 @@ +#define CLASS(NAME) \ + class NAME { \ + public: \ + struct Inner; \ + Inner *i = nullptr; \ + }; \ +NAME::Inner &getInner##NAME(); + +CLASS(A) +CLASS(B) +CLASS(C) +CLASS(D) +CLASS(E) +CLASS(F) +CLASS(G) + +int main() +{ + A::Inner &inner_a = getInnerA(); + B::Inner &inner_b = getInnerB(); + C::Inner &inner_c = getInnerC(); + D::Inner &inner_d = getInnerD(); + E::Inner &inner_e = getInnerE(); + F::Inner &inner_f = getInnerF(); + G::Inner &inner_g = getInnerG(); + + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/source.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/source.h new file mode 100644 index 00000000000..214e7dada2e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/accelerator-table/source.h @@ -0,0 +1,12 @@ +#define CLASS(NAME) \ + class NAME { \ + public: \ + class Inner { \ + int j = #NAME[0]; \ + }; \ + Inner *i = nullptr; \ + }; \ + \ + static NAME::Inner inner; \ + static NAME obj; \ + NAME::Inner &getInner##NAME() { return inner; } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py new file mode 100644 index 00000000000..fe3a8324348 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py @@ -0,0 +1,41 @@ +""" +Tests that auto types work +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CPPAutoTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + compiler="gcc", + bugnumber="GCC generates incomplete debug info") + @expectedFailureAll(oslist=['windows'], bugnumber="llvm.org/pr26339") + @expectedFailureNetBSD + def test_with_run_command(self): + """Test that auto types work in the expression parser""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + line = line_number('main.cpp', '// break here') + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) + + self.runCmd("process launch", RUN_SUCCEEDED) + + self.expect('expr auto f = 123456; f', substrs=['int', '123456']) + self.expect( + 'expr struct Test { int x; int y; Test() : x(123), y(456) {} }; auto t = Test(); t', + substrs=[ + 'Test', + '123', + '456']) + self.expect( + 'expr auto s = helloworld; s', + substrs=[ + 'string', + 'hello world']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/main.cpp new file mode 100644 index 00000000000..d411af67911 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/auto/main.cpp @@ -0,0 +1,20 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <string> + +int main() +{ + std::string helloworld("hello world"); + + // Ensure std::string copy constructor is present in the binary, as we will + // use it in an expression. + std::string other = helloworld; + + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bitfields/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bitfields/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bitfields/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bitfields/TestCppBitfields.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bitfields/TestCppBitfields.py new file mode 100644 index 00000000000..1b362e6b04f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bitfields/TestCppBitfields.py @@ -0,0 +1,105 @@ +"""Show bitfields and check that they display correctly.""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CppBitfieldsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + + # BitFields exhibit crashes in record layout on Windows + # (http://llvm.org/pr21800) + @skipIfWindows + def test_and_run_command(self): + """Test 'frame variable ...' on a variable with bitfields.""" + self.build() + + lldbutil.run_to_source_breakpoint(self, '// Set break point at this line.', + lldb.SBFileSpec("main.cpp", False)) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.expect("expr (lba.a)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['unsigned int', '2']) + self.expect("expr (lbb.b)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['unsigned int', '3']) + self.expect("expr (lbc.c)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['unsigned int', '4']) + self.expect("expr (lbd.a)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['unsigned int', '5']) + self.expect("expr (clang_example.f.a)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['uint64_t', '1']) + + self.expect( + "frame variable --show-types lba", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(int:32) = ', + '(unsigned int:20) a = 2', + ]) + + self.expect( + "frame variable --show-types lbb", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(unsigned int:1) a = 1', + '(int:31) =', + '(unsigned int:20) b = 3', + ]) + + self.expect( + "frame variable --show-types lbc", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(int:22) =', + '(unsigned int:1) a = 1', + '(unsigned int:1) b = 0', + '(unsigned int:5) c = 4', + '(unsigned int:1) d = 1', + '(int:2) =', + '(unsigned int:20) e = 20', + ]) + + self.expect( + "frame variable --show-types lbd", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(char [3]) arr = "ab"', + '(int:32) =', + '(unsigned int:20) a = 5', + ]) + + self.expect( + "frame variable --show-types clang_example", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(int:22) =', + '(uint64_t:1) a = 1', + '(uint64_t:1) b = 0', + '(uint64_t:1) c = 1', + '(uint64_t:1) d = 0', + '(uint64_t:1) e = 1', + '(uint64_t:1) f = 0', + '(uint64_t:1) g = 1', + '(uint64_t:1) h = 0', + '(uint64_t:1) i = 1', + '(uint64_t:1) j = 0', + '(uint64_t:1) k = 1', + ]) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bitfields/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bitfields/main.cpp new file mode 100644 index 00000000000..e43bf8c138e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bitfields/main.cpp @@ -0,0 +1,81 @@ +#include <stdint.h> + +int main(int argc, char const *argv[]) { + struct LargeBitsA { + unsigned int : 30, a : 20; + } lba; + + struct LargeBitsB { + unsigned int a : 1, : 11, : 12, b : 20; + } lbb; + + struct LargeBitsC { + unsigned int : 13, : 9, a : 1, b : 1, c : 5, d : 1, e : 20; + } lbc; + + struct LargeBitsD { + char arr[3]; + unsigned int : 30, a : 20; + } lbd; + + // This case came up when debugging clang and models RecordDeclBits + struct BitExampleFromClangDeclContext { + class fields { + uint64_t : 13; + uint64_t : 9; + + uint64_t a: 1; + uint64_t b: 1; + uint64_t c: 1; + uint64_t d: 1; + uint64_t e: 1; + uint64_t f: 1; + uint64_t g: 1; + uint64_t h: 1; + uint64_t i: 1; + uint64_t j: 1; + uint64_t k: 1; + + // In order to reproduce the crash for this case we need the + // members of fields to stay private :-( + friend struct BitExampleFromClangDeclContext; + }; + + union { + struct fields f; + }; + + BitExampleFromClangDeclContext() { + f.a = 1; + f.b = 0; + f.c = 1; + f.d = 0; + f.e = 1; + f.f = 0; + f.g = 1; + f.h = 0; + f.i = 1; + f.j = 0; + f.k = 1; + } + } clang_example; + + lba.a = 2; + + lbb.a = 1; + lbb.b = 3; + + lbc.a = 1; + lbc.b = 0; + lbc.c = 4; + lbc.d = 1; + lbc.e = 20; + + lbd.arr[0] = 'a'; + lbd.arr[1] = 'b'; + lbd.arr[2] = '\0'; + lbd.a = 5; + + + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py new file mode 100644 index 00000000000..27ea773c5db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py @@ -0,0 +1,28 @@ +""" +Tests that bool types work +""" +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class CPPBoolTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """Test that bool types work in the expression parser""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + line = line_number('main.cpp', '// breakpoint 1') + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) + + self.runCmd("process launch", RUN_SUCCEEDED) + + self.expect("expression -- bool second_bool = my_bool; second_bool", + startstr="(bool) $0 = false") + + self.expect("expression -- my_bool = true", + startstr="(bool) $1 = true") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/main.cpp new file mode 100644 index 00000000000..a14cc690da7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/bool/main.cpp @@ -0,0 +1,16 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +int main() +{ + bool my_bool = false; + + printf("%s\n", my_bool ? "true" : "false"); // breakpoint 1 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/Makefile new file mode 100644 index 00000000000..6afea39f81c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := nested.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py new file mode 100644 index 00000000000..32c974810f7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py @@ -0,0 +1,83 @@ +""" +Test lldb breakpoint command for CPP methods & functions in a namespace. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CPPBreakpointCommandsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def make_breakpoint(self, name, type, expected_num_locations): + bkpt = self.target.BreakpointCreateByName(name, + type, + self.a_out_module, + self.nested_comp_unit) + num_locations = bkpt.GetNumLocations() + self.assertTrue( + num_locations == expected_num_locations, + "Wrong number of locations for '%s', expected: %d got: %d" % + (name, + expected_num_locations, + num_locations)) + return bkpt + + def test_cpp_breakpoint_cmds(self): + """Test a sequence of breakpoint command add, list, and delete.""" + self.build() + + exe = self.getBuildArtifact("a.out") + + # Create a target from the debugger. + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + self.a_out_module = lldb.SBFileSpecList() + self.a_out_module.Append(lldb.SBFileSpec(exe)) + + self.nested_comp_unit = lldb.SBFileSpecList() + self.nested_comp_unit.Append(lldb.SBFileSpec("nested.cpp")) + + # First provide ONLY the method name. This should get everybody... + self.make_breakpoint("Function", + lldb.eFunctionNameTypeAuto, + 5) + + # Now add the Baz class specifier. This should get the version contained in Bar, + # AND the one contained in :: + self.make_breakpoint("Baz::Function", + lldb.eFunctionNameTypeAuto, + 2) + + # Then add the Bar::Baz specifier. This should get the version + # contained in Bar only + self.make_breakpoint("Bar::Baz::Function", + lldb.eFunctionNameTypeAuto, + 1) + + self.make_breakpoint("Function", + lldb.eFunctionNameTypeMethod, + 3) + + self.make_breakpoint("Baz::Function", + lldb.eFunctionNameTypeMethod, + 2) + + self.make_breakpoint("Bar::Baz::Function", + lldb.eFunctionNameTypeMethod, + 1) + + self.make_breakpoint("Function", + lldb.eFunctionNameTypeBase, + 2) + + self.make_breakpoint("Bar::Function", + lldb.eFunctionNameTypeBase, + 1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/nested.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/nested.cpp new file mode 100644 index 00000000000..740649622ca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/nested.cpp @@ -0,0 +1,76 @@ +#include <stdio.h> + +namespace Foo +{ + namespace Bar + { + class Baz + { + public: + Baz (int value):m_value(value) {} + int Function () + { + printf ("%s returning: %d.\n", __FUNCTION__, m_value); + return m_value + 1; + } + private: + int m_value; + }; + + class Baz2 + { + public: + Baz2 (int value):m_value(value) {} + int Function () + { + printf ("%s returning: %d.\n", __FUNCTION__, m_value); + return m_value + 2; + } + private: + int m_value; + }; + + static int bar_value = 20; + int Function () + { + printf ("%s returning: %d.\n", __FUNCTION__, bar_value); + return bar_value + 3; + } + } +} + +class Baz +{ +public: + Baz (int value):m_value(value) {} + int Function () + { + printf ("%s returning: %d.\n", __FUNCTION__, m_value); + return m_value + 4; + } +private: + int m_value; +}; + +int +Function () +{ + printf ("I am a global function, I return 333.\n"); + return 333; +} + +int main () +{ + Foo::Bar::Baz mine(200); + Foo::Bar::Baz2 mine2(300); + ::Baz bare_baz (500); + + printf ("Yup, got %d from Baz.\n", mine.Function()); + printf ("Yup, got %d from Baz.\n", mine2.Function()); + printf ("Yup, got %d from Baz.\n", bare_baz.Function()); + printf ("And got %d from Bar.\n", Foo::Bar::Function()); + printf ("And got %d from ::.\n", ::Function()); + + return 0; + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/Makefile new file mode 100644 index 00000000000..dc53622129f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES = main.cpp a.cpp +CFLAGS_EXTRAS = $(MANDATORY_CXXMODULE_BUILD_CFLAGS) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/TestBreakpointInMemberFuncWNonPrimitiveParams.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/TestBreakpointInMemberFuncWNonPrimitiveParams.py new file mode 100644 index 00000000000..1e46f73cb29 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/TestBreakpointInMemberFuncWNonPrimitiveParams.py @@ -0,0 +1,26 @@ +""" +This is a regression test for an assert that happens while setting a breakpoint. +The root cause of the assert was attempting to add a ParmVarDecl to a CXXRecordDecl +when it should have been added to a CXXMethodDecl. + +We can reproduce with a module build and setting a breakpoint in a member function +of a class with a non-primitive type as a parameter. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestBreakpointInMemberFuncWNonPrimitiveParams(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(["gmodules"]) + def test_breakpint_in_member_func_w_non_primitie_params(self): + self.build() + + (self.target, self.process, _, bkpt) = lldbutil.run_to_source_breakpoint(self, '// break here', + lldb.SBFileSpec("main.cpp", False)) + + self.runCmd("b a.cpp:11"); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/a.cpp new file mode 100644 index 00000000000..64e142c5379 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/a.cpp @@ -0,0 +1,14 @@ +#include "a.h" + +bool A::b(int x) { + if (x) + return true; + + return false; +} + +bool B::member_func_a(A a) { + return a.b(10); // We will try and add a breakpoint here which + // trigger an assert since we will attempt to + // to add ParamVarDecl a to CXXRecordDecl A +}; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/a.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/a.h new file mode 100644 index 00000000000..cb31d3efe8f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/a.h @@ -0,0 +1,7 @@ +struct A { + bool b(int x); +}; + +struct B { + bool member_func_a(A a); +}; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/main.cpp new file mode 100644 index 00000000000..779ef04072b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/main.cpp @@ -0,0 +1,15 @@ +#include "a.h" +#include <cstdio> + +bool foo() { + A a1; + B b1; + + return b1.member_func_a(a1); // break here +} + +int main() { + int x = 0; + + return foo(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/module.modulemap b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/module.modulemap new file mode 100644 index 00000000000..bbd9d674c94 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/breakpoint_in_member_func_w_non_primitive_params/module.modulemap @@ -0,0 +1,3 @@ +module A { + header "a.h" +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py new file mode 100644 index 00000000000..b6274b3d266 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py @@ -0,0 +1,35 @@ +""" +Tests calling a function by basename +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CallCPPFunctionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.line = line_number('main.cpp', '// breakpoint') + + def test_with_run_command(self): + """Test calling a function by basename""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("process launch", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect("expression -- a_function_to_call()", + startstr="(int) $0 = 0") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/main.cpp new file mode 100644 index 00000000000..61a5e9d21ab --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/call-function/main.cpp @@ -0,0 +1,11 @@ +#include <stdio.h> + +int a_function_to_call() +{ + return 0; +} + +int main() +{ + printf("%d\n", a_function_to_call()); // breakpoint +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py new file mode 100644 index 00000000000..080c051de98 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py @@ -0,0 +1,99 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestCppChainedCalls(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + self.build() + + # Get main source file + src_file = "main.cpp" + src_file_spec = lldb.SBFileSpec(src_file) + self.assertTrue(src_file_spec.IsValid(), "Main source file") + + # Get the path of the executable + exe_path = self.getBuildArtifact("a.out") + + # Load the executable + target = self.dbg.CreateTarget(exe_path) + self.assertTrue(target.IsValid(), VALID_TARGET) + + # Break on main function + main_breakpoint = target.BreakpointCreateBySourceRegex( + "break here", src_file_spec) + self.assertTrue( + main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Launch the process + args = None + env = None + process = target.LaunchSimple( + args, env, self.get_process_working_directory()) + self.assertTrue(process.IsValid(), PROCESS_IS_VALID) + + # Get the thread of the process + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + + # Get frame for current thread + frame = thread.GetSelectedFrame() + + # Test chained calls + test_result = frame.EvaluateExpression("get(set(true))") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "true", + "get(set(true)) = true") + + test_result = frame.EvaluateExpression("get(set(false))") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(set(false)) = false") + + test_result = frame.EvaluateExpression("get(t & f)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(t & f) = false") + + test_result = frame.EvaluateExpression("get(f & t)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(f & t) = false") + + test_result = frame.EvaluateExpression("get(t & t)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "true", + "get(t & t) = true") + + test_result = frame.EvaluateExpression("get(f & f)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(f & f) = false") + + test_result = frame.EvaluateExpression("get(t & f)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(t & f) = false") + + test_result = frame.EvaluateExpression("get(f) && get(t)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(f) && get(t) = false") + + test_result = frame.EvaluateExpression("get(f) && get(f)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "get(f) && get(t) = false") + + test_result = frame.EvaluateExpression("get(t) && get(t)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "true", + "get(t) && get(t) = true") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/main.cpp new file mode 100644 index 00000000000..a888c3f6c55 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/chained-calls/main.cpp @@ -0,0 +1,33 @@ +class Bool { +public: + Bool operator&(const Bool other) + { + Bool result; + result.value = value && other.value; + return result; + } + + bool value; +}; + +bool get(Bool object) +{ + return object.value; +} + +Bool set(bool value) +{ + Bool result; + result.value = value; + return result; +} + +int main() +{ + Bool t = set(true); + Bool f = set(false); + get(t); + get(f); + get(t & f); + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/.categories new file mode 100644 index 00000000000..fe1da0247c6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/.categories @@ -0,0 +1 @@ +dataformatters diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/Makefile new file mode 100644 index 00000000000..64fd6effcee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp +CFLAGS :=-g -O0 -std=c++11 + +clean: OBJECTS+=$(wildcard main.d.*) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py new file mode 100644 index 00000000000..986d9e59cdf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py @@ -0,0 +1,119 @@ +# coding=utf8 +""" +Test that the C++11 support for char16_t and char32_t works correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class Char1632TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.cpp. + self.source = 'main.cpp' + self.lines = [line_number(self.source, '// breakpoint1'), + line_number(self.source, '// breakpoint2')] + + @expectedFailureAll( + compiler="icc", + bugnumber="ICC (13.1) does not emit the DW_TAG_base_type for char16_t and char32_t.") + def test(self): + """Test that the C++11 support for char16_t and char32_t works correctly.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set breakpoints + for line in self.lines: + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", line) + + # Now launch the process, and do not stop at entry point and stop at + # breakpoint1 + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.Launch() failed") + + if self.TraceOn(): + self.runCmd("frame variable") + + # Check that we correctly report the const types + self.expect( + "frame variable cs16 cs32", + substrs=[ + '(const char16_t *) cs16 = ', + '(const char32_t *) cs32 = ', + 'u"hello world ྒྙྐ"', + 'U"hello world ྒྙྐ"']) + + # Check that we correctly report the non-const types + self.expect( + "frame variable s16 s32", + substrs=[ + '(char16_t *) s16 = ', + '(char32_t *) s32 = ', + 'u"ﺸﺵۻ"', + 'U"ЕЙРГЖО"']) + + # Check that we correctly report the array types + self.expect( + "frame variable as16 as32", + patterns=[ + '\(char16_t \[[0-9]+\]\) as16 = ', + '\(char32_t \[[0-9]+\]\) as32 = '], + substrs=[ + 'u"ﺸﺵۻ"', + 'U"ЕЙРГЖО"']) + + self.runCmd("next") # step to after the string is nullified + + # check that we don't crash on NULL + self.expect("frame variable s32", + substrs=['(char32_t *) s32 = 0x00000000']) + + # continue and hit breakpoint2 + self.runCmd("continue") + + # check that the new strings show + self.expect( + "frame variable s16 s32", + substrs=[ + '(char16_t *) s16 = 0x', + '(char32_t *) s32 = ', + '"色ハ匂ヘト散リヌルヲ"', + '"෴"']) + + # check the same as above for arrays + self.expect( + "frame variable as16 as32", + patterns=[ + '\(char16_t \[[0-9]+\]\) as16 = ', + '\(char32_t \[[0-9]+\]\) as32 = '], + substrs=[ + '"色ハ匂ヘト散リヌルヲ"', + '"෴"']) + + # check that zero values are properly handles + self.expect('frame variable cs16_zero', substrs=["U+0000 u'\\0'"]) + self.expect( + 'frame variable cs32_zero', + substrs=["U+0x00000000 U'\\0'"]) + self.expect('expression cs16_zero', substrs=["U+0000 u'\\0'"]) + self.expect('expression cs32_zero', substrs=["U+0x00000000 U'\\0'"]) + + # Check that we can run expressions that return charN_t + self.expect("expression u'a'", substrs=['(char16_t) $', "61 u'a'"]) + self.expect("expression U'a'", substrs=['(char32_t) $', "61 U'a'"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/main.cpp new file mode 100644 index 00000000000..8cd0cfc77c5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char1632_t/main.cpp @@ -0,0 +1,43 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <assert.h> +#include <string> + +#define UASZ 64 + +template<class T, int N> +void copy_char_seq (T (&arr)[N], const T* src) +{ + size_t src_len = std::char_traits<T>::length(src); + assert(src_len < N); + + std::char_traits<T>::copy(arr, src, src_len); + arr[src_len] = 0; +} + +int main (int argc, char const *argv[]) +{ + char16_t as16[UASZ]; + char32_t as32[UASZ]; + auto cs16_zero = (char16_t)0; + auto cs32_zero = (char32_t)0; + auto cs16 = u"hello world ྒྙྐ"; + auto cs32 = U"hello world ྒྙྐ"; + char16_t *s16 = (char16_t *)u"ﺸﺵۻ"; + char32_t *s32 = (char32_t *)U"ЕЙРГЖО"; + copy_char_seq(as16, s16); + copy_char_seq(as32, s32); + s32 = nullptr; // breakpoint1 + s32 = (char32_t *)U"෴"; + s16 = (char16_t *)u"色ハ匂ヘト散リヌルヲ"; + copy_char_seq(as16, s16); + copy_char_seq(as32, s32); + s32 = nullptr; // breakpoint2 + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char8_t/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char8_t/Makefile new file mode 100644 index 00000000000..e7c9938b5a8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char8_t/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp +CXXFLAGS_EXTRAS := -std=c++2a -fchar8_t + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char8_t/TestCxxChar8_t.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char8_t/TestCxxChar8_t.py new file mode 100644 index 00000000000..e7f2c1afbdd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char8_t/TestCxxChar8_t.py @@ -0,0 +1,39 @@ +# coding=utf8 +""" +Test that C++ supports char8_t correctly. +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class CxxChar8_tTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(compiler="clang", compiler_version=['<', '7.0']) + def test(self): + """Test that C++ supports char8_t correctly.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # FIXME: We should be able to test this with target variable, but the + # data formatter output is broken. + lldbutil.run_break_set_by_symbol(self, 'main') + self.runCmd("run", RUN_SUCCEEDED) + + self.expect( + "frame variable a", substrs=["(char8_t)", "0x61 u8'a'"]) + + self.expect( + "frame variable ab", substrs=['(const char8_t *)' , 'u8"你好"']) + + self.expect( + "frame variable abc", substrs=['(char8_t [9])', 'u8"你好"']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char8_t/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char8_t/main.cpp new file mode 100644 index 00000000000..b73ba0c4e61 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/char8_t/main.cpp @@ -0,0 +1,5 @@ +char8_t a = u8'a'; +const char8_t* ab = u8"你好"; +char8_t abc[9] = u8"你好"; + +int main (int argc, char const *argv[]) { return 0; } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class-template-parameter-pack/TestClassTemplateParameterPack.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class-template-parameter-pack/TestClassTemplateParameterPack.py new file mode 100644 index 00000000000..7e67f73b709 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class-template-parameter-pack/TestClassTemplateParameterPack.py @@ -0,0 +1,7 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.expectedFailureAll( + compiler="gcc")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class-template-parameter-pack/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class-template-parameter-pack/main.cpp new file mode 100644 index 00000000000..9278d01f8c5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class-template-parameter-pack/main.cpp @@ -0,0 +1,64 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +template <class T, int... Args> struct C { + T member; + bool isSixteenThirtyTwo() { return false; } +}; + +template <> struct C<int, 16> { + int member; + bool isSixteenThirtyTwo() { return false; } +}; + +template <> struct C<int, 16, 32> : C<int, 16> { + bool isSixteenThirtyTwo() { return true; } +}; + +template <class T, typename... Args> struct D { + T member; + bool isIntBool() { return false; } +}; + +template <> struct D<int, int> { + int member; + bool isIntBool() { return false; } +}; + +template <> struct D<int, int, bool> : D<int, int> { + bool isIntBool() { return true; } +}; + +int main (int argc, char const *argv[]) +{ + C<int,16,32> myC; + C<int,16> myLesserC; + myC.member = 64; + (void)C<int,16,32>().isSixteenThirtyTwo(); + (void)C<int,16>().isSixteenThirtyTwo(); + (void)(myC.member != 64); //% self.expect("expression -- myC", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["64"]) + //% self.expect("expression -- myLesserC.isSixteenThirtyTwo()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["false"]) + //% self.expect("expression -- myC.isSixteenThirtyTwo()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["true"]) + + // Disabling until we do template lookup correctly: http://lists.llvm.org/pipermail/lldb-commits/Week-of-Mon-20180507/040689.html + //#% self.expect("expression -- C<int, 16>().isSixteenThirtyTwo()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["false"]) + //#% self.expect("expression -- C<int, 16, 32>().isSixteenThirtyTwo()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["true"]) + + D<int,int,bool> myD; + D<int,int> myLesserD; + myD.member = 64; + (void)D<int,int,bool>().isIntBool(); + (void)D<int,int>().isIntBool(); + return myD.member != 64; //% self.expect("expression -- myD", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["64"]) + //% self.expect("expression -- myLesserD.isIntBool()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["false"]) + //% self.expect("expression -- myD.isIntBool()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["true"]) + + // See comment above. + //#% self.expect("expression -- D<int, int>().isIntBool()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["false"]) + //#% self.expect("expression -- D<int, int, bool>().isIntBool()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["true"]) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py new file mode 100644 index 00000000000..7c019e0e7cf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py @@ -0,0 +1,173 @@ +""" +Test display and Python APIs on file and class static variables. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class StaticVariableTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test_with_run_command(self): + """Test that file and class static variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Global variables are no longer displayed with the "frame variable" + # command. + self.expect( + 'target variable A::g_points', + VARIABLES_DISPLAYED_CORRECTLY, + patterns=['\(PointType \[[1-9]*\]\) A::g_points = {']) + self.expect('target variable g_points', VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(PointType [2]) g_points']) + + # On Mac OS X, gcc 4.2 emits the wrong debug info for A::g_points. + # A::g_points is an array of two elements. + if self.platformIsDarwin() or self.getPlatform() == "linux": + self.expect( + "target variable A::g_points[1].x", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(int) A::g_points[1].x = 11") + + @expectedFailureAll( + compiler=["gcc"], + bugnumber="Compiler emits incomplete debug info") + @expectedFailureAll( + compiler=["clang"], + compiler_version=["<", "3.9"], + bugnumber='llvm.org/pr20550') + def test_with_run_command_complete(self): + """ + Test that file and class static variables display correctly with + complete debug information. + """ + self.build() + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Global variables are no longer displayed with the "frame variable" + # command. + self.expect( + 'target variable A::g_points', + VARIABLES_DISPLAYED_CORRECTLY, + patterns=[ + '\(PointType \[[1-9]*\]\) A::g_points = {', '(x = 1, y = 2)', + '(x = 11, y = 22)' + ]) + + # Ensure that we take the context into account and only print + # A::g_points. + self.expect( + 'target variable A::g_points', + VARIABLES_DISPLAYED_CORRECTLY, + matching=False, + patterns=['(x = 3, y = 4)', '(x = 33, y = 44)']) + + # Finally, ensure that we print both points when not specifying a + # context. + self.expect( + 'target variable g_points', + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + '(PointType [2]) g_points', '(x = 1, y = 2)', + '(x = 11, y = 22)', '(x = 3, y = 4)', '(x = 33, y = 44)' + ]) + + @expectedFailureAll( + compiler=["gcc"], + bugnumber="Compiler emits incomplete debug info") + @expectedFailureAll( + compiler=["clang"], + compiler_version=["<", "3.9"], + bugnumber='llvm.org/pr20550') + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test Python APIs on file and class static variables.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # Get the SBValue of 'A::g_points' and 'g_points'. + frame = thread.GetFrameAtIndex(0) + + # arguments => False + # locals => False + # statics => True + # in_scope_only => False + valList = frame.GetVariables(False, False, True, False) + + for val in valList: + self.DebugSBValue(val) + name = val.GetName() + self.assertTrue(name in ['g_points', 'A::g_points']) + if name == 'g_points': + self.assertTrue( + val.GetValueType() == lldb.eValueTypeVariableStatic) + self.assertEqual(val.GetNumChildren(), 2) + elif name == 'A::g_points': + self.assertTrue( + val.GetValueType() == lldb.eValueTypeVariableGlobal) + self.assertEqual(val.GetNumChildren(), 2) + child1 = val.GetChildAtIndex(1) + self.DebugSBValue(child1) + child1_x = child1.GetChildAtIndex(0) + self.DebugSBValue(child1_x) + self.assertTrue(child1_x.GetTypeName() == 'int' and + child1_x.GetValue() == '11') + + # SBFrame.FindValue() should also work. + val = frame.FindValue("A::g_points", lldb.eValueTypeVariableGlobal) + self.DebugSBValue(val) + self.assertTrue(val.GetName() == 'A::g_points') + + # Also exercise the "parameter" and "local" scopes while we are at it. + val = frame.FindValue("argc", lldb.eValueTypeVariableArgument) + self.DebugSBValue(val) + self.assertTrue(val.GetName() == 'argc') + + val = frame.FindValue("argv", lldb.eValueTypeVariableArgument) + self.DebugSBValue(val) + self.assertTrue(val.GetName() == 'argv') + + val = frame.FindValue("hello_world", lldb.eValueTypeVariableLocal) + self.DebugSBValue(val) + self.assertTrue(val.GetName() == 'hello_world') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/main.cpp new file mode 100644 index 00000000000..319a05a7bee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_static/main.cpp @@ -0,0 +1,52 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// I made this example after noting that I was unable to display an unsized +// static class array. It turns out that gcc 4.2 will emit DWARF that correctly +// describes the PointType, but it will incorrectly emit debug info for the +// "g_points" array where the following things are wrong: +// - the DW_TAG_array_type won't have a subrange info +// - the DW_TAG_variable for "g_points" won't have a valid byte size, so even +// though we know the size of PointType, we can't infer the actual size +// of the array by dividing the size of the variable by the number of +// elements. + +#include <stdio.h> + +typedef struct PointType +{ + int x, y; +} PointType; + +class A +{ +public: + static PointType g_points[]; +}; + +PointType A::g_points[] = +{ + { 1, 2 }, + { 11, 22 } +}; + +static PointType g_points[] = +{ + { 3, 4 }, + { 33, 44 } +}; + +int +main (int argc, char const *argv[]) +{ + const char *hello_world = "Hello, world!"; + printf ("A::g_points[1].x = %i\n", A::g_points[1].x); // Set break point at this line. + printf ("::g_points[1].x = %i\n", g_points[1].x); + printf ("%s\n", hello_world); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py new file mode 100644 index 00000000000..45d64431ab3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py @@ -0,0 +1,224 @@ +"""Test breakpoint on a class constructor; and variable list the this object.""" + + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ClassTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # 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.') + + def test_with_run_command(self): + """Test 'frame variable this' when stopped on a class constructor.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break on the ctor function of class C. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1) + + self.runCmd("run", RUN_SUCCEEDED) + + # The test suite sometimes shows that the process has exited without stopping. + # + # CC=clang ./dotest.py -v -t class_types + # ... + # Process 76604 exited with status = 0 (0x00000000) + self.runCmd("process status") + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # We should be stopped on the ctor function of class C. + self.expect( + "frame variable --show-types this", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + 'C *', + ' this = ']) + + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Use Python APIs to create a breakpoint by (filespec, line).""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + filespec = target.GetExecutable() + self.assertTrue(filespec, VALID_FILESPEC) + + fsDir = os.path.normpath(filespec.GetDirectory()) + fsFile = filespec.GetFilename() + + self.assertTrue(fsDir == os.path.dirname(self.getBuildArtifact()) + and fsFile == "a.out", + "FileSpec matches the executable") + + bpfilespec = lldb.SBFileSpec("main.cpp", False) + + breakpoint = target.BreakpointCreateByLocation(bpfilespec, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Verify the breakpoint just created. + self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False, + substrs=['main.cpp', + str(self.line)]) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.Launch() failed") + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + # The stop reason of the thread should be breakpoint. + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # The filename of frame #0 should be 'main.cpp' and the line number + # should be 93. + self.expect("%s:%d" % (lldbutil.get_filenames(thread)[0], + lldbutil.get_line_numbers(thread)[0]), + "Break correctly at main.cpp:%d" % self.line, exe=False, + startstr="main.cpp:") + # clang compiled code reported main.cpp:94? + # startstr = "main.cpp:93") + + # We should be stopped on the breakpoint with a hit count of 1. + self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE) + + process.Continue() + + def test_with_expr_parser(self): + """Test 'frame variable this' and 'expr this' when stopped inside a constructor.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # rdar://problem/8516141 + # Is this a case of clang (116.1) generating bad debug info? + # + # Break on the ctor function of class C. + # self.expect("breakpoint set -M C", BREAKPOINT_CREATED, + # startstr = "Breakpoint created: 1: name = 'C'") + + # Make the test case more robust by using line number to break, + # instead. + lldbutil.run_break_set_by_file_and_line( + self, None, self.line, num_expected_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=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Continue on inside the ctor() body... + self.runCmd("register read pc") + self.runCmd("thread step-over") + + # Verify that 'frame variable this' gets the data type correct. + self.expect("frame variable this", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['C *']) + + # Verify that frame variable --show-types this->m_c_int behaves + # correctly. + self.runCmd("register read pc") + self.runCmd("expr m_c_int") + self.expect( + "frame variable --show-types this->m_c_int", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) this->m_c_int = 66') + + # Verify that 'expression this' gets the data type correct. + self.expect("expression this", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['C *']) + + # rdar://problem/8430916 + # expr this->m_c_int returns an incorrect value + # + # Verify that expr this->m_c_int behaves correctly. + self.expect("expression this->m_c_int", VARIABLES_DISPLAYED_CORRECTLY, + patterns=['\(int\) \$[0-9]+ = 66']) + + def test_with_constructor_name(self): + """Test 'frame variable this' and 'expr this' when stopped inside a constructor.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + filespec = target.GetExecutable() + self.assertTrue(filespec, VALID_FILESPEC) + + fsDir = os.path.normpath(filespec.GetDirectory()) + fsFile = filespec.GetFilename() + + self.assertTrue(fsDir == os.path.dirname(self.getBuildArtifact()) + and fsFile == "a.out", + "FileSpec matches the executable") + + bpfilespec = lldb.SBFileSpec("main.cpp", False) + + breakpoint = target.BreakpointCreateByLocation(bpfilespec, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Verify the breakpoint just created. + self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False, + substrs=['main.cpp', + str(self.line)]) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.Launch() failed") + + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + # The stop reason of the thread should be breakpoint. + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + frame = thread.frames[0] + self.assertTrue(frame.IsValid(), "Got a valid frame.") + + self.assertTrue("C::C" in frame.name, + "Constructor name includes class name.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py new file mode 100644 index 00000000000..ad187d0394b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py @@ -0,0 +1,99 @@ +""" +Test the lldb disassemble command on each call frame when stopped on C's ctor. +""" + +from __future__ import print_function + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class IterateFrameAndDisassembleTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_and_run_command(self): + """Disassemble each call frame when stopped on C's constructor.""" + self.build() + self.breakOnCtor() + + raw_output = self.res.GetOutput() + frameRE = re.compile(r""" + ^\s\sframe # heading for the frame info, + .* # wildcard, and + 0x[0-9a-f]{16} # the frame pc, and + \sa.out`(.+) # module`function, and + \s\+\s # the rest ' + ....' + """, re.VERBOSE) + for line in raw_output.split(os.linesep): + match = frameRE.search(line) + if match: + function = match.group(1) + #print("line:", line) + #print("function:", function) + self.runCmd("disassemble -n '%s'" % function) + + @add_test_categories(['pyapi']) + def test_and_python_api(self): + """Disassemble each call frame when stopped on C's constructor.""" + self.build() + self.breakOnCtor() + + # Now use the Python API to get at each function on the call stack and + # disassemble it. + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + depth = thread.GetNumFrames() + for i in range(depth - 1): + frame = thread.GetFrameAtIndex(i) + function = frame.GetFunction() + # Print the function header. + if self.TraceOn(): + print() + print(function) + if function: + # Get all instructions for this function and print them out. + insts = function.GetInstructions(target) + for inst in insts: + # We could simply do 'print inst' to print out the disassembly. + # But we want to print to stdout only if self.TraceOn() is + # True. + disasm = str(inst) + if self.TraceOn(): + print(disasm) + + def setUp(self): + # 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.') + + def breakOnCtor(self): + """Setup/run the program so it stops on C's constructor.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break on the ctor function of class C. + bpno = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_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=['stopped', + 'stop reason = breakpoint %d.' % (bpno)]) + + # This test was failing because we fail to put the C:: in front of constructore. + # We should maybe make another testcase to cover that specifically, but we shouldn't + # fail this whole testcase for an inessential issue. + # We should be stopped on the ctor function of class C. + # self.expect("thread backtrace", BACKTRACE_DISPLAYED_CORRECTLY, + # substrs = ['C::C']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/cmds.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/cmds.txt new file mode 100644 index 00000000000..1c7ef9f1c8a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/cmds.txt @@ -0,0 +1,3 @@ +b main.cpp:97 +c +var diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/main.cpp new file mode 100644 index 00000000000..179f2177793 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/class_types/main.cpp @@ -0,0 +1,125 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +class Conversion +{ +public: + Conversion (int i) : + m_i (i) + {} + + operator bool() + { + return m_i != 0; + } + +private: + int m_i; +}; + +class A +{ +public: + A(int i=0): + m_a_int(i), + m_aa_int(i+1) + { + } + + //virtual + ~A() + { + } + + int + GetInteger() const + { + return m_a_int; + } + void + SetInteger(int i) + { + m_a_int = i; + } + +protected: + int m_a_int; + int m_aa_int; +}; + +class B : public A +{ +public: + B(int ai, int bi) : + A(ai), + m_b_int(bi) + { + } + + //virtual + ~B() + { + } + + int + GetIntegerB() const + { + return m_b_int; + } + void + SetIntegerB(int i) + { + m_b_int = i; + } + +protected: + int m_b_int; +}; + +#include <cstdio> +class C : public B +{ +public: + C(int ai, int bi, int ci) : + B(ai, bi), + m_c_int(ci) + { + std::printf("Within C::ctor() m_c_int=%d\n", m_c_int); // Set break point at this line. + } + + //virtual + ~C() + { + } + + int + GetIntegerC() const + { + return m_c_int; + } + void + SetIntegerC(int i) + { + m_c_int = i; + } + +protected: + int m_c_int; +}; + +int +main (int argc, char const *argv[]) +{ + A a(12); + B b(22,33); + C c(44,55,66); + Conversion conv(1); + if (conv) + return b.GetIntegerB() - a.GetInteger() + c.GetInteger(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/TestConstThis.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/TestConstThis.py new file mode 100644 index 00000000000..f08c0dcbda9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/TestConstThis.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), []) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/main.cpp new file mode 100644 index 00000000000..c244e1bf44e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/const_this/main.cpp @@ -0,0 +1,22 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +class foo { +public: + template <class T> T func(T x) const { + return x+2; //% self.expect("expr 2+3", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["5"]) + } +}; + +int i; + +int main() { + return foo().func(i); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py new file mode 100644 index 00000000000..c1d0d236268 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py @@ -0,0 +1,51 @@ +""" +Tests that bool types work +""" +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class CPPTestDiamondInheritance(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """Test that virtual base classes work in when SBValue objects are used to explore the variable value""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + self.set_breakpoint(line_number('main.cpp', '// breakpoint 1')) + self.set_breakpoint(line_number('main.cpp', '// breakpoint 2')) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + frame = thread.GetFrameAtIndex(0) + j1 = frame.FindVariable("j1") + j1_Derived1 = j1.GetChildAtIndex(0) + j1_Derived2 = j1.GetChildAtIndex(1) + j1_Derived1_VBase = j1_Derived1.GetChildAtIndex(0) + j1_Derived2_VBase = j1_Derived2.GetChildAtIndex(0) + j1_Derived1_VBase_m_value = j1_Derived1_VBase.GetChildAtIndex(0) + j1_Derived2_VBase_m_value = j1_Derived2_VBase.GetChildAtIndex(0) + self.assertTrue( + j1_Derived1_VBase.GetLoadAddress() == j1_Derived2_VBase.GetLoadAddress(), + "ensure virtual base class is the same between Derived1 and Derived2") + self.assertTrue(j1_Derived1_VBase_m_value.GetValueAsUnsigned( + 1) == j1_Derived2_VBase_m_value.GetValueAsUnsigned(2), "ensure m_value in VBase is the same") + self.assertTrue(frame.FindVariable("d").GetChildAtIndex(0).GetChildAtIndex( + 0).GetValueAsUnsigned(0) == 12345, "ensure Derived2 from j1 is correct") + thread.StepOver() + self.assertTrue(frame.FindVariable("d").GetChildAtIndex(0).GetChildAtIndex( + 0).GetValueAsUnsigned(0) == 12346, "ensure Derived2 from j2 is correct") + + def set_breakpoint(self, line): + # Some compilers (for example GCC 4.4.7 and 4.6.1) emit multiple locations for the statement with the ternary + # operator in the test program, while others emit only 1. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/main.cpp new file mode 100644 index 00000000000..31329b271e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/diamond/main.cpp @@ -0,0 +1,84 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +static int g_next_value = 12345; + +class VBase +{ +public: + VBase() : m_value(g_next_value++) {} + virtual ~VBase() {} + void Print() + { + printf("%p: %s\n%p: m_value = 0x%8.8x\n", this, __PRETTY_FUNCTION__, &m_value, m_value); + } + int m_value; +}; + +class Derived1 : public virtual VBase +{ +public: + Derived1() {}; + void Print () + { + printf("%p: %s\n", this, __PRETTY_FUNCTION__); + VBase::Print(); + } + +}; + +class Derived2 : public virtual VBase +{ +public: + Derived2() {}; + + void Print () + { + printf("%p: %s\n", this, __PRETTY_FUNCTION__); + VBase::Print(); + } +}; + +class Joiner1 : public Derived1, public Derived2 +{ +public: + Joiner1() : + m_joiner1(3456), + m_joiner2(6789) {} + void Print () + { + printf("%p: %s \n%p: m_joiner1 = 0x%8.8x\n%p: m_joiner2 = 0x%8.8x\n", + this, + __PRETTY_FUNCTION__, + &m_joiner1, + m_joiner1, + &m_joiner2, + m_joiner2); + Derived1::Print(); + Derived2::Print(); + } + int m_joiner1; + int m_joiner2; +}; + +class Joiner2 : public Derived2 +{ + int m_stuff[32]; +}; + +int main(int argc, const char * argv[]) +{ + Joiner1 j1; + Joiner2 j2; + j1.Print(); + j2.Print(); + Derived2 *d = &j1; + d = &j2; // breakpoint 1 + return 0; // breakpoint 2 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value-same-basename/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value-same-basename/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value-same-basename/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value-same-basename/TestDynamicValueSameBase.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value-same-basename/TestDynamicValueSameBase.py new file mode 100644 index 00000000000..546fd11a1b4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value-same-basename/TestDynamicValueSameBase.py @@ -0,0 +1,58 @@ +""" +Make sure if we have two classes with the same base name the +dynamic value calculator doesn't confuse them +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class DynamicValueSameBaseTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def test_same_basename_this(self): + """Test that the we use the full name to resolve dynamic types.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.cpp") + self.sample_test() + + def sample_test(self): + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Break here to get started", self.main_source_file) + + # Set breakpoints in the two class methods and run to them: + namesp_bkpt = target.BreakpointCreateBySourceRegex("namesp function did something.", self.main_source_file) + self.assertEqual(namesp_bkpt.GetNumLocations(), 1, "Namespace breakpoint invalid") + + virtual_bkpt = target.BreakpointCreateBySourceRegex("Virtual function did something.", self.main_source_file) + self.assertEqual(virtual_bkpt.GetNumLocations(), 1, "Virtual breakpoint invalid") + + threads = lldbutil.continue_to_breakpoint(process, namesp_bkpt) + self.assertEqual(len(threads), 1, "Didn't stop at namespace breakpoint") + + frame = threads[0].frame[0] + namesp_this = frame.FindVariable("this", lldb.eDynamicCanRunTarget) + # Clang specifies the type of this as "T *", gcc as "T * const". This + # erases the difference. + namesp_type = namesp_this.GetType().GetUnqualifiedType() + self.assertEqual(namesp_type.GetName(), "namesp::Virtual *", "Didn't get the right dynamic type") + + threads = lldbutil.continue_to_breakpoint(process, virtual_bkpt) + self.assertEqual(len(threads), 1, "Didn't stop at virtual breakpoint") + + frame = threads[0].frame[0] + virtual_this = frame.FindVariable("this", lldb.eDynamicCanRunTarget) + virtual_type = virtual_this.GetType().GetUnqualifiedType() + self.assertEqual(virtual_type.GetName(), "Virtual *", "Didn't get the right dynamic type") + + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value-same-basename/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value-same-basename/main.cpp new file mode 100644 index 00000000000..38e46c03f41 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value-same-basename/main.cpp @@ -0,0 +1,32 @@ +#include <stdio.h> + +namespace namesp +{ + class Virtual { + public: + virtual void doSomething() { + printf ("namesp function did something.\n"); + } + }; +} + +class Virtual { + public: + virtual void doSomething() { + printf("Virtual function did something.\n"); + } +}; + +int +main() +{ + namesp::Virtual my_outer; + Virtual my_virtual; + + // Break here to get started + my_outer.doSomething(); + my_virtual.doSomething(); + + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/Makefile new file mode 100644 index 00000000000..2bba8e757f7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := pass-to-base.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py new file mode 100644 index 00000000000..609dd608aa4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py @@ -0,0 +1,135 @@ +""" +Test lldb Python API SBValue::Cast(SBType) for C++ types. +""" + +from __future__ import print_function + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CppValueCastTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(bugnumber="llvm.org/PR36714") + @add_test_categories(['pyapi']) + def test_value_cast_with_virtual_inheritance(self): + """Test SBValue::Cast(SBType) API for C++ types with virtual inheritance.""" + self.build(dictionary=self.d_virtual) + self.setTearDownCleanup(dictionary=self.d_virtual) + self.do_sbvalue_cast(self.exe_name) + + @add_test_categories(['pyapi']) + def test_value_cast_with_regular_inheritance(self): + """Test SBValue::Cast(SBType) API for C++ types with regular inheritance.""" + self.build(dictionary=self.d_regular) + self.setTearDownCleanup(dictionary=self.d_regular) + self.do_sbvalue_cast(self.exe_name) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # Find the line number to break for main.c. + self.source = 'sbvalue-cast.cpp' + self.line = line_number(self.source, '// Set breakpoint here.') + self.exe_name = self.testMethodName + self.d_virtual = { + 'CXX_SOURCES': self.source, + 'EXE': self.exe_name, + 'CFLAGS_EXTRAS': '-DDO_VIRTUAL_INHERITANCE'} + self.d_regular = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + + def do_sbvalue_cast(self, exe_name): + """Test SBValue::Cast(SBType) API for C++ types.""" + exe = self.getBuildArtifact(exe_name) + + # Create a target from the debugger. + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set up our breakpoints: + + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + # Find DerivedA and DerivedB types. + typeA = target.FindFirstType('DerivedA') + typeB = target.FindFirstType('DerivedB') + self.DebugSBType(typeA) + self.DebugSBType(typeB) + self.assertTrue(typeA) + self.assertTrue(typeB) + error = lldb.SBError() + + # First stop is for DerivedA instance. + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(threads) == 1) + thread = threads[0] + frame0 = thread.GetFrameAtIndex(0) + + tellerA = frame0.FindVariable('teller', lldb.eNoDynamicValues) + self.DebugSBValue(tellerA) + self.assertTrue(tellerA.GetChildMemberWithName( + 'm_base_val').GetValueAsUnsigned(error, 0) == 20) + + if self.TraceOn(): + for child in tellerA: + print("child name:", child.GetName()) + print(child) + + # Call SBValue.Cast() to obtain instanceA. + instanceA = tellerA.Cast(typeA.GetPointerType()) + self.DebugSBValue(instanceA) + + # Iterate through all the children and print their values. + if self.TraceOn(): + for child in instanceA: + print("child name:", child.GetName()) + print(child) + a_member_val = instanceA.GetChildMemberWithName('m_a_val') + self.DebugSBValue(a_member_val) + self.assertTrue(a_member_val.GetValueAsUnsigned(error, 0) == 10) + + # Second stop is for DerivedB instance. + threads = lldbutil.continue_to_breakpoint(process, breakpoint) + self.assertTrue(len(threads) == 1) + thread = threads[0] + frame0 = thread.GetFrameAtIndex(0) + + tellerB = frame0.FindVariable('teller', lldb.eNoDynamicValues) + self.DebugSBValue(tellerB) + self.assertTrue(tellerB.GetChildMemberWithName( + 'm_base_val').GetValueAsUnsigned(error, 0) == 12) + + if self.TraceOn(): + for child in tellerB: + print("child name:", child.GetName()) + print(child) + + # Call SBValue.Cast() to obtain instanceB. + instanceB = tellerB.Cast(typeB.GetPointerType()) + self.DebugSBValue(instanceB) + + # Iterate through all the children and print their values. + if self.TraceOn(): + for child in instanceB: + print("child name:", child.GetName()) + print(child) + b_member_val = instanceB.GetChildMemberWithName('m_b_val') + self.DebugSBValue(b_member_val) + self.assertTrue(b_member_val.GetValueAsUnsigned(error, 0) == 36) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py new file mode 100644 index 00000000000..c3d7dfb328f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py @@ -0,0 +1,249 @@ +""" +Use lldb Python API to test dynamic values in C++ +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DynamicValueTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # Find the line number to break for main.c. + + self.do_something_line = line_number( + 'pass-to-base.cpp', '// Break here in doSomething.') + self.main_first_call_line = line_number( + 'pass-to-base.cpp', + '// Break here and get real addresses of myB and otherB.') + self.main_second_call_line = line_number( + 'pass-to-base.cpp', '// Break here and get real address of reallyA.') + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24663") + def test_get_dynamic_vals(self): + """Test fetching C++ dynamic values from pointers & references.""" + self.build(dictionary=self.getBuildFlags()) + exe = self.getBuildArtifact("a.out") + + # Create a target from the debugger. + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set up our breakpoints: + + do_something_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.do_something_line) + self.assertTrue(do_something_bpt, + VALID_BREAKPOINT) + + first_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_first_call_line) + self.assertTrue(first_call_bpt, + VALID_BREAKPOINT) + + second_call_bpt = target.BreakpointCreateByLocation( + 'pass-to-base.cpp', self.main_second_call_line) + self.assertTrue(second_call_bpt, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, first_call_bpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + + frame = thread.GetFrameAtIndex(0) + + # Now find the dynamic addresses of myB and otherB so we can compare them + # with the dynamic values we get in doSomething: + + use_dynamic = lldb.eDynamicCanRunTarget + no_dynamic = lldb.eNoDynamicValues + + myB = frame.FindVariable('myB', no_dynamic) + self.assertTrue(myB) + myB_loc = int(myB.GetLocation(), 16) + + otherB = frame.FindVariable('otherB', no_dynamic) + self.assertTrue(otherB) + otherB_loc = int(otherB.GetLocation(), 16) + + # Okay now run to doSomething: + + threads = lldbutil.continue_to_breakpoint(process, do_something_bpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + + frame = thread.GetFrameAtIndex(0) + + # Get "this" using FindVariable: + + this_static = frame.FindVariable('this', no_dynamic) + this_dynamic = frame.FindVariable('this', use_dynamic) + self.examine_value_object_of_this_ptr( + this_static, this_dynamic, myB_loc) + + # Now make sure that the "GetDynamicValue" works: + # This doesn't work currently because we can't get dynamic values from + # ConstResult objects. + fetched_dynamic_value = this_static.GetDynamicValue(use_dynamic) + self.examine_value_object_of_this_ptr( + this_static, fetched_dynamic_value, myB_loc) + + # And conversely that the GetDynamicValue() interface also works: + fetched_static_value = this_dynamic.GetStaticValue() + self.examine_value_object_of_this_ptr( + fetched_static_value, this_dynamic, myB_loc) + + # Get "this" using FindValue, make sure that works too: + this_static = frame.FindValue( + 'this', lldb.eValueTypeVariableArgument, no_dynamic) + this_dynamic = frame.FindValue( + 'this', lldb.eValueTypeVariableArgument, use_dynamic) + self.examine_value_object_of_this_ptr( + this_static, this_dynamic, myB_loc) + + # Get "this" using the EvaluateExpression: + this_static = frame.EvaluateExpression('this', False) + this_dynamic = frame.EvaluateExpression('this', True) + self.examine_value_object_of_this_ptr( + this_static, this_dynamic, myB_loc) + + # The "frame var" code uses another path to get into children, so let's + # make sure that works as well: + + self.expect( + 'frame var -d run-target --ptr-depth=2 --show-types anotherA.m_client_A', + 'frame var finds its way into a child member', + patterns=['\(B \*\)']) + + # Now make sure we also get it right for a reference as well: + + anotherA_static = frame.FindVariable('anotherA', False) + self.assertTrue(anotherA_static) + anotherA_static_addr = int(anotherA_static.GetValue(), 16) + + anotherA_dynamic = frame.FindVariable('anotherA', True) + self.assertTrue(anotherA_dynamic) + anotherA_dynamic_addr = int(anotherA_dynamic.GetValue(), 16) + anotherA_dynamic_typename = anotherA_dynamic.GetTypeName() + self.assertTrue(anotherA_dynamic_typename.find('B') != -1) + + self.assertTrue(anotherA_dynamic_addr < anotherA_static_addr) + + anotherA_m_b_value_dynamic = anotherA_dynamic.GetChildMemberWithName( + 'm_b_value', True) + self.assertTrue(anotherA_m_b_value_dynamic) + anotherA_m_b_val = int(anotherA_m_b_value_dynamic.GetValue(), 10) + self.assertTrue(anotherA_m_b_val == 300) + + anotherA_m_b_value_static = anotherA_static.GetChildMemberWithName( + 'm_b_value', True) + self.assertFalse(anotherA_m_b_value_static) + + # Okay, now continue again, and when we hit the second breakpoint in + # main + + threads = lldbutil.continue_to_breakpoint(process, second_call_bpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + + frame = thread.GetFrameAtIndex(0) + reallyA_value = frame.FindVariable('reallyA', False) + self.assertTrue(reallyA_value) + reallyA_loc = int(reallyA_value.GetLocation(), 16) + + # Finally continue to doSomething again, and make sure we get the right value for anotherA, + # which this time around is just an "A". + + threads = lldbutil.continue_to_breakpoint(process, do_something_bpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + + frame = thread.GetFrameAtIndex(0) + anotherA_value = frame.FindVariable('anotherA', True) + self.assertTrue(anotherA_value) + anotherA_loc = int(anotherA_value.GetValue(), 16) + self.assertTrue(anotherA_loc == reallyA_loc) + self.assertTrue(anotherA_value.GetTypeName().find('B') == -1) + + def examine_value_object_of_this_ptr( + self, this_static, this_dynamic, dynamic_location): + # Get "this" as its static value + self.assertTrue(this_static) + this_static_loc = int(this_static.GetValue(), 16) + + # Get "this" as its dynamic value + + self.assertTrue(this_dynamic) + this_dynamic_typename = this_dynamic.GetTypeName() + self.assertTrue(this_dynamic_typename.find('B') != -1) + this_dynamic_loc = int(this_dynamic.GetValue(), 16) + + # Make sure we got the right address for "this" + + self.assertTrue(this_dynamic_loc == dynamic_location) + + # And that the static address is greater than the dynamic one + + self.assertTrue(this_static_loc > this_dynamic_loc) + + # Now read m_b_value which is only in the dynamic value: + + use_dynamic = lldb.eDynamicCanRunTarget + no_dynamic = lldb.eNoDynamicValues + + this_dynamic_m_b_value = this_dynamic.GetChildMemberWithName( + 'm_b_value', use_dynamic) + self.assertTrue(this_dynamic_m_b_value) + + m_b_value = int(this_dynamic_m_b_value.GetValue(), 0) + self.assertTrue(m_b_value == 10) + + # Make sure it is not in the static version + + this_static_m_b_value = this_static.GetChildMemberWithName( + 'm_b_value', no_dynamic) + self.assertFalse(this_static_m_b_value) + + # Okay, now let's make sure that we can get the dynamic type of a child + # element: + + contained_auto_ptr = this_dynamic.GetChildMemberWithName( + 'm_client_A', use_dynamic) + self.assertTrue(contained_auto_ptr) + contained_b = contained_auto_ptr.GetChildMemberWithName( + '_M_ptr', use_dynamic) + if not contained_b: + contained_b = contained_auto_ptr.GetChildMemberWithName( + '__ptr_', use_dynamic) + self.assertTrue(contained_b) + + contained_b_static = contained_auto_ptr.GetChildMemberWithName( + '_M_ptr', no_dynamic) + if not contained_b_static: + contained_b_static = contained_auto_ptr.GetChildMemberWithName( + '__ptr_', no_dynamic) + self.assertTrue(contained_b_static) + + contained_b_addr = int(contained_b.GetValue(), 16) + contained_b_static_addr = int(contained_b_static.GetValue(), 16) + + self.assertTrue(contained_b_addr < contained_b_static_addr) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/pass-to-base.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/pass-to-base.cpp new file mode 100644 index 00000000000..2bccf330382 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/pass-to-base.cpp @@ -0,0 +1,69 @@ +#include <stdio.h> +#include <memory> + +class Extra +{ +public: + Extra (int in_one, int in_two) : m_extra_one(in_one), m_extra_two(in_two) {} + +private: + int m_extra_one; + int m_extra_two; +}; + +class A +{ +public: + A(int value) : m_a_value (value) {} + A(int value, A* client_A) : m_a_value (value), m_client_A (client_A) {} + + virtual ~A() {} + + virtual void + doSomething (A &anotherA) + { + printf ("In A %p doing something with %d.\n", this, m_a_value); + int tmp_value = anotherA.Value(); + printf ("Also have another A at %p: %d.\n", &anotherA, tmp_value); // Break here in doSomething. + } + + int + Value() + { + return m_a_value; + } + +private: + int m_a_value; + std::auto_ptr<A> m_client_A; +}; + +class B : public Extra, public virtual A +{ +public: + B (int b_value, int a_value) : Extra(b_value, a_value), A(a_value), m_b_value(b_value) {} + B (int b_value, int a_value, A *client_A) : Extra(b_value, a_value), A(a_value, client_A), m_b_value(b_value) {} + + virtual ~B () {} + +private: + int m_b_value; +}; + +static A* my_global_A_ptr; + +int +main (int argc, char **argv) +{ + my_global_A_ptr = new B (100, 200); + B myB (10, 20, my_global_A_ptr); + B *second_fake_A_ptr = new B (150, 250); + B otherB (300, 400, second_fake_A_ptr); + + myB.doSomething(otherB); // Break here and get real addresses of myB and otherB. + + A reallyA (500); + myB.doSomething (reallyA); // Break here and get real address of reallyA. + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/sbvalue-cast.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/sbvalue-cast.cpp new file mode 100644 index 00000000000..9e03594a734 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/sbvalue-cast.cpp @@ -0,0 +1,79 @@ +//===-- sbvalue-cast.cpp ----------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifdef DO_VIRTUAL_INHERITANCE +#define VIRTUAL virtual +#else +#define VIRTUAL +#endif + +#include <stdio.h> + +class Base +{ +public: + Base(int val) : m_base_val (val) {} + virtual ~Base() {} + + virtual void + forcast(int input) { + int future_val = m_base_val + input * 1; + printf("Forcasting %d\n", future_val); + } + +protected: + int m_base_val; +}; + +class DerivedA : public VIRTUAL Base +{ +public: + DerivedA(int val) : Base(val*2), m_a_val(val) { + printf("DerivedA::ctor()->\n"); + printf("m_base_val=%d\n", m_base_val); + printf("m_a_val=%d\n", m_a_val); + } + virtual ~DerivedA() {} + +private: + int m_a_val; +}; + +class DerivedB : public VIRTUAL Base +{ +public: + DerivedB(int val) : Base(val), m_b_val(val*3) { + printf("DerivedB::ctor()->\n"); + printf("m_base_val=%d\n", m_base_val); + printf("m_b_val=%d\n", m_b_val); + } + virtual ~DerivedB() {} + + virtual void + forcast(int input) { + int future_val = m_b_val + input * 2; + printf("Forcasting %d\n", future_val); + } + +private: + int m_b_val; +}; + +int +main(int argc, char **argv) +{ + DerivedA* dA = new DerivedA(10); + DerivedB* dB = new DerivedB(12); + Base *array[2] = {dA, dB}; + Base *teller = NULL; + for (int i = 0; i < 2; ++i) { + teller = array[i]; + teller->forcast(i); // Set breakpoint here. + } + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/Makefile new file mode 100644 index 00000000000..a02c72adc20 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/Makefile @@ -0,0 +1,9 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -std=c++11 + +clean: OBJECTS+=$(wildcard main.d.*) + + + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py new file mode 100644 index 00000000000..c58f700039e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py @@ -0,0 +1,156 @@ +"""Look up enum type information and check for correct display.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class CPP11EnumTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr36527') + @skipIf(dwarf_version=['<', '4']) + def test_int8_t(self): + """Test C++11 enumeration class types as int8_t types.""" + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DSIGNED_ENUM_CLASS_TYPE=int8_t"'}) + self.image_lookup_for_enum_type(True) + + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr36527') + @skipIf(dwarf_version=['<', '4']) + def test_int16_t(self): + """Test C++11 enumeration class types as int16_t types.""" + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DSIGNED_ENUM_CLASS_TYPE=int16_t"'}) + self.image_lookup_for_enum_type(True) + + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr36527') + @skipIf(dwarf_version=['<', '4']) + def test_int32_t(self): + """Test C++11 enumeration class types as int32_t types.""" + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DSIGNED_ENUM_CLASS_TYPE=int32_t"'}) + self.image_lookup_for_enum_type(True) + + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr36527') + @skipIf(dwarf_version=['<', '4']) + def test_int64_t(self): + """Test C++11 enumeration class types as int64_t types.""" + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DSIGNED_ENUM_CLASS_TYPE=int64_t"'}) + self.image_lookup_for_enum_type(True) + + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr36527') + @skipIf(dwarf_version=['<', '4']) + def test_uint8_t(self): + """Test C++11 enumeration class types as uint8_t types.""" + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DUNSIGNED_ENUM_CLASS_TYPE=uint8_t"'}) + self.image_lookup_for_enum_type(False) + + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr36527') + @skipIf(dwarf_version=['<', '4']) + def test_uint16_t(self): + """Test C++11 enumeration class types as uint16_t types.""" + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DUNSIGNED_ENUM_CLASS_TYPE=uint16_t"'}) + self.image_lookup_for_enum_type(False) + + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr36527') + @skipIf(dwarf_version=['<', '4']) + def test_uint32_t(self): + """Test C++11 enumeration class types as uint32_t types.""" + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DUNSIGNED_ENUM_CLASS_TYPE=uint32_t"'}) + self.image_lookup_for_enum_type(False) + + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr36527') + @skipIf(dwarf_version=['<', '4']) + def test_uint64_t(self): + """Test C++11 enumeration class types as uint64_t types.""" + self.build( + dictionary={ + 'CFLAGS_EXTRAS': '"-DUNSIGNED_ENUM_CLASS_TYPE=uint64_t"'}) + self.image_lookup_for_enum_type(False) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + + def image_lookup_for_enum_type(self, is_signed): + """Test C++11 enumeration class types.""" + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the main. + bkpt_id = lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Look up information about the 'DayType' enum type. + # Check for correct display. + self.expect("image lookup -t DayType", DATA_TYPES_DISPLAYED_CORRECTLY, + patterns=['enum( struct| class) DayType {'], + substrs=['Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday', + 'kNumDays', + '}']) + + if is_signed: + enum_values = ['-4', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday', + 'kNumDays', + '5'] + else: + enum_values = ['199', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday', + 'kNumDays', + '208'] + + bkpt = self.target().FindBreakpointByID(bkpt_id) + for enum_value in enum_values: + self.expect( + "frame variable day", + 'check for valid enumeration value', + substrs=[enum_value]) + lldbutil.continue_to_breakpoint(self.process(), bkpt) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/main.cpp new file mode 100644 index 00000000000..e00fc2df460 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/enum_types/main.cpp @@ -0,0 +1,48 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + + +int main (int argc, char const *argv[]) +{ +#ifdef SIGNED_ENUM_CLASS_TYPE + typedef SIGNED_ENUM_CLASS_TYPE enum_integer_t; + enum class DayType : enum_integer_t { + Monday = -3, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, + Sunday, + kNumDays + }; + enum_integer_t day_value; +#else + typedef UNSIGNED_ENUM_CLASS_TYPE enum_integer_t; + enum class DayType : enum_integer_t { + Monday = 200, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, + Sunday, + kNumDays + }; + enum_integer_t day_value; +#endif + + for (day_value = (enum_integer_t)DayType::Monday - 1; day_value <= (enum_integer_t)DayType::kNumDays + 1; ++day_value) + { + DayType day = (DayType)day_value; + printf("day as int is %i\n", (int)day); // Set break point at this line. + } + return 0; // Break here for char tests +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/Makefile new file mode 100644 index 00000000000..edb53da7b8e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := exceptions.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py new file mode 100644 index 00000000000..e888958987a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py @@ -0,0 +1,82 @@ +""" +Test lldb exception breakpoint command for CPP. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CPPBreakpointTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.source = 'exceptions.cpp' + self.catch_line = line_number( + self.source, '// This is the line you should stop at for catch') + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24538, clang-cl does not support throw or catch") + @expectedFailureNetBSD + def test(self): + """Test lldb exception breakpoint command for CPP.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target from the debugger. + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + exception_bkpt = target.BreakpointCreateForException( + lldb.eLanguageTypeC_plus_plus, True, True) + self.assertTrue(exception_bkpt, "Made an exception breakpoint") + + # Now run, and make sure we hit our breakpoint: + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, "Got a valid process") + + stopped_threads = [] + stopped_threads = lldbutil.get_threads_stopped_at_breakpoint( + process, exception_bkpt) + self.assertTrue( + len(stopped_threads) == 1, + "Stopped at our exception breakpoint.") + thread = stopped_threads[0] + # Make sure our throw function is still above us on the stack: + + frame_functions = lldbutil.get_function_names(thread) + self.assertTrue( + frame_functions.count("throws_exception_on_even(int)") == 1, + "Our throw function is still on the stack.") + + # Okay we hit our exception throw breakpoint, now make sure we get our catch breakpoint. + # One potential complication is that we might hit a couple of the exception breakpoints in getting out of the throw. + # so loop till we don't see the throws function on the stack. We should stop one more time for our exception breakpoint + # and that should be the catch... + + while frame_functions.count("throws_exception_on_even(int)") == 1: + stopped_threads = lldbutil.continue_to_breakpoint( + process, exception_bkpt) + self.assertTrue(len(stopped_threads) == 1) + + thread = stopped_threads[0] + frame_functions = lldbutil.get_function_names(thread) + + self.assertTrue( + frame_functions.count("throws_exception_on_even(int)") == 0, + "At catch our throw function is off the stack") + self.assertTrue( + frame_functions.count("intervening_function(int)") == 0, + "At catch our intervening function is off the stack") + self.assertTrue( + frame_functions.count("catches_exception(int)") == 1, + "At catch our catch function is on the stack") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/exceptions.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/exceptions.cpp new file mode 100644 index 00000000000..150d420b241 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/exceptions/exceptions.cpp @@ -0,0 +1,42 @@ +#include <exception> +#include <stdio.h> + +int throws_exception_on_even (int value); +int intervening_function (int value); +int catches_exception (int value); + +int +catches_exception (int value) +{ + try + { + return intervening_function(value); // This is the line you should stop at for catch + } + catch (int value) + { + return value; + } +} + +int +intervening_function (int value) +{ + return throws_exception_on_even (2 * value); +} + +int +throws_exception_on_even (int value) +{ + printf ("Mod two works: %d.\n", value%2); + if (value % 2 == 0) + throw 30; + else + return value; +} + +int +main () +{ + catches_exception (10); // Stop here + return 5; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/extern_c/TestExternCSymbols.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/extern_c/TestExternCSymbols.py new file mode 100644 index 00000000000..b1b7e1744f1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/extern_c/TestExternCSymbols.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), lldbinline.expectedFailureAll(oslist=["windows"])) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/extern_c/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/extern_c/main.cpp new file mode 100644 index 00000000000..47769014d49 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/extern_c/main.cpp @@ -0,0 +1,28 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> +#include <stdint.h> + +extern "C" +{ + int foo(); +}; + +int foo() +{ + puts("foo"); + return 2; +} + +int main (int argc, char const *argv[], char const *envp[]) +{ + foo(); + return 0; //% self.expect("expression -- foo()", substrs = ['2']) +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py new file mode 100644 index 00000000000..6352b68e7d7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py @@ -0,0 +1,35 @@ +""" +Tests that frame variable looks into anonymous unions +""" +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class FrameVariableAnonymousUnionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """Tests that frame variable looks into anonymous unions""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + line = line_number('main.cpp', '// break here') + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=-1, loc_exact=False) + + self.runCmd("process launch", RUN_SUCCEEDED) + + process = self.dbg.GetSelectedTarget().GetProcess() + + if process.GetByteOrder() == lldb.eByteOrderLittle: + self.expect('frame variable -f x i', substrs=['ffffff41']) + else: + self.expect('frame variable -f x i', substrs=['41ffff00']) + + self.expect('frame variable c', substrs=["'A"]) + + self.expect('frame variable x', matching=False, substrs=['3']) + self.expect('frame variable y', matching=False, substrs=["'B'"]) + self.expect('frame variable z', matching=False, substrs=['14']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/main.cpp new file mode 100644 index 00000000000..2489506b280 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/main.cpp @@ -0,0 +1,22 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main() { + union { + int i; + char c; + }; + struct { + int x; + char y; + short z; + } s{3,'B',14}; + i = 0xFFFFFF00; + c = 'A'; + return c; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function-template-parameter-pack/TestFunctionTemplateParameterPack.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function-template-parameter-pack/TestFunctionTemplateParameterPack.py new file mode 100644 index 00000000000..b90f74656cd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function-template-parameter-pack/TestFunctionTemplateParameterPack.py @@ -0,0 +1,12 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +# https://bugs.llvm.org/show_bug.cgi?id=35920 +# This test stresses expression evaluation support for template functions. +# Currently the support is rudimentary, and running this test causes assertion +# failures in clang. This test cannot be XFAIL'ed because the test harness +# treats assertion failures as unexpected events. For now, the test must be +# skipped. +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIf]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function-template-parameter-pack/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function-template-parameter-pack/main.cpp new file mode 100644 index 00000000000..eea2830aef8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function-template-parameter-pack/main.cpp @@ -0,0 +1,23 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +template <class T> int staticSizeof() { + return sizeof(T); +} + +template <class T1, class T2, class... Ts> int staticSizeof() { + return staticSizeof<T2, Ts...>() + sizeof(T1); +} + +int main (int argc, char const *argv[]) +{ + int sz = staticSizeof<long, int, char>(); + return staticSizeof<long, int, char>() != sz; //% self.expect("expression -- sz == staticSizeof<long, int, char>()", "staticSizeof<long, int, char> worked", substrs = ["true"]) + //% self.expect("expression -- sz == staticSizeof<long, int>() + sizeof(char)", "staticSizeof<long, int> worked", substrs = ["true"]) + //% self.expect("expression -- sz == staticSizeof<long>() + sizeof(int) + sizeof(char)", "staticSizeof<long> worked", substrs = ["true"]) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function_refs/TestFunctionRefs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function_refs/TestFunctionRefs.py new file mode 100644 index 00000000000..293e9139637 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function_refs/TestFunctionRefs.py @@ -0,0 +1,5 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + lldbinline.expectedFailureAll(oslist=["windows"])) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function_refs/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function_refs/main.cpp new file mode 100644 index 00000000000..a57b0867fb8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/function_refs/main.cpp @@ -0,0 +1,32 @@ +// This is plagiarized from lit/SymbolFile/NativePDB/function-types-builtin.cpp. +void nullary() {} + +template<typename Arg> +void unary(Arg) { } + +template<typename A1, typename A2> +void binary(A1, A2) { } + +int varargs(int, int, ...) { return 0; } + +auto &ref = unary<bool>; +auto &ref2 = unary<volatile int*>; +auto &ref3 = varargs; +auto binp = &binary<int*, const int*>; +auto &binr = binary<int*, const int*>; +auto null = &nullary; +int main(int argc, char **argv) { +//% self.expect("target var ref", substrs=["(void (&)(bool))", "ref = 0x", +//% "&::ref = <no summary available>"]) +//% self.expect("target var ref2", +//% substrs=["(void (&)(volatile int *))", "ref2 = 0x"]) +//% self.expect("target var ref3", +//% substrs=["(int (&)(int, int, ...))", "ref3 = 0x"]) +//% self.expect("target var binp", +//% substrs=["(void (*)(int *, const int *))", "binp = 0x"]) +//% self.expect("target var binr", +//% substrs=["(void (&)(int *, const int *))", "binr = 0x"]) +//% self.expect("target var null", +//% substrs=["(void (*)())", "null = 0x"]) + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py new file mode 100644 index 00000000000..4ead709cf56 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py @@ -0,0 +1,93 @@ +""" +Test that global operators are found and evaluated. +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestCppGlobalOperators(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def prepare_executable_and_get_frame(self): + self.build() + + # Get main source file + src_file = "main.cpp" + src_file_spec = lldb.SBFileSpec(src_file) + self.assertTrue(src_file_spec.IsValid(), "Main source file") + + # Get the path of the executable + exe_path = self.getBuildArtifact("a.out") + + # Load the executable + target = self.dbg.CreateTarget(exe_path) + self.assertTrue(target.IsValid(), VALID_TARGET) + + # Break on main function + main_breakpoint = target.BreakpointCreateBySourceRegex( + "// break here", src_file_spec) + self.assertTrue( + main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Launch the process + args = None + env = None + process = target.LaunchSimple( + args, env, self.get_process_working_directory()) + self.assertTrue(process.IsValid(), PROCESS_IS_VALID) + + # Get the thread of the process + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + + return thread.GetSelectedFrame() + + def test_equals_operator(self): + frame = self.prepare_executable_and_get_frame() + + test_result = frame.EvaluateExpression("operator==(s1, s2)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "operator==(s1, s2) = false") + + test_result = frame.EvaluateExpression("operator==(s1, s3)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "true", + "operator==(s1, s3) = true") + + test_result = frame.EvaluateExpression("operator==(s2, s3)") + self.assertTrue( + test_result.IsValid() and test_result.GetValue() == "false", + "operator==(s2, s3) = false") + + def do_new_test(self, frame, expr, expected_value_name): + """Evaluate a new expression, and check its result""" + + expected_value = frame.FindValue( + expected_value_name, lldb.eValueTypeVariableGlobal) + self.assertTrue(expected_value.IsValid()) + + expected_value_addr = expected_value.AddressOf() + self.assertTrue(expected_value_addr.IsValid()) + + got = frame.EvaluateExpression(expr) + self.assertTrue(got.IsValid()) + self.assertEqual( + got.GetValueAsUnsigned(), + expected_value_addr.GetValueAsUnsigned()) + got_type = got.GetType() + self.assertTrue(got_type.IsPointerType()) + self.assertEqual(got_type.GetPointeeType().GetName(), "Struct") + + def test_operator_new(self): + frame = self.prepare_executable_and_get_frame() + + self.do_new_test(frame, "new Struct()", "global_new_buf") + self.do_new_test(frame, "new(new_tag) Struct()", "tagged_new_buf") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/main.cpp new file mode 100644 index 00000000000..c6dafd29586 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_operators/main.cpp @@ -0,0 +1,42 @@ +#include <new> + +struct new_tag_t +{ +}; +new_tag_t new_tag; + +struct Struct { + int value; +}; + +bool operator==(const Struct &a, const Struct &b) { + return a.value == b.value; +} + +typedef char buf_t[sizeof(Struct)]; +buf_t global_new_buf, tagged_new_buf; + +// This overrides global operator new +// This function and the following does not actually allocate memory. We are merely +// trying to make sure it is getting called. +void * +operator new(std::size_t count) +{ + return &global_new_buf; +} + +// A custom allocator +void * +operator new(std::size_t count, const new_tag_t &) +{ + return &tagged_new_buf; +} + +int main() { + Struct s1, s2, s3; + s1.value = 3; + s2.value = 5; + s3.value = 3; + return 0; // break here +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_variables/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_variables/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_variables/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_variables/TestCPPGlobalVariables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_variables/TestCPPGlobalVariables.py new file mode 100644 index 00000000000..4870247995f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_variables/TestCPPGlobalVariables.py @@ -0,0 +1,40 @@ +"""Test that C++ global variables can be inspected by name and also their mangled name.""" + + + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class GlobalVariablesCppTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.source = lldb.SBFileSpec('main.cpp') + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") + def test(self): + self.build() + + (target, _, _, _) = lldbutil.run_to_source_breakpoint(self, "// Set break point at this line.", self.source) + + # Check that we can access g_file_global_int by its name + self.expect("target variable g_file_global_int", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['42']) + self.expect("target variable abc::g_file_global_int", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['42']) + self.expect("target variable xyz::g_file_global_int", VARIABLES_DISPLAYED_CORRECTLY, + error=True, substrs=['can\'t find global variable']) + + # Check that we can access g_file_global_int by its mangled name + addr = target.EvaluateExpression("&abc::g_file_global_int").GetValueAsUnsigned() + self.assertTrue(addr != 0) + mangled = lldb.SBAddress(addr, target).GetSymbol().GetMangledName() + self.assertTrue(mangled != None) + gv = target.FindFirstGlobalVariable(mangled) + self.assertTrue(gv.IsValid()) + self.assertEqual(gv.GetName(), "abc::g_file_global_int") + self.assertEqual(gv.GetValueAsUnsigned(), 42) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_variables/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_variables/main.cpp new file mode 100644 index 00000000000..0a164186e71 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/global_variables/main.cpp @@ -0,0 +1,17 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +namespace abc { + int g_file_global_int = 42; +} + +int main (int argc, char const *argv[]) +{ + return abc::g_file_global_int; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/TestGModules.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/TestGModules.py new file mode 100644 index 00000000000..69d04636d86 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/TestGModules.py @@ -0,0 +1,6 @@ +import lldbsuite.test.lldbinline as lldbinline +from lldbsuite.test.decorators import * + +lldbinline.MakeInlineTest(__file__, globals(), [ + expectedFailureAll(oslist=["linux"], bugnumber="llvm.org/pr36107", + debug_info="gmodules")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/a.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/a.h new file mode 100644 index 00000000000..7384f230801 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/a.h @@ -0,0 +1,7 @@ +#include "memory.h" + +class MemoryBuffer { int buffer = 42; }; + +struct SrcBuffer { + my_std::unique_ptr<MemoryBuffer> Buffer; +}; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/b.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/b.h new file mode 100644 index 00000000000..b777e8e3473 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/b.h @@ -0,0 +1,6 @@ +#include "a.h" +#include "memory.h" + +class Module { + my_std::unique_ptr<MemoryBuffer> MBptr; +}; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/main.cpp new file mode 100644 index 00000000000..df752616570 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/main.cpp @@ -0,0 +1,9 @@ +#include "b.h" + +int main(int argc, const char * argv[]) +{ + Module m; + // Test that the type Module which contains a field that is a + // template instantiation can be fully resolved. + return 0; //% self.assertTrue(self.frame().FindVariable('m').GetChildAtIndex(0).GetChildAtIndex(0).GetChildAtIndex(0).GetName() == 'buffer', 'find template specializations in imported modules') +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/memory.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/memory.h new file mode 100644 index 00000000000..1d59dc0bbf0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/memory.h @@ -0,0 +1,8 @@ +#ifndef MEMORY_H +#define MEMORY_H +namespace my_std { + template<class T> class unique_ptr { + T t; + }; +} +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/module.modulemap b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/module.modulemap new file mode 100644 index 00000000000..2f05073a0b8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules-templates/module.modulemap @@ -0,0 +1,11 @@ +module A { + header "a.h" +} + +module B { + header "b.h" +} + +module std { + header "memory.h" +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/Makefile new file mode 100644 index 00000000000..a98dca64e8a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/Makefile @@ -0,0 +1,5 @@ +PCH_CXX_SOURCE = pch.h +CXX_SOURCES = main.cpp +CFLAGS_EXTRAS := $(MODULE_DEBUG_INFO_FLAGS) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/TestWithModuleDebugging.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/TestWithModuleDebugging.py new file mode 100644 index 00000000000..20207c54db9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/TestWithModuleDebugging.py @@ -0,0 +1,94 @@ +import lldb +import os +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestWithGmodulesDebugInfo(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(bugnumber="llvm.org/pr36146", oslist=["linux"], archs=["i386"]) + @add_test_categories(["gmodules"]) + def test_specialized_typedef_from_pch(self): + self.build() + + src_file = os.path.join(self.getSourceDir(), "main.cpp") + src_file_spec = lldb.SBFileSpec(src_file) + self.assertTrue(src_file_spec.IsValid(), "breakpoint file") + + # Get the path of the executable + exe_path = self.getBuildArtifact("a.out") + + # Load the executable + target = self.dbg.CreateTarget(exe_path) + self.assertTrue(target.IsValid(), VALID_TARGET) + + # Break on interesting line + breakpoint = target.BreakpointCreateBySourceRegex( + "break here", src_file_spec) + self.assertTrue( + breakpoint.IsValid() and breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Launch the process + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process.IsValid(), PROCESS_IS_VALID) + + # Get the thread of the process + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + + # Get frame for current thread + frame = thread.frames[0] + + testValue = frame.EvaluateExpression("test") + self.assertTrue( + testValue.GetError().Success(), + "Test expression value invalid: %s" % + (testValue.GetError().GetCString())) + self.assertTrue( + testValue.GetTypeName() == "IntContainer", + "Test expression type incorrect") + + memberValue = testValue.GetChildMemberWithName("storage") + self.assertTrue( + memberValue.GetError().Success(), + "Member value missing or invalid: %s" % + (testValue.GetError().GetCString())) + self.assertTrue( + memberValue.GetTypeName() == "int", + "Member type incorrect") + self.assertEqual( + 42, + memberValue.GetValueAsSigned(), + "Member value incorrect") + + testValue = frame.EvaluateExpression("bar") + self.assertTrue( + testValue.GetError().Success(), + "Test expression value invalid: %s" % + (testValue.GetError().GetCString())) + self.assertTrue( + testValue.GetTypeName() == "Foo::Bar", + "Test expression type incorrect") + + memberValue = testValue.GetChildMemberWithName("i") + self.assertTrue( + memberValue.GetError().Success(), + "Member value missing or invalid: %s" % + (testValue.GetError().GetCString())) + self.assertTrue( + memberValue.GetTypeName() == "int", + "Member type incorrect") + self.assertEqual( + 123, + memberValue.GetValueAsSigned(), + "Member value incorrect") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/main.cpp new file mode 100644 index 00000000000..588a3a8e01f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/main.cpp @@ -0,0 +1,8 @@ +class Foo::Bar { int i = 123; }; + +int main(int argc, const char * argv[]) +{ + IntContainer test(42); + Foo::Bar bar; + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/pch.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/pch.h new file mode 100644 index 00000000000..dba4fee9a8c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/gmodules/pch.h @@ -0,0 +1,17 @@ +template<typename T> +class GenericContainer { + private: + T storage; + + public: + GenericContainer(T value) { + storage = value; + }; +}; + +typedef GenericContainer<int> IntContainer; + +struct Foo { + class Bar; + Bar *bar; +}; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/Makefile new file mode 100644 index 00000000000..769920c2833 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/Makefile @@ -0,0 +1,33 @@ +CXX_SOURCES = main.cpp length.cpp a.cpp + +CFLAGS_LIMIT = -c $(CXXFLAGS) +CFLAGS_NO_LIMIT = -c $(CXXFLAGS) + +ifneq (,$(findstring clang,$(CC))) + CFLAGS_LIMIT += -flimit-debug-info + CFLAGS_NO_LIMIT += -fno-limit-debug-info +endif + +all: limit nolimit + +limit: main.o length_limit.o a.o + $(CXX) main.o length_limit.o a.o -o limit $(LDFLAGS) + +nolimit: main.o length_nolimit.o a.o + $(CXX) main.o length_nolimit.o a.o -o nolimit $(LDFLAGS) + +main.o: main.cpp + $(CXX) $(CFLAGS_LIMIT) $(SRCDIR)/main.cpp -o main.o + +length_limit.o: length.cpp + $(CXX) $(CFLAGS_LIMIT) $(SRCDIR)/length.cpp -o length_limit.o + +length_nolimit.o: length.cpp + $(CXX) $(CFLAGS_NO_LIMIT) $(SRCDIR)/length.cpp -o length_nolimit.o + +a.o: a.cpp + $(CXX) $(CFLAGS_NO_DEBUG) -c $(SRCDIR)/a.cpp -o a.o + +clean: OBJECTS += limit nolimit length_limit.o length_nolimit.o length_limit.dwo length_nolimit.dwo + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py new file mode 100644 index 00000000000..7ce2e343b88 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py @@ -0,0 +1,55 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestCppIncompleteTypes(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(compiler="gcc") + def test_limit_debug_info(self): + self.build() + frame = self.get_test_frame('limit') + + value_f = frame.EvaluateExpression("f") + self.assertTrue( + value_f.IsValid(), + "'expr f' results in a valid SBValue object") + self.assertTrue(value_f.GetError().Success(), "'expr f' is successful") + + value_a = frame.EvaluateExpression("a") + self.assertTrue( + value_a.IsValid(), + "'expr a' results in a valid SBValue object") + self.assertTrue(value_a.GetError().Success(), "'expr a' is successful") + + @skipIf(compiler="gcc") + # Clang on Windows asserts in external record layout in this case. + @skipIfWindows + def test_partial_limit_debug_info(self): + self.build() + frame = self.get_test_frame('nolimit') + + value_f = frame.EvaluateExpression("f") + self.assertTrue( + value_f.IsValid(), + "'expr f' results in a valid SBValue object") + self.assertTrue(value_f.GetError().Success(), "'expr f' is successful") + + value_a = frame.EvaluateExpression("a") + self.assertTrue( + value_a.IsValid(), + "'expr a' results in a valid SBValue object") + self.assertTrue(value_a.GetError().Success(), "'expr a' is successful") + + def get_test_frame(self, exe): + # Get main source file + src_file = "main.cpp" + src_file_spec = lldb.SBFileSpec(src_file) + + (target, process, thread, main_breakpoint) = lldbutil.run_to_source_breakpoint(self, + "break here", src_file_spec, exe_name = exe) + # Get frame for current thread + return thread.GetSelectedFrame() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.cpp new file mode 100644 index 00000000000..36b374be6f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.cpp @@ -0,0 +1,10 @@ + +#include "a.h" + +A::A () { } + +int +A::length () +{ + return 123; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.h new file mode 100644 index 00000000000..13e9496e3fd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.h @@ -0,0 +1,11 @@ +#ifndef __A_H__ +#define __A_H__ + +class A +{ +public: + A(); + virtual int length(); +}; + +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.cpp new file mode 100644 index 00000000000..90a3b640f73 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.cpp @@ -0,0 +1,8 @@ + +#include "length.h" + +int +length (A &a) +{ + return a.length(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.h new file mode 100644 index 00000000000..96df4f02180 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.h @@ -0,0 +1,8 @@ +#ifndef __LENGTH_H__ +#define __LENGTH_H__ + +#include "a.h" + +int length (A &a); + +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/main.cpp new file mode 100644 index 00000000000..ad324c90581 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/main.cpp @@ -0,0 +1,18 @@ + +#include "length.h" + +class Foo { +public: + A a; +}; + +class MyA : public A { +}; + +int main() +{ + Foo f; + MyA a; + + return length(a); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/Makefile new file mode 100644 index 00000000000..055e318e220 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := inlines.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/TestInlines.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/TestInlines.py new file mode 100644 index 00000000000..5f77d8f5963 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/TestInlines.py @@ -0,0 +1,59 @@ +"""Test variable lookup when stopped in inline functions.""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class InlinesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number( + 'inlines.cpp', + '// Set break point at this line.') + + @expectedFailureAll("llvm.org/pr26710", oslist=["linux"], compiler="gcc") + def test(self): + """Test that local variables are visible in expressions.""" + self.build() + self.runToBreakpoint() + + # Check that 'frame variable' finds a variable + self.expect( + "frame variable inner_input", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) inner_input =') + + # Check that 'expr' finds a variable + self.expect("expr inner_input", VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) $0 =') + + def runToBreakpoint(self): + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the main. + lldbutil.run_break_set_by_file_and_line( + self, + "inlines.cpp", + self.line, + num_expected_locations=2, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/inlines.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/inlines.cpp new file mode 100644 index 00000000000..822d88e22f9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/inlines.cpp @@ -0,0 +1,53 @@ +#include <stdio.h> +#include "inlines.h" + +#define INLINE_ME __inline__ __attribute__((always_inline)) + +int +not_inlined_2 (int input) +{ + printf ("Called in not_inlined_2 with : %d.\n", input); + return input; +} + +int +not_inlined_1 (int input) +{ + printf ("Called in not_inlined_1 with %d.\n", input); + return not_inlined_2(input); +} + +INLINE_ME int +inner_inline (int inner_input, int mod_value) +{ + int inner_result; + inner_result = inner_input % mod_value; + printf ("Returning: %d.\n", inner_result); + return not_inlined_1 (inner_result); // Set break point at this line. +} + +INLINE_ME int +outer_inline (int outer_input) +{ + int outer_result; + + outer_result = inner_inline (outer_input, outer_input % 3); + return outer_result; +} + +int +main (int argc, char **argv) +{ + printf ("Starting...\n"); + + int (*func_ptr) (int); + func_ptr = outer_inline; + + outer_inline (argc); + + func_ptr (argc); + + return 0; +} + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/inlines.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/inlines.h new file mode 100644 index 00000000000..265d7b4966e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/inlines/inlines.h @@ -0,0 +1,4 @@ +int inner_inline (int inner_input, int mod_value); +int outer_inline (int outer_input); +int not_inlined_2 (int input); +int not_inlined_1 (int input); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/TestLambdas.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/TestLambdas.py new file mode 100644 index 00000000000..c8308c16011 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/TestLambdas.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/main.cpp new file mode 100644 index 00000000000..5870c877f4a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/lambdas/main.cpp @@ -0,0 +1,16 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +int main (int argc, char const *argv[]) +{ + printf("Stop here\n"); //% self.runCmd("expression auto $add = [](int first, int second) { return first + second; }") + //% self.expect("expression $add(2,3)", substrs = ['= 5']) + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/Makefile new file mode 100644 index 00000000000..ba7e0153752 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES = main.cpp derived.cpp base.cpp + +CFLAGS_EXTRAS := $(LIMIT_DEBUG_INFO_FLAGS) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py new file mode 100644 index 00000000000..ae50d3d3966 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py @@ -0,0 +1,63 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestWithLimitDebugInfo(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(debug_info=no_match(["dwarf"])) + def test_limit_debug_info(self): + self.build() + + src_file = os.path.join(self.getSourceDir(), "main.cpp") + src_file_spec = lldb.SBFileSpec(src_file) + self.assertTrue(src_file_spec.IsValid(), "breakpoint file") + + # Get the path of the executable + exe_path = self.getBuildArtifact("a.out") + + # Load the executable + target = self.dbg.CreateTarget(exe_path) + self.assertTrue(target.IsValid(), VALID_TARGET) + + # Break on main function + breakpoint = target.BreakpointCreateBySourceRegex( + "break here", src_file_spec) + self.assertTrue( + breakpoint.IsValid() and breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Launch the process + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process.IsValid(), PROCESS_IS_VALID) + + # Get the thread of the process + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + thread.StepInto() + + # Get frame for current thread + frame = thread.GetSelectedFrame() + + v1 = frame.EvaluateExpression("1") + self.assertTrue( + v1.IsValid(), + "'expr 1' results in a valid SBValue object") + self.assertTrue( + v1.GetError().Success(), + "'expr 1' succeeds without an error.") + + v2 = frame.EvaluateExpression("this") + self.assertTrue( + v2.IsValid(), + "'expr this' results in a valid SBValue object") + self.assertTrue( + v2.GetError().Success(), + "'expr this' succeeds without an error.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.cpp new file mode 100644 index 00000000000..4023bdbc64a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.cpp @@ -0,0 +1,6 @@ +#include "base.h" + +void FooNS::bar() { + x = 54321; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.h new file mode 100644 index 00000000000..d3a09572bd2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.h @@ -0,0 +1,10 @@ +class FooNS +{ +public: + virtual void bar(); + virtual char baz() = 0; + +protected: + int x; +}; + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.cpp new file mode 100644 index 00000000000..9d773593eb5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.cpp @@ -0,0 +1,6 @@ +#include "derived.h" + +char Foo::baz() { + return (char)(x&0xff); +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.h new file mode 100644 index 00000000000..46b3f83b9f7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.h @@ -0,0 +1,13 @@ +#include "base.h" + +class Foo : public FooNS +{ +public: + Foo() { + a = 12345; + } + + char baz() override; + int a; +}; + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/main.cpp new file mode 100644 index 00000000000..64e0349b582 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/main.cpp @@ -0,0 +1,7 @@ +#include "derived.h" + +int main() { + Foo f; // break here + f.bar(); + return f.baz(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/llvm-style/TestLLVMStyle.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/llvm-style/TestLLVMStyle.py new file mode 100644 index 00000000000..c8308c16011 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/llvm-style/TestLLVMStyle.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/llvm-style/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/llvm-style/main.cpp new file mode 100644 index 00000000000..048eeb2d27b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/llvm-style/main.cpp @@ -0,0 +1,35 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +namespace n { + struct D { + int i; + static int anInt() { return 2; } + int dump() { return i; } + }; + + class C { + public: + int foo(D *D); + }; +} + +using namespace n; + +int C::foo(D* D) { + return D->dump(); //% self.expect("expression -- D->dump()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["int", "2"]) + //% self.expect("expression -- D::anInt()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["int", "2"]) + +} + +int main (int argc, char const *argv[]) +{ + D myD { D::anInt() }; + C().foo(&myD); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/Makefile new file mode 100644 index 00000000000..82f96b62609 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES = main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/TestMembersAndLocalsWithSameName.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/TestMembersAndLocalsWithSameName.py new file mode 100644 index 00000000000..a0dcbf00266 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/TestMembersAndLocalsWithSameName.py @@ -0,0 +1,285 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class TestMembersAndLocalsWithSameName(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_when_stopped_in_method(self): + self._load_exe() + + # Set breakpoints + bp1 = self.target.BreakpointCreateBySourceRegex( + "Break 1", self.src_file_spec) + self.assertTrue( + bp1.IsValid() and bp1.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp2 = self.target.BreakpointCreateBySourceRegex( + "Break 2", self.src_file_spec) + self.assertTrue( + bp2.IsValid() and bp2.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp3 = self.target.BreakpointCreateBySourceRegex( + "Break 3", self.src_file_spec) + self.assertTrue( + bp3.IsValid() and bp3.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp4 = self.target.BreakpointCreateBySourceRegex( + "Break 4", self.src_file_spec) + self.assertTrue( + bp4.IsValid() and bp4.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Launch the process + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(self.process.IsValid(), PROCESS_IS_VALID) + + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + self._test_globals() + + self.process.Continue() + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid()) + frame = thread.GetSelectedFrame() + self.assertTrue(frame.IsValid()) + + val = frame.EvaluateExpression("a") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 12345) + + val = frame.EvaluateExpression("b") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 54321) + + val = frame.EvaluateExpression("c") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 34567) + + self.process.Continue() + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid()) + frame = thread.GetSelectedFrame() + self.assertTrue(frame.IsValid()) + + val = frame.EvaluateExpression("a") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 10001) + + val = frame.EvaluateExpression("b") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 10002) + + val = frame.EvaluateExpression("c") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 10003) + + self.process.Continue() + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid()) + frame = thread.GetSelectedFrame() + self.assertTrue(frame.IsValid()) + + val = frame.EvaluateExpression("a") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 1) + + val = frame.EvaluateExpression("b") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 2) + + val = frame.EvaluateExpression("c") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 778899) + + def test_when_stopped_in_function(self): + self._load_exe() + + # Set breakpoints + bp1 = self.target.BreakpointCreateBySourceRegex( + "Break 1", self.src_file_spec) + self.assertTrue( + bp1.IsValid() and bp1.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp5 = self.target.BreakpointCreateBySourceRegex( + "Break 5", self.src_file_spec) + self.assertTrue( + bp5.IsValid() and bp5.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp6 = self.target.BreakpointCreateBySourceRegex( + "Break 6", self.src_file_spec) + self.assertTrue( + bp6.IsValid() and bp6.GetNumLocations() >= 1, + VALID_BREAKPOINT) + bp7 = self.target.BreakpointCreateBySourceRegex( + "Break 7", self.src_file_spec) + self.assertTrue( + bp7.IsValid() and bp7.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Launch the process + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(self.process.IsValid(), PROCESS_IS_VALID) + + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + self._test_globals() + + self.process.Continue() + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid()) + frame = thread.GetSelectedFrame() + self.assertTrue(frame.IsValid()) + + self.enable_expression_log() + val = frame.EvaluateExpression("a") + self.disable_expression_log_and_check_for_locals(['a']) + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 12345) + + val = frame.EvaluateExpression("b") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 54321) + + val = frame.EvaluateExpression("c") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 34567) + + self.process.Continue() + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid()) + frame = thread.GetSelectedFrame() + self.assertTrue(frame.IsValid()) + + val = frame.EvaluateExpression("a") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 10001) + + val = frame.EvaluateExpression("b") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 10002) + + val = frame.EvaluateExpression("c") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 10003) + + self.enable_expression_log() + val = frame.EvaluateExpression("c-b") + self.disable_expression_log_and_check_for_locals(['c','b']) + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 1) + + self.process.Continue() + self.assertTrue( + self.process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid()) + frame = thread.GetSelectedFrame() + self.assertTrue(frame.IsValid()) + + val = frame.EvaluateExpression("a") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 1) + + val = frame.EvaluateExpression("b") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 2) + + val = frame.EvaluateExpression("c") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 778899) + + self.enable_expression_log() + val = frame.EvaluateExpression("a+b") + self.disable_expression_log_and_check_for_locals(['a','b']) + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 3) + + + def _load_exe(self): + self.build() + + cwd = os.getcwd() + + src_file = os.path.join(cwd, "main.cpp") + self.src_file_spec = lldb.SBFileSpec(src_file) + self.assertTrue(self.src_file_spec.IsValid(), "breakpoint file") + + # Get the path of the executable + exe_path = self.getBuildArtifact("a.out") + + # Load the executable + self.target = self.dbg.CreateTarget(exe_path) + self.assertTrue(self.target.IsValid(), VALID_TARGET) + + def _test_globals(self): + thread = lldbutil.get_stopped_thread( + self.process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid()) + frame = thread.GetSelectedFrame() + self.assertTrue(frame.IsValid()) + + self.enable_expression_log() + val = frame.EvaluateExpression("a") + self.disable_expression_log_and_check_for_locals([]) + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 112233) + + val = frame.EvaluateExpression("b") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 445566) + + val = frame.EvaluateExpression("c") + self.assertTrue(val.IsValid()) + self.assertEqual(val.GetValueAsUnsigned(), 778899) + + def enable_expression_log(self): + log_file = os.path.join(self.getBuildDir(), "expr.log") + self.runCmd("log enable -f '%s' lldb expr" % (log_file)) + + def disable_expression_log_and_check_for_locals(self, variables): + log_file = os.path.join(self.getBuildDir(), "expr.log") + self.runCmd("log disable lldb expr") + local_var_regex = re.compile(r".*__lldb_local_vars::(.*);") + matched = [] + with open(log_file, 'r') as log: + for line in log: + if line.find('LLDB_BODY_START') != -1: + break + m = re.match(local_var_regex, line) + if m: + self.assertIn(m.group(1), variables) + matched.append(m.group(1)) + self.assertEqual([item for item in variables if item not in matched], + []) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/main.cpp new file mode 100644 index 00000000000..baf08f6a983 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/member-and-local-vars-with-same-name/main.cpp @@ -0,0 +1,73 @@ +namespace NN +{ + int a = 778899; + int b = 665544; + int c = 445566; +} + +class A +{ +public: + A(); + int Method(int a, int b); + +private: + int a, b; +}; + +A::A() : a(10), b(100) { } + +int a = 112233; +int b = 445566; +int c = 778899; + +int +A::Method(int a, int b) +{ + { + int a = 12345; + int b = 54321; + int c = 34567; + this->a = a + b + this->b; // Break 2 + } + + { + using namespace NN; + int a = 10001; + int b = 10002; + int c = 10003; + this->a = a + b + this->b; // Break 3 + } + + return this->a + this->b + a + b; // Break 4 +} + +int +Function(int a, int b) +{ + int A; + + { + int a = 12345; + int b = 54321; + int c = 34567; + A = a + b + c; // Break 5 + } + + { + using namespace NN; + int a = 10001; + int b = 10002; + int c = 10003; + A = a + b + c; // Break 6 + } + + return A + a + b; // Break 7 +} + +int +main() +{ + A obj; + return obj.Method(1, 2) + Function(1, 2); // Break 1 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Inputs/Bar.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Inputs/Bar.h new file mode 100644 index 00000000000..3d9a88c024d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Inputs/Bar.h @@ -0,0 +1 @@ +struct Bar { int success; }; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Inputs/Foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Inputs/Foo.h new file mode 100644 index 00000000000..1fe02e89786 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Inputs/Foo.h @@ -0,0 +1 @@ +struct Foo {}; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Inputs/module.modulemap b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Inputs/module.modulemap new file mode 100644 index 00000000000..4221d0f9134 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Inputs/module.modulemap @@ -0,0 +1,7 @@ +module Foo { + header "Foo.h" +} + +module Bar { + header "Bar.h" +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Makefile new file mode 100644 index 00000000000..3dff43b34c7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := main.cpp +CXXFLAGS_EXTRAS = $(MANDATORY_MODULE_BUILD_CFLAGS) -I$(BUILDDIR)/include + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/TestCXXModulesImport.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/TestCXXModulesImport.py new file mode 100644 index 00000000000..e7f98c63b5e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/TestCXXModulesImport.py @@ -0,0 +1,45 @@ +"""Test that importing modules in C++ works as expected.""" + + +import unittest2 +import lldb +import shutil + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CXXModulesImportTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def build(self): + include = self.getBuildArtifact('include') + lldbutil.mkdir_p(include) + for f in ['Foo.h', 'Bar.h', 'module.modulemap']: + shutil.copyfile(self.getSourcePath(os.path.join('Inputs', f)), + os.path.join(include, f)) + super(CXXModulesImportTestCase, self).build() + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + def test_expr(self): + self.build() + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, 'break here', lldb.SBFileSpec('main.cpp')) + + self.expect("expr -l Objective-C++ -- @import Bar") + self.expect("expr -- Bar()", substrs = ["success"]) + self.expect("expr -l Objective-C++ -- @import THIS_MODULE_DOES_NOT_EXIST", + error=True) + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + def test_expr_failing_import(self): + self.build() + shutil.rmtree(self.getBuildArtifact('include')) + target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, 'break here', lldb.SBFileSpec('main.cpp')) + + self.expect("expr -l Objective-C++ -- @import Bar", error=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/main.cpp new file mode 100644 index 00000000000..a6acf9a1a69 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/modules-import/main.cpp @@ -0,0 +1,7 @@ +#include "Foo.h" + +int main(int argc, char **argv) { + Foo foo; + // break here. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/Makefile new file mode 100644 index 00000000000..638974fafd6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp ns.cpp ns2.cpp ns3.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py new file mode 100644 index 00000000000..2221755fad3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py @@ -0,0 +1,236 @@ +""" +Test the printing of anonymous and named namespace variables. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NamespaceBreakpointTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(bugnumber="llvm.org/pr28548", compiler="gcc") + @expectedFailureAll(oslist=["windows"]) + def test_breakpoints_func_auto(self): + """Test that we can set breakpoints correctly by basename to find all functions whose basename is "func".""" + self.build() + + names = [ + "func()", + "func(int)", + "A::B::func()", + "A::func()", + "A::func(int)"] + + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + module_list = lldb.SBFileSpecList() + module_list.Append(lldb.SBFileSpec(exe, False)) + cu_list = lldb.SBFileSpecList() + # Set a breakpoint by name "func" which should pick up all functions + # whose basename is "func" + bp = target.BreakpointCreateByName( + "func", lldb.eFunctionNameTypeAuto, module_list, cu_list) + for bp_loc in bp: + name = bp_loc.GetAddress().GetFunction().GetName() + self.assertTrue( + name in names, + "make sure breakpoint locations are correct for 'func' with eFunctionNameTypeAuto") + + @expectedFailureAll(bugnumber="llvm.org/pr28548", compiler="gcc") + def test_breakpoints_func_full(self): + """Test that we can set breakpoints correctly by fullname to find all functions whose fully qualified name is "func" + (no namespaces).""" + self.build() + + names = ["func()", "func(int)"] + + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + module_list = lldb.SBFileSpecList() + module_list.Append(lldb.SBFileSpec(exe, False)) + cu_list = lldb.SBFileSpecList() + + # Set a breakpoint by name "func" whose fullly qualified named matches "func" which + # should pick up only functions whose basename is "func" and has no + # containing context + bp = target.BreakpointCreateByName( + "func", lldb.eFunctionNameTypeFull, module_list, cu_list) + for bp_loc in bp: + name = bp_loc.GetAddress().GetFunction().GetName() + self.assertTrue( + name in names, + "make sure breakpoint locations are correct for 'func' with eFunctionNameTypeFull") + + def test_breakpoints_a_func_full(self): + """Test that we can set breakpoints correctly by fullname to find all functions whose fully qualified name is "A::func".""" + self.build() + + names = ["A::func()", "A::func(int)"] + + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + module_list = lldb.SBFileSpecList() + module_list.Append(lldb.SBFileSpec(exe, False)) + cu_list = lldb.SBFileSpecList() + + # Set a breakpoint by name "A::func" whose fullly qualified named matches "A::func" which + # should pick up only functions whose basename is "func" and is + # contained in the "A" namespace + bp = target.BreakpointCreateByName( + "A::func", lldb.eFunctionNameTypeFull, module_list, cu_list) + for bp_loc in bp: + name = bp_loc.GetAddress().GetFunction().GetName() + self.assertTrue( + name in names, + "make sure breakpoint locations are correct for 'A::func' with eFunctionNameTypeFull") + + +class NamespaceTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers for declarations of namespace variables i and + # j. + self.line_var_i = line_number( + 'main.cpp', '// Find the line number for anonymous namespace variable i.') + self.line_var_j = line_number( + 'main.cpp', '// Find the line number for named namespace variable j.') + # And the line number to break at. + self.line_break = line_number('main.cpp', + '// Set break point at this line.') + # Break inside do {} while and evaluate value + self.line_break_ns1 = line_number('main.cpp', '// Evaluate ns1::value') + self.line_break_ns2 = line_number('main.cpp', '// Evaluate ns2::value') + + def runToBkpt(self, command): + self.runCmd(command, RUN_SUCCEEDED) + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # rdar://problem/8668674 + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") + def test_with_run_command(self): + """Test that anonymous and named namespace variables display correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line_break_ns1, + num_expected_locations=1, + loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line_break_ns2, + num_expected_locations=1, + loc_exact=True) + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line_break, + num_expected_locations=1, + loc_exact=True) + + self.runToBkpt("run") + # Evaluate ns1::value + self.expect("expression -- value", startstr="(int) $0 = 100") + + self.runToBkpt("continue") + # Evaluate ns2::value + self.expect("expression -- value", startstr="(int) $1 = 200") + + self.runToBkpt("continue") + # On Mac OS X, gcc 4.2 emits the wrong debug info with respect to + # types. + slist = ['(int) a = 12', 'anon_uint', 'a_uint', 'b_uint', 'y_uint'] + if self.platformIsDarwin() and self.getCompiler() in [ + 'clang', 'llvm-gcc']: + slist = ['(int) a = 12', + '::my_uint_t', 'anon_uint = 0', + '(A::uint_t) a_uint = 1', + '(A::B::uint_t) b_uint = 2', + '(Y::uint_t) y_uint = 3'] + + # 'frame variable' displays the local variables with type information. + self.expect('frame variable', VARIABLES_DISPLAYED_CORRECTLY, + substrs=slist) + + # 'frame variable' with basename 'i' should work. + self.expect( + "frame variable --show-declaration --show-globals i", + startstr="main.cpp:%d: (int) (anonymous namespace)::i = 3" % + self.line_var_i) + # main.cpp:12: (int) (anonymous namespace)::i = 3 + + # 'frame variable' with basename 'j' should work, too. + self.expect( + "frame variable --show-declaration --show-globals j", + startstr="main.cpp:%d: (int) A::B::j = 4" % + self.line_var_j) + # main.cpp:19: (int) A::B::j = 4 + + # 'frame variable' should support address-of operator. + self.runCmd("frame variable &i") + + # 'frame variable' with fully qualified name 'A::B::j' should work. + self.expect("frame variable A::B::j", VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) A::B::j = 4', + patterns=[' = 4']) + + # So should the anonymous namespace case. + self.expect( + "frame variable '(anonymous namespace)::i'", + VARIABLES_DISPLAYED_CORRECTLY, + startstr='(int) (anonymous namespace)::i = 3', + patterns=[' = 3']) + + # rdar://problem/8660275 + # test/namespace: 'expression -- i+j' not working + # This has been fixed. + self.expect("expression -- i + j", + startstr="(int) $2 = 7") + # (int) $2 = 7 + + self.runCmd("expression -- i") + self.runCmd("expression -- j") + + # rdar://problem/8668674 + # expression command with fully qualified namespace for a variable does + # not work + self.expect("expression -- ::i", VARIABLES_DISPLAYED_CORRECTLY, + patterns=[' = 3']) + self.expect("expression -- A::B::j", VARIABLES_DISPLAYED_CORRECTLY, + patterns=[' = 4']) + + # expression command with function in anonymous namespace + self.expect("expression -- myanonfunc(3)", + patterns=[' = 6']) + + # global namespace qualification with function in anonymous namespace + self.expect("expression -- ::myanonfunc(4)", + patterns=[' = 8']) + + self.expect("p myanonfunc", + patterns=['\(anonymous namespace\)::myanonfunc\(int\)']) + + self.expect("p variadic_sum", patterns=[ + '\(anonymous namespace\)::variadic_sum\(int, ...\)']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py new file mode 100644 index 00000000000..5526a14f530 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py @@ -0,0 +1,314 @@ +""" +Test the printing of anonymous and named namespace variables. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class NamespaceLookupTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Break inside different scopes and evaluate value + self.line_break_global_scope = line_number( + 'ns.cpp', '// BP_global_scope') + self.line_break_file_scope = line_number('ns2.cpp', '// BP_file_scope') + self.line_break_ns_scope = line_number('ns2.cpp', '// BP_ns_scope') + self.line_break_nested_ns_scope = line_number( + 'ns2.cpp', '// BP_nested_ns_scope') + self.line_break_nested_ns_scope_after_using = line_number( + 'ns2.cpp', '// BP_nested_ns_scope_after_using') + self.line_break_before_using_directive = line_number( + 'ns3.cpp', '// BP_before_using_directive') + self.line_break_after_using_directive = line_number( + 'ns3.cpp', '// BP_after_using_directive') + + def runToBkpt(self, command): + self.runCmd(command, RUN_SUCCEEDED) + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr25819") + @skipIfWindows # This is flakey on Windows: llvm.org/pr38373 + def test_scope_lookup_with_run_command(self): + """Test scope lookup of functions in lldb.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "ns.cpp", + self.line_break_global_scope, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_ns_scope, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_nested_ns_scope, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_nested_ns_scope_after_using, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_before_using_directive, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_after_using_directive, + num_expected_locations=1, + loc_exact=False) + + # Run to BP_global_scope at global scope + self.runToBkpt("run") + # Evaluate func() - should call ::func() + self.expect("expr -- func()", startstr="(int) $0 = 1") + # Evaluate A::B::func() - should call A::B::func() + self.expect("expr -- A::B::func()", startstr="(int) $1 = 4") + # Evaluate func(10) - should call ::func(int) + self.expect("expr -- func(10)", startstr="(int) $2 = 11") + # Evaluate ::func() - should call A::func() + self.expect("expr -- ::func()", startstr="(int) $3 = 1") + # Evaluate A::foo() - should call A::foo() + self.expect("expr -- A::foo()", startstr="(int) $4 = 42") + + # Continue to BP_ns_scope at ns scope + self.runToBkpt("continue") + # Evaluate func(10) - should call A::func(int) + self.expect("expr -- func(10)", startstr="(int) $5 = 13") + # Evaluate B::func() - should call B::func() + self.expect("expr -- B::func()", startstr="(int) $6 = 4") + # Evaluate func() - should call A::func() + self.expect("expr -- func()", startstr="(int) $7 = 3") + + # Continue to BP_nested_ns_scope at nested ns scope + self.runToBkpt("continue") + # Evaluate func() - should call A::B::func() + self.expect("expr -- func()", startstr="(int) $8 = 4") + # Evaluate A::func() - should call A::func() + self.expect("expr -- A::func()", startstr="(int) $9 = 3") + + # Evaluate func(10) - should call A::func(10) + # NOTE: Under the rules of C++, this test would normally get an error + # because A::B::func() hides A::func(), but lldb intentionally + # disobeys these rules so that the intended overload can be found + # by only removing duplicates if they have the same type. + self.expect("expr -- func(10)", startstr="(int) $10 = 13") + + # Continue to BP_nested_ns_scope_after_using at nested ns scope after + # using declaration + self.runToBkpt("continue") + # Evaluate A::func(10) - should call A::func(int) + self.expect("expr -- A::func(10)", startstr="(int) $11 = 13") + + # Continue to BP_before_using_directive at global scope before using + # declaration + self.runToBkpt("continue") + # Evaluate ::func() - should call ::func() + self.expect("expr -- ::func()", startstr="(int) $12 = 1") + # Evaluate B::func() - should call B::func() + self.expect("expr -- B::func()", startstr="(int) $13 = 4") + + # Continue to BP_after_using_directive at global scope after using + # declaration + self.runToBkpt("continue") + # Evaluate ::func() - should call ::func() + self.expect("expr -- ::func()", startstr="(int) $14 = 1") + # Evaluate B::func() - should call B::func() + self.expect("expr -- B::func()", startstr="(int) $15 = 4") + + @unittest2.expectedFailure("lldb scope lookup of functions bugs") + def test_function_scope_lookup_with_run_command(self): + """Test scope lookup of functions in lldb.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "ns.cpp", + self.line_break_global_scope, + num_expected_locations=1, + loc_exact=False) + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_ns_scope, + num_expected_locations=1, + loc_exact=False) + + # Run to BP_global_scope at global scope + self.runToBkpt("run") + # Evaluate foo() - should call ::foo() + # FIXME: lldb finds Y::foo because lookup for variables is done + # before functions. + self.expect("expr -- foo()", startstr="(int) $0 = 42") + # Evaluate ::foo() - should call ::foo() + # FIXME: lldb finds Y::foo because lookup for variables is done + # before functions and :: is ignored. + self.expect("expr -- ::foo()", startstr="(int) $1 = 42") + + # Continue to BP_ns_scope at ns scope + self.runToBkpt("continue") + # Evaluate foo() - should call A::foo() + # FIXME: lldb finds Y::foo because lookup for variables is done + # before functions. + self.expect("expr -- foo()", startstr="(int) $2 = 42") + + @unittest2.expectedFailure("lldb file scope lookup bugs") + @skipIfWindows # This is flakey on Windows: llvm.org/pr38373 + def test_file_scope_lookup_with_run_command(self): + """Test file scope lookup in lldb.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_file_scope, + num_expected_locations=1, + loc_exact=False) + + # Run to BP_file_scope at file scope + self.runToBkpt("run") + # Evaluate func() - should call static ns2.cpp:func() + # FIXME: This test fails because lldb doesn't know about file scopes so + # finds the global ::func(). + self.expect("expr -- func()", startstr="(int) $0 = 2") + + @skipIfWindows # This is flakey on Windows: llvm.org/pr38373 + def test_scope_lookup_before_using_with_run_command(self): + """Test scope lookup before using in lldb.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_before_using_directive, + num_expected_locations=1, + loc_exact=False) + + # Run to BP_before_using_directive at global scope before using + # declaration + self.runToBkpt("run") + # Evaluate func() - should call ::func() + self.expect("expr -- func()", startstr="(int) $0 = 1") + + # NOTE: this test may fail on older systems that don't emit import + # entries in DWARF - may need to add checks for compiler versions here. + @skipIf( + compiler="gcc", + oslist=["linux"], + debug_info=["dwo"]) # Skip to avoid crash + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr25819") + def test_scope_after_using_directive_lookup_with_run_command(self): + """Test scope lookup after using directive in lldb.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_after_using_directive, + num_expected_locations=1, + loc_exact=False) + + # Run to BP_after_using_directive at global scope after using + # declaration + self.runToBkpt("run") + # Evaluate func2() - should call A::func2() + self.expect("expr -- func2()", startstr="(int) $0 = 3") + + @unittest2.expectedFailure( + "lldb scope lookup after using declaration bugs") + # NOTE: this test may fail on older systems that don't emit import + # emtries in DWARF - may need to add checks for compiler versions here. + def test_scope_after_using_declaration_lookup_with_run_command(self): + """Test scope lookup after using declaration in lldb.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_nested_ns_scope_after_using, + num_expected_locations=1, + loc_exact=False) + + # Run to BP_nested_ns_scope_after_using at nested ns scope after using + # declaration + self.runToBkpt("run") + # Evaluate func() - should call A::func() + self.expect("expr -- func()", startstr="(int) $0 = 3") + + @unittest2.expectedFailure("lldb scope lookup ambiguity after using bugs") + def test_scope_ambiguity_after_using_lookup_with_run_command(self): + """Test scope lookup ambiguity after using in lldb.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "ns3.cpp", + self.line_break_after_using_directive, + num_expected_locations=1, + loc_exact=False) + + # Run to BP_after_using_directive at global scope after using + # declaration + self.runToBkpt("run") + # Evaluate func() - should get error: ambiguous + # FIXME: This test fails because lldb removes duplicates if they have + # the same type. + self.expect("expr -- func()", startstr="error") + + @expectedFailureAll( + oslist=["freebsd"], + bugnumber="llvm.org/pr25819") + def test_scope_lookup_shadowed_by_using_with_run_command(self): + """Test scope lookup shadowed by using in lldb.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "ns2.cpp", + self.line_break_nested_ns_scope, + num_expected_locations=1, + loc_exact=False) + + # Run to BP_nested_ns_scope at nested ns scope + self.runToBkpt("run") + # Evaluate func(10) - should call A::func(10) + # NOTE: Under the rules of C++, this test would normally get an error + # because A::B::func() shadows A::func(), but lldb intentionally + # disobeys these rules so that the intended overload can be found + # by only removing duplicates if they have the same type. + self.expect("expr -- func(10)", startstr="(int) $0 = 13") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/cmds.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/cmds.txt new file mode 100644 index 00000000000..76bb1bcba75 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/cmds.txt @@ -0,0 +1,3 @@ +b main.cpp:54 +c +var diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/main.cpp new file mode 100644 index 00000000000..22c0309695c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/main.cpp @@ -0,0 +1,124 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <cstdarg> +#include <cstdlib> +#include "ns.h" + +namespace { + typedef unsigned int my_uint_t; + int i; // Find the line number for anonymous namespace variable i. + + int myanonfunc (int a) + { + return a + a; + } + + int + variadic_sum (int arg_count...) + { + int sum = 0; + std::va_list args; + va_start(args, arg_count); + + for (int i = 0; i < arg_count; i++) + sum += va_arg(args, int); + + va_end(args); + return sum; + } +} + +namespace A { + typedef unsigned int uint_t; + namespace B { + typedef unsigned int uint_t; + int j; // Find the line number for named namespace variable j. + int myfunc (int a); + int myfunc2(int a) + { + return a + 2; + } + float myfunc (float f) + { + return f - 2.0; + } + } +} + +namespace Y +{ + typedef unsigned int uint_t; + using A::B::j; + int foo; +} + +using A::B::j; // using declaration + +namespace Foo = A::B; // namespace alias + +using Foo::myfunc; // using declaration + +using namespace Foo; // using directive + +namespace A { + namespace B { + using namespace Y; + int k; + } +} + +namespace ns1 { + int value = 100; +} + +namespace ns2 { + int value = 200; +} + +void test_namespace_scopes() { + do { + using namespace ns1; + printf("ns1::value = %d\n", value); // Evaluate ns1::value + } while(0); + + do { + using namespace ns2; + printf("ns2::value = %d\n", value); // Evaluate ns2::value + } while(0); +} + +int Foo::myfunc(int a) +{ + test_namespace_scopes(); + + ::my_uint_t anon_uint = 0; + A::uint_t a_uint = 1; + B::uint_t b_uint = 2; + Y::uint_t y_uint = 3; + i = 3; + j = 4; + printf("::i=%d\n", ::i); + printf("A::B::j=%d\n", A::B::j); + printf("variadic_sum=%d\n", variadic_sum(3, 1, 2, 3)); + myanonfunc(3); + return myfunc2(3) + j + i + a + 2 + anon_uint + a_uint + b_uint + y_uint; // Set break point at this line. +} + +int +main (int argc, char const *argv[]) +{ + test_lookup_at_global_scope(); + test_lookup_at_file_scope(); + A::test_lookup_at_ns_scope(); + A::B::test_lookup_at_nested_ns_scope(); + A::B::test_lookup_at_nested_ns_scope_after_using(); + test_lookup_before_using_directive(); + test_lookup_after_using_directive(); + return Foo::myfunc(12); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.cpp new file mode 100644 index 00000000000..481a9866fcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.cpp @@ -0,0 +1,31 @@ +//===-- ns.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "ns.h" + +int foo() +{ + std::printf("global foo()\n"); + return 42; +} +int func() +{ + std::printf("global func()\n"); + return 1; +} +int func(int a) +{ + std::printf("global func(int)\n"); + return a + 1; +} +void test_lookup_at_global_scope() +{ + // BP_global_scope + std::printf("at global scope: foo() = %d\n", foo()); // eval foo(), exp: 42 + std::printf("at global scope: func() = %d\n", func()); // eval func(), exp: 1 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.h new file mode 100644 index 00000000000..d04b45a7d7a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.h @@ -0,0 +1,33 @@ +//===-- ns.h ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <cstdio> + +void test_lookup_at_global_scope(); +void test_lookup_at_file_scope(); +void test_lookup_before_using_directive(); +void test_lookup_after_using_directive(); +int func(int a); +namespace A { +int foo(); +int func(int a); +inline int func() { + std::printf("A::func()\n"); + return 3; +} +inline int func2() { + std::printf("A::func2()\n"); + return 3; +} +void test_lookup_at_ns_scope(); +namespace B { +int func(); +void test_lookup_at_nested_ns_scope(); +void test_lookup_at_nested_ns_scope_after_using(); +} // namespace B +} // namespace A diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns2.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns2.cpp new file mode 100644 index 00000000000..9aae5d0a495 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns2.cpp @@ -0,0 +1,64 @@ +//===-- ns2.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "ns.h" + +static int func() +{ + std::printf("static m2.cpp func()\n"); + return 2; +} +void test_lookup_at_file_scope() +{ + // BP_file_scope + std::printf("at file scope: func() = %d\n", func()); // eval func(), exp: 2 + std::printf("at file scope: func(10) = %d\n", func(10)); // eval func(10), exp: 11 +} +namespace A { + namespace B { + int func() + { + std::printf("A::B::func()\n"); + return 4; + } + void test_lookup_at_nested_ns_scope() + { + // BP_nested_ns_scope + std::printf("at nested ns scope: func() = %d\n", func()); // eval func(), exp: 4 + + //printf("func(10) = %d\n", func(10)); // eval func(10), exp: 13 + // NOTE: Under the rules of C++, this test would normally get an error + // because A::B::func() hides A::func(), but lldb intentionally + // disobeys these rules so that the intended overload can be found + // by only removing duplicates if they have the same type. + } + void test_lookup_at_nested_ns_scope_after_using() + { + // BP_nested_ns_scope_after_using + using A::func; + std::printf("at nested ns scope after using: func() = %d\n", func()); // eval func(), exp: 3 + } + } +} +int A::foo() +{ + std::printf("A::foo()\n"); + return 42; +} +int A::func(int a) +{ + std::printf("A::func(int)\n"); + return a + 3; +} +void A::test_lookup_at_ns_scope() +{ + // BP_ns_scope + std::printf("at nested ns scope: func() = %d\n", func()); // eval func(), exp: 3 + std::printf("at nested ns scope: func(10) = %d\n", func(10)); // eval func(10), exp: 13 + std::printf("at nested ns scope: foo() = %d\n", foo()); // eval foo(), exp: 42 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns3.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns3.cpp new file mode 100644 index 00000000000..0f7a5050fde --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace/ns3.cpp @@ -0,0 +1,26 @@ +//===-- ns3.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "ns.h" +extern int func(); + +// Note: the following function must be before the using. +void test_lookup_before_using_directive() +{ + // BP_before_using_directive + std::printf("before using directive: func() = %d\n", func()); // eval func(), exp: 1 +} +using namespace A; +void test_lookup_after_using_directive() +{ + // BP_after_using_directive + //printf("func() = %d\n", func()); // eval func(), exp: error, amiguous + std::printf("after using directive: func2() = %d\n", func2()); // eval func2(), exp: 3 + std::printf("after using directive: ::func() = %d\n", ::func()); // eval ::func(), exp: 1 + std::printf("after using directive: B::func() = %d\n", B::func()); // eval B::func(), exp: 4 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_conflicts/TestNamespaceConflicts.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_conflicts/TestNamespaceConflicts.py new file mode 100644 index 00000000000..c8308c16011 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_conflicts/TestNamespaceConflicts.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_conflicts/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_conflicts/main.cpp new file mode 100644 index 00000000000..0349365d843 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_conflicts/main.cpp @@ -0,0 +1,28 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +namespace n { + struct D { + int i; + static int anInt() { return 2; } + int dump() { return i; } + }; +} + +using namespace n; + +int foo(D* D) { + return D->dump(); //% self.expect("expression -- D->dump()", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["int", "2"]) +} + +int main (int argc, char const *argv[]) +{ + D myD { D::anInt() }; + foo(&myD); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/Makefile new file mode 100644 index 00000000000..fc9165f67f4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/Makefile @@ -0,0 +1,15 @@ +LD_EXTRAS := -L. -la -lb +CXX_SOURCES := main.cpp + +a.out: liba libb + +include Makefile.rules + +liba: + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_NAME=a DYLIB_CXX_SOURCES=a.cpp + +libb: + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_NAME=b DYLIB_CXX_SOURCES=b.cpp + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/TestNamespaceDefinitions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/TestNamespaceDefinitions.py new file mode 100644 index 00000000000..e96a9fb93b7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/TestNamespaceDefinitions.py @@ -0,0 +1,73 @@ +"""Test that forward declarations don't cause bogus conflicts in namespaced types""" + + + +import unittest2 +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil + + +class NamespaceDefinitionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + bugnumber="llvm.org/pr28948", + compiler="gcc", + compiler_version=[ + "<", + "4.9"]) + @expectedFailureAll( + bugnumber="llvm.org/pr28948", + oslist=['linux'], compiler="gcc", archs=['arm','aarch64']) + @expectedFailureAll(oslist=["windows"]) + @expectedFailureNetBSD + def test_expr(self): + self.build() + self.common_setup() + + self.expect( + "expression -- Foo::MyClass()", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=['thing = ']) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.cpp' + self.line = line_number(self.source, '// Set breakpoint here') + self.shlib_names = ["a", "b"] + + def common_setup(self): + # Run in synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/a.cpp new file mode 100644 index 00000000000..2795b206e8e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/a.cpp @@ -0,0 +1,15 @@ +//===-- a.cpp ---------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "foo.h" + +class ThingInside { + int a; +}; + +Foo::MyClass a_class; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/b.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/b.cpp new file mode 100644 index 00000000000..b676865c4d2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/b.cpp @@ -0,0 +1,11 @@ +//===-- b.cpp ---------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "foo.h" + +Foo::MyClass b_class; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/foo.h new file mode 100644 index 00000000000..a2c64ab5928 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/foo.h @@ -0,0 +1,17 @@ +//===-- foo.h ---------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +class ThingInside; + +namespace Foo { + class MyClass { + ThingInside *thing; + public: + MyClass() { } + }; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/main.cpp new file mode 100644 index 00000000000..8703cd99246 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/namespace_definitions/main.cpp @@ -0,0 +1,15 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +int +main (int argc, char const *argv[]) +{ + return 0; // Set breakpoint here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/Makefile new file mode 100644 index 00000000000..020dce7c31d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp other.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/TestNestedClassWithParentInAnotherCU.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/TestNestedClassWithParentInAnotherCU.py new file mode 100644 index 00000000000..5b590d6363a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/TestNestedClassWithParentInAnotherCU.py @@ -0,0 +1,29 @@ +""" +Test that the expression evaluator can access members of nested classes even if +the parents of the nested classes were imported from another compilation unit. +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestNestedClassWithParentInAnotherCU(TestBase): + mydir = TestBase.compute_mydir(__file__) + + def test_nested_class_with_parent_in_another_cu(self): + self.main_source_file = lldb.SBFileSpec("main.cpp") + self.build() + (_, _, thread, _) = lldbutil.run_to_source_breakpoint(self, "// break here", self.main_source_file) + frame = thread.GetSelectedFrame() + # Parse the DIEs of the parent classes and the nested classes from + # other.cpp's CU. + warmup_result = frame.EvaluateExpression("b") + self.assertTrue(warmup_result.IsValid()) + # Inspect fields of the nested classes. This will reuse the types that + # were parsed during the evaluation above. By accessing a chain of + # fields, we try to verify that all the DIEs, reused types and + # declaration contexts were wired properly into lldb's parser's state. + expr_result = frame.EvaluateExpression("a.y.oY_inner.oX_inner") + self.assertTrue(expr_result.IsValid()) + self.assertEqual(expr_result.GetValue(), "42") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/main.cpp new file mode 100644 index 00000000000..8a6e6ff81d2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/main.cpp @@ -0,0 +1,22 @@ +#include "shared.h" + +struct WrapperA { + OuterY::Inner<unsigned int> y; +}; + +int main() { + // WrapperA refers to the Inner and Outer class DIEs from this CU. + WrapperA a; + // WrapperB refers to the Inner and Outer DIEs from the other.cpp CU. + // It is important that WrapperB is only forward-declared in shared.h. + WrapperB* b = foo(); + + // Evaluating 'b' here will parse other.cpp's DIEs for all + // the Inner and Outer classes from shared.h. + // + // Evaluating 'a' here will find and reuse the already-parsed + // versions of the Inner and Outer classes. In the associated test + // we make sure that we can still resolve all the types properly + // by evaluating 'a.y.oY_inner.oX_inner'. + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/other.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/other.cpp new file mode 100644 index 00000000000..71a9579c4e8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/other.cpp @@ -0,0 +1,10 @@ +#include "shared.h" + +struct WrapperB { + OuterY y; + OuterX x; +}; + +WrapperB* foo() { + return new WrapperB(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/shared.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/shared.h new file mode 100644 index 00000000000..627f49ab79c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nested-class-other-compilation-unit/shared.h @@ -0,0 +1,17 @@ +struct OuterX { + template<typename T> + struct Inner { + int oX_inner = 42; + }; +}; + +struct OuterY { + template<typename T> + struct Inner { + typename OuterX::Inner<T> oY_inner; + }; +}; + +struct WrapperB; + +WrapperB* foo(); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py new file mode 100644 index 00000000000..f42d194cd62 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py @@ -0,0 +1,136 @@ +""" +Tests imported namespaces in C++. +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestCppNsImport(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_with_run_command(self): + """Tests imported namespaces in C++.""" + self.build() + + # Get main source file + src_file = os.path.join(self.getSourceDir(), "main.cpp") + src_file_spec = lldb.SBFileSpec(src_file) + self.assertTrue(src_file_spec.IsValid(), "Main source file") + + # Get the path of the executable + exe_path = self.getBuildArtifact("a.out") + + # Load the executable + target = self.dbg.CreateTarget(exe_path) + self.assertTrue(target.IsValid(), VALID_TARGET) + + # Break on main function + break_0 = target.BreakpointCreateBySourceRegex( + "// break 0", src_file_spec) + self.assertTrue( + break_0.IsValid() and break_0.GetNumLocations() >= 1, + VALID_BREAKPOINT) + break_1 = target.BreakpointCreateBySourceRegex( + "// break 1", src_file_spec) + self.assertTrue( + break_1.IsValid() and break_1.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Launch the process + args = None + env = None + process = target.LaunchSimple( + args, env, self.get_process_working_directory()) + self.assertTrue(process.IsValid(), PROCESS_IS_VALID) + + # Get the thread of the process + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + + # Get current fream of the thread at the breakpoint + frame = thread.GetSelectedFrame() + + # Test imported namespaces + test_result = frame.EvaluateExpression("n") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 1, + "n = 1") + + test_result = frame.EvaluateExpression("N::n") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 1, + "N::n = 1") + + test_result = frame.EvaluateExpression("nested") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 3, + "nested = 3") + + test_result = frame.EvaluateExpression("anon") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 2, + "anon = 2") + + test_result = frame.EvaluateExpression("global") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 4, + "global = 4") + + test_result = frame.EvaluateExpression("fun_var") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 9, + "fun_var = 9") + + test_result = frame.EvaluateExpression("Fun::fun_var") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 0, + "Fun::fun_var = 0") + + test_result = frame.EvaluateExpression("not_imported") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 35, + "not_imported = 35") + + # Currently there is no way to distinguish between "::imported" and "imported" in ClangExpressionDeclMap so this fails + #test_result = frame.EvaluateExpression("::imported") + #self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 89, "::imported = 89") + + test_result = frame.EvaluateExpression("Imported::imported") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 99, + "Imported::imported = 99") + + test_result = frame.EvaluateExpression("imported") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 99, + "imported = 99") + + test_result = frame.EvaluateExpression("single") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 3, + "single = 3") + + # Continue to second breakpoint + process.Continue() + + # Get the thread of the process + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + + # Get current fream of the thread at the breakpoint + frame = thread.GetSelectedFrame() + + # Test function inside namespace + test_result = frame.EvaluateExpression("fun_var") + self.assertTrue( + test_result.IsValid() and test_result.GetValueAsSigned() == 5, + "fun_var = 5") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/main.cpp new file mode 100644 index 00000000000..e125ebaa243 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/nsimport/main.cpp @@ -0,0 +1,72 @@ +namespace N +{ + int n; +} + +namespace +{ + int anon; +} + +namespace Nested +{ + namespace + { + int nested; + } +} + +namespace Global +{ + int global; +} + +namespace Fun +{ + int fun_var; + int fun() + { + fun_var = 5; + return 0; // break 1 + } +} + +namespace Single +{ + int single = 3; +} + +namespace NotImportedBefore +{ + int not_imported = 45; +} + +using namespace Global; + +int not_imported = 35; +int fun_var = 9; + +namespace NotImportedAfter +{ + int not_imported = 55; +} + +namespace Imported +{ + int imported = 99; +} + +int imported = 89; + +int main() +{ + using namespace N; + using namespace Nested; + using namespace Imported; + using Single::single; + n = 1; + anon = 2; + nested = 3; + global = 4; + return Fun::fun(); // break 0 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/offsetof/TestOffsetofCpp.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/offsetof/TestOffsetofCpp.py new file mode 100644 index 00000000000..cdfbaae0ce3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/offsetof/TestOffsetofCpp.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), [decorators.no_debug_info_test]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/offsetof/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/offsetof/main.cpp new file mode 100644 index 00000000000..ab379f839c8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/offsetof/main.cpp @@ -0,0 +1,25 @@ +#include <cstdint> + +class Base { + int32_t a; +}; +class Class1 : Base { +public: + int32_t b; +}; + +class EmptyBase { +}; +class Class2 : EmptyBase { +public: + int32_t b; +}; + +int main(int argc, char **argv) { + Class1 c1; + Class2 c2; + //% self.expect("expr offsetof(Base, a)", substrs=["= 0"]) + //% self.expect("expr offsetof(Class1, b)", substrs=["= 4"]) + //% self.expect("expr offsetof(Class2, b)", substrs=["= 0"]) + return c1.b + c2.b; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/Makefile new file mode 100644 index 00000000000..80b3ee02c3e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES = a.cpp b.cpp + +include Makefile.rules + +a.o: a.cpp + $(CC) $(CFLAGS_NO_DEBUG) -c $< -o $@ diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/TestOperatorOverload.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/TestOperatorOverload.py new file mode 100644 index 00000000000..f541a6617e3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/TestOperatorOverload.py @@ -0,0 +1,22 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestOperatorOverload(TestBase): + mydir = TestBase.compute_mydir(__file__) + + def test_overload(self): + self.build() + (target, process, thread, + main_breakpoint) = lldbutil.run_to_source_breakpoint(self, + "break here", lldb.SBFileSpec("b.cpp")) + frame = thread.GetSelectedFrame() + value = frame.EvaluateExpression("x == nil") + self.assertTrue(str(value.GetError()) + .find("comparison between NULL and non-pointer ('Tinky' and NULL)") + != -1) + self.assertTrue(str(value.GetError()) + .find("invalid operands to binary expression ('Tinky' and") + != -1) + self.assertFalse(value.GetError().Success()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/a.cpp new file mode 100644 index 00000000000..77b2f6ace82 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/a.cpp @@ -0,0 +1,9 @@ +class Patatino { +public: + double _blah; + Patatino(int blah) : _blah(blah) {} +}; + +bool operator==(const Patatino& a, const Patatino& b) { + return a._blah < b._blah; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/b.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/b.cpp new file mode 100644 index 00000000000..c0eb29bb79f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operator-overload/b.cpp @@ -0,0 +1,10 @@ +class Tinky { +public: + int _meh; + Tinky(int meh) : _meh(meh) {} +}; + +int main(void) { + Tinky x(12); + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operators/TestCppOperators.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operators/TestCppOperators.py new file mode 100644 index 00000000000..c8308c16011 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operators/TestCppOperators.py @@ -0,0 +1,4 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operators/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operators/main.cpp new file mode 100644 index 00000000000..892d0bae42a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/operators/main.cpp @@ -0,0 +1,181 @@ +#include <cstdlib> + +int side_effect = 0; + +struct B { int dummy = 2324; }; +struct C { + void *operator new(size_t size) { C* r = ::new C; r->custom_new = true; return r; } + void *operator new[](size_t size) { C* r = static_cast<C*>(std::malloc(size)); r->custom_new = true; return r; } + void operator delete(void *p) { std::free(p); side_effect = 1; } + void operator delete[](void *p) { std::free(p); side_effect = 2; } + + bool custom_new = false; + B b; + B* operator->() { return &b; } + int operator->*(int) { return 2; } + int operator+(int) { return 44; } + int operator+=(int) { return 42; } + int operator++(int) { return 123; } + int operator++() { return 1234; } + int operator-(int) { return 34; } + int operator-=(int) { return 32; } + int operator--() { return 321; } + int operator--(int) { return 4321; } + + int operator*(int) { return 51; } + int operator*=(int) { return 52; } + int operator%(int) { return 53; } + int operator%=(int) { return 54; } + int operator/(int) { return 55; } + int operator/=(int) { return 56; } + int operator^(int) { return 57; } + int operator^=(int) { return 58; } + + int operator|(int) { return 61; } + int operator|=(int) { return 62; } + int operator||(int) { return 63; } + int operator&(int) { return 64; } + int operator&=(int) { return 65; } + int operator&&(int) { return 66; } + + int operator~() { return 71; } + int operator!() { return 72; } + int operator!=(int) { return 73; } + int operator=(int) { return 74; } + int operator==(int) { return 75; } + + int operator<(int) { return 81; } + int operator<<(int) { return 82; } + int operator<=(int) { return 83; } + int operator<<=(int) { return 84; } + int operator>(int) { return 85; } + int operator>>(int) { return 86; } + int operator>=(int) { return 87; } + int operator>>=(int) { return 88; } + + int operator,(int) { return 2012; } + int operator&() { return 2013; } + + int operator()(int) { return 91; } + int operator[](int) { return 92; } + + operator int() { return 11; } + operator long() { return 12; } + + // Make sure this doesn't collide with + // the real operator int. + int operatorint() { return 13; } + int operatornew() { return 14; } +}; + +int main(int argc, char **argv) { + C c; + int result = c->dummy; + result = c->*4; + result += c+1; + result += c+=1; + result += c++; + result += ++c; + result += c-1; + result += c-=1; + result += c--; + result += --c; + + result += c * 4; + result += c *= 4; + result += c % 4; + result += c %= 4; + result += c / 4; + result += c /= 4; + result += c ^ 4; + result += c ^= 4; + + result += c | 4; + result += c |= 4; + result += c || 4; + result += c & 4; + result += c &= 4; + result += c && 4; + + result += ~c; + result += !c; + result += c!=1; + result += c=2; + result += c==2; + + result += c<2; + result += c<<2; + result += c<=2; + result += c<<=2; + result += c>2; + result += c>>2; + result += c>=2; + result += c>>=2; + + result += (c , 2); + result += &c; + + result += c(1); + result += c[1]; + + result += static_cast<int>(c); + result += static_cast<long>(c); + result += c.operatorint(); + result += c.operatornew(); + + C *c2 = new C(); + C *c3 = new C[3]; + + //% self.expect("expr c->dummy", endstr=" 2324\n") + //% self.expect("expr c->*2", endstr=" 2\n") + //% self.expect("expr c + 44", endstr=" 44\n") + //% self.expect("expr c += 42", endstr=" 42\n") + //% self.expect("expr c++", endstr=" 123\n") + //% self.expect("expr ++c", endstr=" 1234\n") + //% self.expect("expr c - 34", endstr=" 34\n") + //% self.expect("expr c -= 32", endstr=" 32\n") + //% self.expect("expr c--", endstr=" 4321\n") + //% self.expect("expr --c", endstr=" 321\n") + //% self.expect("expr c * 3", endstr=" 51\n") + //% self.expect("expr c *= 3", endstr=" 52\n") + //% self.expect("expr c % 3", endstr=" 53\n") + //% self.expect("expr c %= 3", endstr=" 54\n") + //% self.expect("expr c / 3", endstr=" 55\n") + //% self.expect("expr c /= 3", endstr=" 56\n") + //% self.expect("expr c ^ 3", endstr=" 57\n") + //% self.expect("expr c ^= 3", endstr=" 58\n") + //% self.expect("expr c | 3", endstr=" 61\n") + //% self.expect("expr c |= 3", endstr=" 62\n") + //% self.expect("expr c || 3", endstr=" 63\n") + //% self.expect("expr c & 3", endstr=" 64\n") + //% self.expect("expr c &= 3", endstr=" 65\n") + //% self.expect("expr c && 3", endstr=" 66\n") + //% self.expect("expr ~c", endstr=" 71\n") + //% self.expect("expr !c", endstr=" 72\n") + //% self.expect("expr c!=1", endstr=" 73\n") + //% self.expect("expr c=1", endstr=" 74\n") + //% self.expect("expr c==1", endstr=" 75\n") + //% self.expect("expr c<1", endstr=" 81\n") + //% self.expect("expr c<<1", endstr=" 82\n") + //% self.expect("expr c<=1", endstr=" 83\n") + //% self.expect("expr c<<=1", endstr=" 84\n") + //% self.expect("expr c>1", endstr=" 85\n") + //% self.expect("expr c>>1", endstr=" 86\n") + //% self.expect("expr c>=1", endstr=" 87\n") + //% self.expect("expr c>>=1", endstr=" 88\n") + //% self.expect("expr c,1", endstr=" 2012\n") + //% self.expect("expr &c", endstr=" 2013\n") + //% self.expect("expr c(1)", endstr=" 91\n") + //% self.expect("expr c[1]", endstr=" 92\n") + //% self.expect("expr static_cast<int>(c)", endstr=" 11\n") + //% self.expect("expr static_cast<long>(c)", endstr=" 12\n") + //% self.expect("expr c.operatorint()", endstr=" 13\n") + //% self.expect("expr c.operatornew()", endstr=" 14\n") + //% self.expect("expr (new C)->custom_new", endstr=" true\n") + //% self.expect("expr (new struct C[1])->custom_new", endstr=" true\n") + //% self.expect("expr delete c2; side_effect", endstr=" = 1\n") + //% self.expect("expr delete[] c3; side_effect", endstr=" = 2\n") + delete c2; + delete[] c3; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/Makefile new file mode 100644 index 00000000000..1185ed0c1e8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp static-a.cpp static-b.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py new file mode 100644 index 00000000000..ad969ef3d08 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py @@ -0,0 +1,38 @@ +""" +Tests that functions with the same name are resolved correctly. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class OverloadedFunctionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.line = line_number('main.cpp', '// breakpoint') + + def test_with_run_command(self): + """Test that functions with the same name are resolved correctly""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("process launch", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect("expression -- Dump(myB)", + startstr="(int) $0 = 2") + + self.expect("expression -- Static()", + startstr="(int) $1 = 1") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/main.cpp new file mode 100644 index 00000000000..250e2cd1d96 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/main.cpp @@ -0,0 +1,43 @@ +#include <stdio.h> + +struct A { + int aa; + char ab; +}; + +struct B { + int ba; + int bb; +}; + +struct C { + int ca; + int cb; +}; + +int Dump (A &a) +{ + return 1; +} + +int Dump (B &b) +{ + return 2; +} + +int Dump (C &c) +{ + return 3; +} + +extern int CallStaticA(); +extern int CallStaticB(); + +int main() +{ + A myA; + B myB; + C myC; + + printf("%d\n", CallStaticA() + CallStaticB()); // breakpoint +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-a.cpp new file mode 100644 index 00000000000..7250fa4bed5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-a.cpp @@ -0,0 +1,9 @@ +static int Static() +{ + return 1; +} + +int CallStaticA() +{ + return Static(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-b.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-b.cpp new file mode 100644 index 00000000000..90a20f69e6d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-b.cpp @@ -0,0 +1,9 @@ +static int Static() +{ + return 1; +} + +int CallStaticB() +{ + return Static(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/TestPrintf.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/TestPrintf.py new file mode 100644 index 00000000000..10e400f4e72 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/TestPrintf.py @@ -0,0 +1,8 @@ +from lldbsuite.test import lldbinline, lldbplatformutil +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.expectedFailureAll( + bugnumber="llvm.org/PR36715", + oslist=lldbplatformutil.getDarwinOSTriples()+['windows'])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/main.cpp new file mode 100644 index 00000000000..27395eb6f41 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/printf/main.cpp @@ -0,0 +1,20 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +class PrintfContainer { +public: + int printf() { + return 0; + } +}; + +int main() { + PrintfContainer().printf(); //% self.expect("expression -- printf(\"Hello\\n\")", substrs = ['6']) + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/Makefile new file mode 100644 index 00000000000..e891bb25dd9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp + +CXXFLAGS_EXTRAS := -std=c++11 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py new file mode 100644 index 00000000000..5e31d93eb16 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py @@ -0,0 +1,53 @@ +""" +Tests that rvalue references are supported in C++ +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class RvalueReferencesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # rdar://problem/11479676 + @expectedFailureAll( + compiler="icc", + bugnumber="ICC (13.1, 14-beta) do not emit DW_TAG_rvalue_reference_type.") + def test_with_run_command(self): + """Test that rvalues are supported in the C++ expression parser""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + self.set_breakpoint(line_number('main.cpp', '// breakpoint 1')) + self.set_breakpoint(line_number('main.cpp', '// breakpoint 2')) + + self.runCmd("process launch", RUN_SUCCEEDED) + + # Note that clang as of r187480 doesn't emit DW_TAG_const_type, unlike gcc 4.8.1 + # With gcc 4.8.1, lldb reports the type as (int &&const) + self.expect("frame variable i", + startstr="(int &&", + substrs=["i = 0x", "&i = 3"]) + + self.expect("expression -- i", + startstr="(int) ", + substrs=["3"]) + + self.expect("breakpoint delete 1") + + self.runCmd("process continue") + + self.expect("expression -- foo(2)") + + self.expect("expression -- int &&j = 3; foo(j)", + error=True) + + self.expect("expression -- int &&k = 6; k", + startstr="(int) $1 = 6") + + def set_breakpoint(self, line): + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=1, loc_exact=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/main.cpp new file mode 100644 index 00000000000..6da34c73f10 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/main.cpp @@ -0,0 +1,12 @@ +#include <stdio.h> + +void foo (int &&i) +{ + printf("%d\n", i); // breakpoint 1 +} + +int main() +{ + foo(3); + return 0; // breakpoint 2 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py new file mode 100644 index 00000000000..213e7fbe902 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py @@ -0,0 +1,91 @@ +""" +Test scopes in C++. +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestCppScopes(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") + def test_all_but_c(self): + self.do_test(False) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24764") + def test_c(self): + self.do_test(True) + + def do_test(self, test_c): + self.build() + + # Get main source file + src_file = os.path.join(self.getSourceDir(), "main.cpp") + src_file_spec = lldb.SBFileSpec(src_file) + self.assertTrue(src_file_spec.IsValid(), "Main source file") + + # Get the path of the executable + exe_path = self.getBuildArtifact("a.out") + + # Load the executable + target = self.dbg.CreateTarget(exe_path) + self.assertTrue(target.IsValid(), VALID_TARGET) + + # Break on main function + main_breakpoint = target.BreakpointCreateBySourceRegex( + "// break here", src_file_spec) + self.assertTrue( + main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, + VALID_BREAKPOINT) + + # Launch the process + args = None + env = None + process = target.LaunchSimple( + args, env, self.get_process_working_directory()) + self.assertTrue(process.IsValid(), PROCESS_IS_VALID) + + # Get the thread of the process + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + + # Get current fream of the thread at the breakpoint + frame = thread.GetSelectedFrame() + + # Test result for scopes of variables + + global_variables = frame.GetVariables(True, True, True, False) + global_variables_assert = { + 'A::a': 1111, + 'B::a': 2222, + 'C::a': 3333, + '::a': 4444, + 'a': 4444 + } + + self.assertTrue( + global_variables.GetSize() == 4, + "target variable returns all variables") + for variable in global_variables: + name = variable.GetName() + self.assertTrue( + name in global_variables_assert, + "target variable returns wrong variable " + name) + + for name in global_variables_assert: + if name is "C::a" and not test_c: + continue + if name is not "C::a" and test_c: + continue + + value = frame.EvaluateExpression(name) + assert_value = global_variables_assert[name] + self.assertTrue( + value.IsValid() and value.GetValueAsSigned() == assert_value, + name + " = " + str(assert_value)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/main.cpp new file mode 100644 index 00000000000..da5d7ed529d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/scope/main.cpp @@ -0,0 +1,25 @@ +class A { +public: + static int a; + int b; +}; + +class B { +public: + static int a; + int b; +}; + +struct C { + static int a; +}; + +int A::a = 1111; +int B::a = 2222; +int C::a = 3333; +int a = 4444; + +int main() // break here +{ + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py new file mode 100644 index 00000000000..f61cd64130d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py @@ -0,0 +1,66 @@ +""" +Test that variables with signed types display correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class SignedTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.cpp' + self.line = line_number( + self.source, '// Set break point at this line.') + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489") + def test(self): + """Test that variables with signed types display correctly.""" + self.build() + + # Run in synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + lldbutil.run_break_set_by_file_and_line( + self, self.source, self.line, num_expected_locations=1, loc_exact=True) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Execute the puts(). + self.runCmd("thread step-over") + + # Test that signed types display correctly. + self.expect( + "frame variable --show-types --no-args", + VARIABLES_DISPLAYED_CORRECTLY, + patterns=[ + "\((short int|short)\) the_signed_short = 99", + "\((signed char|char)\) the_signed_char = 'c'"], + substrs=[ + "(int) the_signed_int = 99", + "(long) the_signed_long = 99", + "(long long) the_signed_long_long = 99"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/main.cpp new file mode 100644 index 00000000000..4f180bbbd13 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/signed_types/main.cpp @@ -0,0 +1,32 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int main (int argc, char const *argv[]) +{ + char the_char = 'c'; + short the_short = 'c'; + wchar_t the_wchar_t = 'c'; + int the_int = 'c'; + long the_long = 'c'; + long long the_long_long = 'c'; + + signed char the_signed_char = 'c'; + signed short the_signed_short = 'c'; + signed int the_signed_int = 'c'; + signed long the_signed_long = 'c'; + signed long long the_signed_long_long = 'c'; + puts(""); // Set break point at this line. + return the_char - the_signed_char + + the_short - the_signed_short + + the_int - the_signed_int + + the_long - the_signed_long + + the_long_long - the_signed_long_long; //// break $source:$line; c + //// var the_int + //// val -set 22 1 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py new file mode 100644 index 00000000000..4e02ebe8965 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py @@ -0,0 +1,61 @@ +""" +Tests that C++ member and static variables have correct layout and scope. +""" + + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CPPStaticMembersTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @unittest2.expectedFailure # llvm.org/pr15401 + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr21765") + def test_with_run_command(self): + """Test that member variables have the correct layout, scope and qualifiers when stopped inside and outside C++ methods""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + self.set_breakpoint(line_number('main.cpp', '// breakpoint 1')) + self.set_breakpoint(line_number('main.cpp', '// breakpoint 2')) + + self.runCmd("process launch", RUN_SUCCEEDED) + self.expect("expression my_a.access()", + startstr="(long) $0 = 10") + + self.expect("expression my_a.m_a", + startstr="(short) $1 = 1") + + # Note: SymbolFileDWARF::ParseChildMembers doesn't call + # AddFieldToRecordType, consistent with clang's AST layout. + self.expect("expression my_a.s_d", + startstr="(int) $2 = 4") + + self.expect("expression my_a.s_b", + startstr="(long) $3 = 2") + + self.expect("expression A::s_b", + startstr="(long) $4 = 2") + + # should not be available in global scope + self.expect("expression s_d", + startstr="error: use of undeclared identifier 's_d'") + + self.runCmd("process continue") + self.expect("expression m_c", + startstr="(char) $5 = \'\\x03\'") + + self.expect("expression s_b", + startstr="(long) $6 = 2") + + self.runCmd("process continue") + + def set_breakpoint(self, line): + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=1, loc_exact=False) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/main.cpp new file mode 100644 index 00000000000..ab8ae1b645f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_members/main.cpp @@ -0,0 +1,35 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +struct A +{ + short m_a; + static long s_b; + char m_c; + static int s_d; + + long access() { + return m_a + s_b + m_c + s_d; // breakpoint 2 + } +}; + +long A::s_b = 2; +int A::s_d = 4; + +int main() +{ + A my_a; + my_a.m_a = 1; + my_a.m_c = 3; + + my_a.access(); // breakpoint 1 + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py new file mode 100644 index 00000000000..4b422674134 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py @@ -0,0 +1,38 @@ +""" +Tests expressions that distinguish between static and non-static methods. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CPPStaticMethodsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.line = line_number('main.cpp', '// Break at this line') + + def test_with_run_command(self): + """Test that static methods are properly distinguished from regular methods""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("process launch", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect("expression -- A::getStaticValue()", + startstr="(int) $0 = 5") + + self.expect("expression -- my_a.getMemberValue()", + startstr="(int) $1 = 3") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/main.cpp new file mode 100644 index 00000000000..4c57e09296c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/static_methods/main.cpp @@ -0,0 +1,37 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +class A +{ +public: + static int getStaticValue(); + int getMemberValue(); + int a; +}; + +int A::getStaticValue() +{ + return 5; +} + +int A::getMemberValue() +{ + return a; +} + +int main() +{ + A my_a; + + my_a.a = 3; + + printf("%d\n", A::getStaticValue()); // Break at this line + printf("%d\n", my_a.getMemberValue()); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/std-function-step-into-callable/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/std-function-step-into-callable/Makefile new file mode 100644 index 00000000000..b016f006747 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/std-function-step-into-callable/Makefile @@ -0,0 +1,5 @@ +CXX_SOURCES := main.cpp +CXXFLAGS_EXTRAS := -std=c++11 +USE_LIBCPP := 1 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/std-function-step-into-callable/TestStdFunctionStepIntoCallable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/std-function-step-into-callable/TestStdFunctionStepIntoCallable.py new file mode 100644 index 00000000000..d667321493e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/std-function-step-into-callable/TestStdFunctionStepIntoCallable.py @@ -0,0 +1,71 @@ +""" +Test stepping into std::function +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LibCxxFunctionSteppingIntoCallableTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(["libc++"]) + def test(self): + """Test that std::function as defined by libc++ is correctly printed by LLDB""" + self.build() + + self.main_source = "main.cpp" + self.main_source_spec = lldb.SBFileSpec(self.main_source) + self.source_foo_line = line_number( + self.main_source, '// Source foo start line') + self.source_lambda_f2_line = line_number( + self.main_source, '// Source lambda used by f2 start line') + self.source_lambda_f3_line = line_number( + self.main_source, '// Source lambda used by f3 start line') + self.source_bar_operator_line = line_number( + self.main_source, '// Source Bar::operator()() start line') + self.source_bar_add_num_line = line_number( + self.main_source, '// Source Bar::add_num start line') + self.source_main_invoking_f1 = line_number( + self.main_source, '// Source main invoking f1') + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "// Set break point at this line.", self.main_source_spec) + + thread.StepInto() + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.source_main_invoking_f1 ) ; + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetFileSpec().GetFilename(), self.main_source) ; + + thread.StepInto() + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.source_foo_line ) ; + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetFileSpec().GetFilename(), self.main_source) ; + process.Continue() + + thread.StepInto() + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.source_lambda_f2_line ) ; + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetFileSpec().GetFilename(), self.main_source) ; + process.Continue() + + thread.StepInto() + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.source_lambda_f3_line ) ; + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetFileSpec().GetFilename(), self.main_source) ; + process.Continue() + + # TODO reenable this case when std::function formatter supports + # general callable object case. + #thread.StepInto() + #self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.source_bar_operator_line ) ; + #self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetFileSpec().GetFilename(), self.main_source) ; + #process.Continue() + + thread.StepInto() + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.source_bar_add_num_line ) ; + self.assertEqual( thread.GetFrameAtIndex(0).GetLineEntry().GetFileSpec().GetFilename(), self.main_source) ; + process.Continue() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/std-function-step-into-callable/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/std-function-step-into-callable/main.cpp new file mode 100644 index 00000000000..ebbb05e6d13 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/std-function-step-into-callable/main.cpp @@ -0,0 +1,40 @@ +#include <functional> + +int foo(int x, int y) { + return x + y - 1; // Source foo start line +} + +struct Bar { + int operator()() { + return 66 ; // Source Bar::operator()() start line + } + int add_num(int i) const { return i + 3 ; } // Source Bar::add_num start line + int num_ = 0 ; +} ; + +int main (int argc, char *argv[]) +{ + int acc = 42; + std::function<int (int,int)> f1 = foo; + std::function<int (int)> f2 = [acc,f1] (int x) -> int { + return x+f1(acc,x); // Source lambda used by f2 start line + }; + + auto f = [](int x, int y) { return x + y; }; // Source lambda used by f3 start line + auto g = [](int x, int y) { return x * y; } ; + std::function<int (int,int)> f3 = argc %2 ? f : g ; + + Bar bar1 ; + std::function<int ()> f4( bar1 ) ; + std::function<int (const Bar&, int)> f5 = &Bar::add_num; + std::function<int(Bar const&)> f_mem = &Bar::num_; + + return f_mem(bar1) + // Set break point at this line. + f1(acc,acc) + // Source main invoking f1 + f2(acc) + // Set break point at this line. + f3(acc+1,acc+2) + // Set break point at this line. + // TODO reenable this case when std::function formatter supports + // general callable object case. + //f4() + // Set break point at this line. + f5(bar1, 10); // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/Makefile new file mode 100644 index 00000000000..a4b03ae0aab --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp +CFLAGS := -g -O0 + +clean: OBJECTS+=$(wildcard main.d.*) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py new file mode 100644 index 00000000000..341b205389f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py @@ -0,0 +1,122 @@ +""" +Test some expressions involving STL data types. +""" + + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class STLTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.cpp' + self.line = line_number( + self.source, '// Set break point at this line.') + + @skipIf + @expectedFailureAll(bugnumber="llvm.org/PR36713") + def test(self): + """Test some expressions involving STL data types.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # The following two lines, if uncommented, will enable loggings. + #self.ci.HandleCommand("log enable -f /tmp/lldb.log lldb default", res) + # self.assertTrue(res.Succeeded()) + + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # Stop at 'std::string hello_world ("Hello World!");'. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['main.cpp:%d' % self.line, + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Now try some expressions.... + + self.runCmd( + 'expr for (int i = 0; i < hello_world.length(); ++i) { (void)printf("%c\\n", hello_world[i]); }') + + self.expect('expr associative_array.size()', + substrs=[' = 3']) + self.expect('expr associative_array.count(hello_world)', + substrs=[' = 1']) + self.expect('expr associative_array[hello_world]', + substrs=[' = 1']) + self.expect('expr associative_array["hello"]', + substrs=[' = 2']) + + @expectedFailureAll( + compiler="icc", + bugnumber="ICC (13.1, 14-beta) do not emit DW_TAG_template_type_parameter.") + @add_test_categories(['pyapi']) + def test_SBType_template_aspects(self): + """Test APIs for getting template arguments from an SBType.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Get Frame #0. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + + # Get the type for variable 'associative_array'. + associative_array = frame0.FindVariable('associative_array') + self.DebugSBValue(associative_array) + self.assertTrue(associative_array, VALID_VARIABLE) + map_type = associative_array.GetType() + self.DebugSBType(map_type) + self.assertTrue(map_type, VALID_TYPE) + num_template_args = map_type.GetNumberOfTemplateArguments() + self.assertTrue(num_template_args > 0) + + # We expect the template arguments to contain at least 'string' and + # 'int'. + expected_types = {'string': False, 'int': False} + for i in range(num_template_args): + t = map_type.GetTemplateArgumentType(i) + self.DebugSBType(t) + self.assertTrue(t, VALID_TYPE) + name = t.GetName() + if 'string' in name: + expected_types['string'] = True + elif 'int' == name: + expected_types['int'] = True + + # Check that both entries of the dictionary have 'True' as the value. + self.assertTrue(all(expected_types.values())) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py new file mode 100644 index 00000000000..49aa16ce106 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py @@ -0,0 +1,114 @@ +""" +Test the lldb disassemble command on lib stdc++. +""" + +from __future__ import print_function + + +import unittest2 +import os +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.decorators import * + +class StdCXXDisassembleTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + + @skipIfWindows + @expectedFailureNetBSD + def test_stdcxx_disasm(self): + """Do 'disassemble' on each and every 'Code' symbol entry from the std c++ lib.""" + self.build() + exe = self.getBuildArtifact("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. + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # Now let's get the target as well as the process objects. + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + + # The process should be in a 'stopped' state. + self.expect(str(process), STOPPED_DUE_TO_BREAKPOINT, exe=False, + substrs=["a.out", + "stopped"]) + + # Disassemble the functions on the call stack. + self.runCmd("thread backtrace") + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + depth = thread.GetNumFrames() + for i in range(depth - 1): + frame = thread.GetFrameAtIndex(i) + function = frame.GetFunction() + if function.GetName(): + self.runCmd("disassemble -n '%s'" % function.GetName()) + + lib_stdcxx = "FAILHORRIBLYHERE" + # Iterate through the available modules, looking for stdc++ library... + for i in range(target.GetNumModules()): + module = target.GetModuleAtIndex(i) + fs = module.GetFileSpec() + if (fs.GetFilename().startswith("libstdc++") + or fs.GetFilename().startswith("libc++")): + lib_stdcxx = str(fs) + break + + # At this point, lib_stdcxx is the full path to the stdc++ library and + # module is the corresponding SBModule. + + self.expect(lib_stdcxx, "Libraray StdC++ is located", exe=False, + substrs=["lib"]) + + self.runCmd("image dump symtab '%s'" % lib_stdcxx) + raw_output = self.res.GetOutput() + # Now, look for every 'Code' symbol and feed its load address into the + # command: 'disassemble -s load_address -e end_address', where the + # end_address is taken from the next consecutive 'Code' symbol entry's + # load address. + # + # The load address column comes after the file address column, with both + # looks like '0xhhhhhhhh', i.e., 8 hexadecimal digits. + codeRE = re.compile(r""" + \ Code\ {9} # ' Code' followed by 9 SPCs, + 0x[0-9a-f]{16} # the file address column, and + \ # a SPC, and + (0x[0-9a-f]{16}) # the load address column, and + .* # the rest. + """, re.VERBOSE) + # Maintain a start address variable; if we arrive at a consecutive Code + # entry, then the load address of the that entry is fed as the end + # address to the 'disassemble -s SA -e LA' command. + SA = None + for line in raw_output.split(os.linesep): + match = codeRE.search(line) + if match: + LA = match.group(1) + if self.TraceOn(): + print("line:", line) + print("load address:", LA) + print("SA:", SA) + if SA and LA: + if int(LA, 16) > int(SA, 16): + self.runCmd("disassemble -s %s -e %s" % (SA, LA)) + SA = LA + else: + # This entry is not a Code entry. Reset SA = None. + SA = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/cmds.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/cmds.txt new file mode 100644 index 00000000000..9c9c2e3db57 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/cmds.txt @@ -0,0 +1,3 @@ +b main.cpp:6 +continue +var diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/main.cpp new file mode 100644 index 00000000000..89895196b15 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/stl/main.cpp @@ -0,0 +1,29 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <cstdio> +#include <iostream> +#include <string> +#include <map> +int main (int argc, char const *argv[]) +{ + std::string hello_world ("Hello World!"); + std::cout << hello_world << std::endl; + std::cout << hello_world.length() << std::endl; + std::cout << hello_world[11] << std::endl; + + std::map<std::string, int> associative_array; + std::cout << "size of upon construction associative_array: " << associative_array.size() << std::endl; + associative_array[hello_world] = 1; + associative_array["hello"] = 2; + associative_array["world"] = 3; + + std::cout << "size of associative_array: " << associative_array.size() << std::endl; + printf("associative_array[\"hello\"]=%d\n", associative_array["hello"]); + + printf("before returning....\n"); // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/symbols/TestSymbols.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/symbols/TestSymbols.py new file mode 100644 index 00000000000..af362f5be5d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/symbols/TestSymbols.py @@ -0,0 +1,7 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.expectedFailureAll( + oslist=["windows"], bugnumber="llvm.org/pr24764")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/symbols/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/symbols/main.cpp new file mode 100644 index 00000000000..cbd3ab253d6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/symbols/main.cpp @@ -0,0 +1,39 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +void *D = 0; + +class D { + static int i; +}; + +int D::i = 3; + +namespace errno { + int j = 4; +}; + +int twice(int n) +{ + return n * 2; //% self.expect("expression -- D::i", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["int", "3"]) + //% self.expect("expression -- D", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["void"]) + //% self.expect("expression -- errno::j", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["int", "4"]) +} + +const char getAChar() +{ + const char D[] = "Hello world"; + return D[0]; //% self.expect("expression -- D::i", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["int", "3"]) + //% self.expect("expression -- D", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["char", "Hello"]) +} + +int main (int argc, char const *argv[]) +{ + int six = twice(3); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template-function/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template-function/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template-function/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template-function/TestTemplateFunctions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template-function/TestTemplateFunctions.py new file mode 100644 index 00000000000..6c9a0ac35f4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template-function/TestTemplateFunctions.py @@ -0,0 +1,32 @@ +""" +Test that we can call C++ template fucntions. +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TemplateFunctionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def do_test_template_function(self, add_cast): + self.build() + (_, _, thread, _) = lldbutil.run_to_name_breakpoint(self, "main") + frame = thread.GetSelectedFrame() + expr = "foo(42)" + if add_cast: + expr = "(int)" + expr + expr_result = frame.EvaluateExpression(expr) + self.assertTrue(expr_result.IsValid()) + self.assertEqual(expr_result.GetValue(), "42") + + @skipIfWindows + def test_template_function_with_cast(self): + self.do_test_template_function(True) + + @skipIfWindows + @expectedFailureAll(debug_info=["dwarf", "gmodules", "dwo"]) + def test_template_function_without_cast(self): + self.do_test_template_function(False) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template-function/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template-function/main.cpp new file mode 100644 index 00000000000..035e6450cd3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template-function/main.cpp @@ -0,0 +1,16 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +template<typename T> +int foo(T t1) { + return int(t1); +} + +int main() { + return foo(42); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template/TestTemplateArgs.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template/TestTemplateArgs.py new file mode 100644 index 00000000000..08132702b8d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template/TestTemplateArgs.py @@ -0,0 +1,158 @@ +""" +Test that C++ template classes that have integer parameters work correctly. + +We must reconstruct the types correctly so the template types are correct +and display correctly, and also make sure the expression parser works and +is able the find all needed functions when evaluating expressions +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TemplateArgsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def prepareProcess(self): + self.build() + + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set breakpoints inside and outside methods that take pointers to the + # containing struct. + line = line_number('main.cpp', '// Breakpoint 1') + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=1, loc_exact=True) + + arguments = None + environment = None + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + arguments, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Get the thread of the process + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + + # Get frame for current thread + return thread.GetSelectedFrame() + + def test_integer_args(self): + frame = self.prepareProcess() + + testpos = frame.FindVariable('testpos') + self.assertTrue( + testpos.IsValid(), + 'make sure we find a local variabble named "testpos"') + self.assertTrue(testpos.GetType().GetName() == 'TestObj<1>') + + expr_result = frame.EvaluateExpression("testpos.getArg()") + self.assertTrue( + expr_result.IsValid(), + 'got a valid expression result from expression "testpos.getArg()"') + self.assertTrue(expr_result.GetValue() == "1", "testpos.getArg() == 1") + self.assertTrue( + expr_result.GetType().GetName() == "int", + 'expr_result.GetType().GetName() == "int"') + + testneg = frame.FindVariable('testneg') + self.assertTrue( + testneg.IsValid(), + 'make sure we find a local variabble named "testneg"') + self.assertTrue(testneg.GetType().GetName() == 'TestObj<-1>') + + expr_result = frame.EvaluateExpression("testneg.getArg()") + self.assertTrue( + expr_result.IsValid(), + 'got a valid expression result from expression "testneg.getArg()"') + self.assertTrue( + expr_result.GetValue() == "-1", + "testneg.getArg() == -1") + self.assertTrue( + expr_result.GetType().GetName() == "int", + 'expr_result.GetType().GetName() == "int"') + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24489") + def test_template_template_args(self): + frame = self.prepareProcess() + + c1 = frame.FindVariable('c1') + self.assertTrue( + c1.IsValid(), + 'make sure we find a local variabble named "c1"') + self.assertTrue(c1.GetType().GetName() == 'C<float, T1>') + f1 = c1.GetChildMemberWithName("V").GetChildAtIndex(0).GetChildMemberWithName("f") + self.assertTrue(f1.GetType().GetName() == 'float') + self.assertTrue(f1.GetValue() == '1.5') + + c2 = frame.FindVariable('c2') + self.assertTrue( + c2.IsValid(), + 'make sure we find a local variabble named "c2"') + self.assertTrue(c2.GetType().GetName() == 'C<double, T1, T2>') + f2 = c2.GetChildMemberWithName("V").GetChildAtIndex(0).GetChildMemberWithName("f") + self.assertTrue(f2.GetType().GetName() == 'double') + self.assertTrue(f2.GetValue() == '1.5') + f3 = c2.GetChildMemberWithName("V").GetChildAtIndex(1).GetChildMemberWithName("f") + self.assertTrue(f3.GetType().GetName() == 'double') + self.assertTrue(f3.GetValue() == '2.5') + f4 = c2.GetChildMemberWithName("V").GetChildAtIndex(1).GetChildMemberWithName("i") + self.assertTrue(f4.GetType().GetName() == 'int') + self.assertTrue(f4.GetValue() == '42') + + # Gcc does not generate the necessary DWARF attribute for enum template + # parameters. + @expectedFailureAll(bugnumber="llvm.org/pr28354", compiler="gcc") + @skipIf(dwarf_version=['<', '4']) + def test_enum_args(self): + frame = self.prepareProcess() + + # Make sure "member" can be displayed and also used in an expression + # correctly + member = frame.FindVariable('member') + self.assertTrue( + member.IsValid(), + 'make sure we find a local variabble named "member"') + self.assertTrue(member.GetType().GetName() == + 'EnumTemplate<EnumType::Member>') + + expr_result = frame.EvaluateExpression("member.getMember()") + self.assertTrue( + expr_result.IsValid(), + 'got a valid expression result from expression "member.getMember()"') + self.assertTrue( + expr_result.GetValue() == "123", + "member.getMember() == 123") + self.assertTrue( + expr_result.GetType().GetName() == "int", + 'expr_result.GetType().GetName() == "int"') + + # Make sure "subclass" can be displayed and also used in an expression + # correctly + subclass = frame.FindVariable('subclass') + self.assertTrue( + subclass.IsValid(), + 'make sure we find a local variabble named "subclass"') + self.assertTrue(subclass.GetType().GetName() == + 'EnumTemplate<EnumType::Subclass>') + + expr_result = frame.EvaluateExpression("subclass.getMember()") + self.assertTrue( + expr_result.IsValid(), + 'got a valid expression result from expression "subclass.getMember()"') + self.assertTrue( + expr_result.GetValue() == "246", + "subclass.getMember() == 246") + self.assertTrue( + expr_result.GetType().GetName() == "int", + 'expr_result.GetType().GetName() == "int"') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template/main.cpp new file mode 100644 index 00000000000..445a34fe067 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/template/main.cpp @@ -0,0 +1,78 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <tuple> + +template <int Arg> +class TestObj +{ +public: + int getArg() + { + return Arg; + } +}; + +//---------------------------------------------------------------------- +// Define a template class that we can specialize with an enumeration +//---------------------------------------------------------------------- +enum class EnumType +{ + Member, + Subclass +}; + +template <EnumType Arg> class EnumTemplate; + +//---------------------------------------------------------------------- +// Specialization for use when "Arg" is "EnumType::Member" +//---------------------------------------------------------------------- +template <> +class EnumTemplate<EnumType::Member> +{ +public: + EnumTemplate(int m) : + m_member(m) + { + } + + int getMember() const + { + return m_member; + } + +protected: + int m_member; +}; + +//---------------------------------------------------------------------- +// Specialization for use when "Arg" is "EnumType::Subclass" +//---------------------------------------------------------------------- +template <> +class EnumTemplate<EnumType::Subclass> : + public EnumTemplate<EnumType::Member> +{ +public: + EnumTemplate(int m) : EnumTemplate<EnumType::Member>(m) + { + } +}; + +template <typename FLOAT> struct T1 { FLOAT f = 1.5; }; +template <typename FLOAT> struct T2 { FLOAT f = 2.5; int i = 42; }; +template <typename FLOAT, template <typename> class ...Args> class C { std::tuple<Args<FLOAT>...> V; }; + +int main(int argc, char **argv) +{ + TestObj<1> testpos; + TestObj<-1> testneg; + EnumTemplate<EnumType::Member> member(123); + EnumTemplate<EnumType::Subclass> subclass(123*2); + C<float, T1> c1; + C<double, T1, T2> c2; + return testpos.getArg() - testneg.getArg() + member.getMember()*2 - subclass.getMember(); // Breakpoint 1 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/this/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/this/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/this/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py new file mode 100644 index 00000000000..ab95627729d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py @@ -0,0 +1,61 @@ +""" +Tests that C++ member and static variables are available where they should be. +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CPPThisTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # rdar://problem/9962849 + @expectedFailureAll( + compiler="gcc", + bugnumber="llvm.org/pr15439 The 'this' pointer isn't available during expression evaluation when stopped in an inlined member function") + @expectedFailureAll( + compiler="icc", + bugnumber="ICC doesn't emit correct DWARF inline debug info for inlined member functions.") + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24489: Name lookup not working correctly on Windows") + @expectedFailureNetBSD + def test_with_run_command(self): + """Test that the appropriate member variables are available when stopped in C++ static, inline, and const methods""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + self.set_breakpoint(line_number('main.cpp', '// breakpoint 1')) + self.set_breakpoint(line_number('main.cpp', '// breakpoint 2')) + self.set_breakpoint(line_number('main.cpp', '// breakpoint 3')) + self.set_breakpoint(line_number('main.cpp', '// breakpoint 4')) + + self.runCmd("process launch", RUN_SUCCEEDED) + + self.expect("expression -- m_a = 2", + startstr="(int) $0 = 2") + + self.runCmd("process continue") + + # This would be disallowed if we enforced const. But we don't. + self.expect("expression -- m_a = 2", + startstr="(int) $1 = 2") + + self.expect("expression -- (int)getpid(); m_a", + startstr="(int) $2 = 2") + + self.runCmd("process continue") + + self.expect("expression -- s_a", + startstr="(int) $3 = 5") + + self.runCmd("process continue") + + self.expect("expression -- m_a", + startstr="(int) $4 = 2") + + def set_breakpoint(self, line): + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", line, num_expected_locations=1, loc_exact=False) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/this/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/this/main.cpp new file mode 100644 index 00000000000..4026de0222f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/this/main.cpp @@ -0,0 +1,52 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <stdio.h> + +template <class T> class A +{ +public: + void accessMember(T a); + T accessMemberConst() const; + static int accessStaticMember(); + + void accessMemberInline(T a) __attribute__ ((always_inline)) + { + m_a = a; // breakpoint 4 + } + + T m_a; + static int s_a; +}; + +template <class T> int A<T>::s_a = 5; + +template <class T> void A<T>::accessMember(T a) +{ + m_a = a; // breakpoint 1 +} + +template <class T> T A<T>::accessMemberConst() const +{ + return m_a; // breakpoint 2 +} + +template <class T> int A<T>::accessStaticMember() +{ + return s_a; // breakpoint 3 +} + +int main() +{ + A<int> my_a; + + my_a.accessMember(3); + my_a.accessMemberConst(); + A<int>::accessStaticMember(); + my_a.accessMemberInline(5); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/thread_local/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/thread_local/Makefile new file mode 100644 index 00000000000..3d0b98f13f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/thread_local/Makefile @@ -0,0 +1,2 @@ +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/thread_local/TestThreadLocal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/thread_local/TestThreadLocal.py new file mode 100644 index 00000000000..5152c0010d1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/thread_local/TestThreadLocal.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest(__file__, globals(), + lldbinline.expectedFailureAll(oslist=[ + "windows", "linux", "netbsd"])) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/thread_local/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/thread_local/main.cpp new file mode 100644 index 00000000000..1855b7c5f34 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/thread_local/main.cpp @@ -0,0 +1,17 @@ +int storage = 45; +thread_local int tl_global_int = 123; +thread_local int *tl_global_ptr = &storage; + +int main(int argc, char **argv) { + //% self.expect("expr tl_local_int", error=True, substrs=["couldn't get the value of variable tl_local_int"]) + //% self.expect("expr *tl_local_ptr", error=True, substrs=["couldn't get the value of variable tl_local_ptr"]) + thread_local int tl_local_int = 321; + thread_local int *tl_local_ptr = nullptr; + tl_local_ptr = &tl_local_int; + tl_local_int++; + //% self.expect("expr tl_local_int + 1", substrs=["int", "= 323"]) + //% self.expect("expr *tl_local_ptr + 2", substrs=["int", "= 324"]) + //% self.expect("expr tl_global_int", substrs=["int", "= 123"]) + //% self.expect("expr *tl_global_ptr", substrs=["int", "= 45"]) + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/trivial_abi/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/trivial_abi/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/trivial_abi/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/trivial_abi/TestTrivialABI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/trivial_abi/TestTrivialABI.py new file mode 100644 index 00000000000..2a8a78a45ff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/trivial_abi/TestTrivialABI.py @@ -0,0 +1,72 @@ +""" +Test that we work properly with classes with the trivial_abi attribute +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestTrivialABI(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipUnlessSupportedTypeAttribute("trivial_abi") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr37995") + @expectedFailureAll(archs=["aarch64"], oslist=["linux"], + bugnumber="llvm.org/pr44161") + def test_call_trivial(self): + """Test that we can print a variable & call a function with a trivial ABI class.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.cpp") + self.expr_test(True) + + @skipUnlessSupportedTypeAttribute("trivial_abi") + # fixed for SysV-x86_64 ABI, but not Windows-x86_64 + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr36870") + @expectedFailureAll(archs=["aarch64"], oslist=["linux"], + bugnumber="llvm.org/pr44161") + @expectedFailureAll(archs=["arm64", "arm64e"], bugnumber="<rdar://problem/57844240>") + def test_call_nontrivial(self): + """Test that we can print a variable & call a function on the same class w/o the trivial ABI marker.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.cpp") + self.expr_test(False) + + def check_value(self, test_var, ivar_value): + self.assertTrue(test_var.GetError().Success(), "Invalid valobj: %s"%(test_var.GetError().GetCString())) + ivar = test_var.GetChildMemberWithName("ivar") + self.assertTrue(test_var.GetError().Success(), "Failed to fetch ivar") + self.assertEqual(ivar_value, ivar.GetValueAsSigned(), "Got the right value for ivar") + + def check_frame(self, thread): + frame = thread.frames[0] + inVal_var = frame.FindVariable("inVal") + self.check_value(inVal_var, 10) + + options = lldb.SBExpressionOptions() + inVal_expr = frame.EvaluateExpression("inVal", options) + self.check_value(inVal_expr, 10) + + thread.StepOut() + outVal_ret = thread.GetStopReturnValue() + self.check_value(outVal_ret, 30) + + def expr_test(self, trivial): + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", self.main_source_file) + + # Stop in a function that takes a trivial value, and try both frame var & expr to get its value: + if trivial: + self.check_frame(thread) + return + + # Now continue to the same thing without the trivial_abi and see if we get that right: + threads = lldbutil.continue_to_breakpoint(process, bkpt) + self.assertEqual(len(threads), 1, "Hit my breakpoint the second time.") + + self.check_frame(threads[0]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/trivial_abi/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/trivial_abi/main.cpp new file mode 100644 index 00000000000..b1f50159692 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/trivial_abi/main.cpp @@ -0,0 +1,35 @@ +struct __attribute__((trivial_abi)) S_Trivial { + ~S_Trivial() {} + int ivar = 10; +}; + +S_Trivial takeTrivial(S_Trivial inVal) +{ + S_Trivial ret_val = inVal; + ret_val.ivar = 30; + return ret_val; // Set a breakpoint here +} + +struct S_NotTrivial { + ~S_NotTrivial() {} + int ivar = 10; +}; + +S_NotTrivial takeNotTrivial(S_NotTrivial inVal) +{ + S_NotTrivial ret_val = inVal; + ret_val.ivar = 30; + return ret_val; // Set a breakpoint here +} + +int +main() +{ + S_Trivial inVal, outVal; + outVal = takeTrivial(inVal); + + S_NotTrivial inNotVal, outNotVal; + outNotVal = takeNotTrivial(inNotVal); + + return 0; // Set another for return value +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/type_lookup/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/type_lookup/Makefile new file mode 100644 index 00000000000..3d0b98f13f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/type_lookup/Makefile @@ -0,0 +1,2 @@ +CXX_SOURCES := main.cpp +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/type_lookup/TestCppTypeLookup.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/type_lookup/TestCppTypeLookup.py new file mode 100644 index 00000000000..45be73118f8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/type_lookup/TestCppTypeLookup.py @@ -0,0 +1,93 @@ +""" +Test that we can lookup types correctly in the expression parser +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * +from lldbsuite.test import decorators + +class TestCppTypeLookup(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def check_value(self, value, ivar_name, ivar_value): + self.assertTrue(value.GetError().Success(), + "Invalid valobj: %s" % ( + value.GetError().GetCString())) + ivar = value.GetChildMemberWithName(ivar_name) + self.assertTrue(ivar.GetError().Success(), + "Failed to fetch ivar named '%s'" % (ivar_name)) + self.assertEqual(ivar_value, + ivar.GetValueAsSigned(), + "Got the right value for ivar") + + def test_namespace_only(self): + """ + Test that we fail to lookup a struct type that exists only in a + namespace. + """ + self.build() + self.main_source_file = lldb.SBFileSpec("main.cpp") + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set a breakpoint here", self.main_source_file) + + # Get frame for current thread + frame = thread.GetSelectedFrame() + + # We are testing LLDB's type lookup machinery, but if we inject local + # variables, the types for those will be found because they have been + # imported through the variable, not because the type lookup worked. + self.runCmd("settings set target.experimental.inject-local-vars false") + + # Make sure we don't accidentally accept structures that exist only + # in namespaces when evaluating expressions with top level types. + # Prior to the revision that added this test, we would accidentally + # accept types from namespaces, so this will ensure we don't regress + # to that behavior again + expr_result = frame.EvaluateExpression("*((namespace_only *)&i)") + self.assertTrue(expr_result.GetError().Fail(), + "'namespace_only' exists in namespace only") + + # Make sure we can find the correct type in a namespace "nsp_a" + expr_result = frame.EvaluateExpression("*((nsp_a::namespace_only *)&i)") + self.check_value(expr_result, "a", 123) + # Make sure we can find the correct type in a namespace "nsp_b" + expr_result = frame.EvaluateExpression("*((nsp_b::namespace_only *)&i)") + self.check_value(expr_result, "b", 123) + + # Make sure we can find the correct type in the root namespace + expr_result = frame.EvaluateExpression("*((namespace_and_file *)&i)") + self.check_value(expr_result, "ff", 123) + # Make sure we can find the correct type in a namespace "nsp_a" + expr_result = frame.EvaluateExpression( + "*((nsp_a::namespace_and_file *)&i)") + self.check_value(expr_result, "aa", 123) + # Make sure we can find the correct type in a namespace "nsp_b" + expr_result = frame.EvaluateExpression( + "*((nsp_b::namespace_and_file *)&i)") + self.check_value(expr_result, "bb", 123) + + # Make sure we don't accidentally accept structures that exist only + # in namespaces when evaluating expressions with top level types. + # Prior to the revision that added this test, we would accidentally + # accept types from namespaces, so this will ensure we don't regress + # to that behavior again + expr_result = frame.EvaluateExpression("*((in_contains_type *)&i)") + self.assertTrue(expr_result.GetError().Fail(), + "'in_contains_type' exists in struct only") + + # Make sure we can find the correct type in the root namespace + expr_result = frame.EvaluateExpression( + "*((contains_type::in_contains_type *)&i)") + self.check_value(expr_result, "fff", 123) + # Make sure we can find the correct type in a namespace "nsp_a" + expr_result = frame.EvaluateExpression( + "*((nsp_a::contains_type::in_contains_type *)&i)") + self.check_value(expr_result, "aaa", 123) + # Make sure we can find the correct type in a namespace "nsp_b" + expr_result = frame.EvaluateExpression( + "*((nsp_b::contains_type::in_contains_type *)&i)") + self.check_value(expr_result, "bbb", 123) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/type_lookup/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/type_lookup/main.cpp new file mode 100644 index 00000000000..f2803e36152 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/type_lookup/main.cpp @@ -0,0 +1,66 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// In this test, we define struct that exist might exist at the different +// levels in the code and test that we can properly locate these types with +// a varienty of different expressions. + +namespace nsp_a { + struct namespace_only { + int a; + }; + struct namespace_and_file { + int aa; + }; + struct contains_type { + struct in_contains_type { + int aaa; + }; + }; +}; +namespace nsp_b { + struct namespace_only { + int b; + }; + struct namespace_and_file { + int bb; + }; + struct contains_type { + struct in_contains_type { + int bbb; + }; + }; +}; + +struct namespace_and_file { + int ff; +}; + +struct contains_type { + struct in_contains_type { + int fff; + }; +}; + + +int main (int argc, char const *argv[]) { + nsp_a::namespace_only a_namespace_only = { 1 }; + nsp_a::namespace_and_file a_namespace_and_file = { 2 }; + nsp_a::contains_type::in_contains_type a_in_contains_type = { 3 }; + nsp_b::namespace_only b_namespace_only = { 11 }; + nsp_b::namespace_and_file b_namespace_and_file = { 22 }; + nsp_b::contains_type::in_contains_type b_in_contains_type = { 33 }; + namespace_and_file file_namespace_and_file = { 44 }; + contains_type::in_contains_type file_in_contains_type = { 55 }; + int i = 123; // Provide an integer that can be used for casting + // Take address of "i" to ensure it is in memory + if (&i == &argc) { + i = -1; + } + return i == -1; // Set a breakpoint here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/Makefile new file mode 100644 index 00000000000..bf443d855ce --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp +CFLAGS := -g -O0 -std=c++11 + +clean: OBJECTS+=$(wildcard main.d.*) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/TestUnicodeLiterals.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/TestUnicodeLiterals.py new file mode 100644 index 00000000000..c1bd892447a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/TestUnicodeLiterals.py @@ -0,0 +1,83 @@ +# coding=utf8 +""" +Test that the expression parser returns proper Unicode strings. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +# this test case fails because of rdar://12991846 +# the expression parser does not deal correctly with Unicode expressions +# e.g. +#(lldb) expr L"Hello" +#(const wchar_t [6]) $0 = { +# [0] = \0\0\0\0 +# [1] = \0\0\0\0 +# [2] = \0\0\0\0 +# [3] = \0\0\0\0 +# [4] = H\0\0\0 +# [5] = e\0\0\0 +#} + + +class UnicodeLiteralsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_expr1(self): + """Test that the expression parser returns proper Unicode strings.""" + self.build() + self.rdar12991846(expr=1) + + def test_expr2(self): + """Test that the expression parser returns proper Unicode strings.""" + self.build() + self.rdar12991846(expr=2) + + def test_expr3(self): + """Test that the expression parser returns proper Unicode strings.""" + self.build() + self.rdar12991846(expr=3) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.cpp. + self.source = 'main.cpp' + self.line = line_number( + self.source, '// Set break point at this line.') + + def rdar12991846(self, expr=None): + """Test that the expression parser returns proper Unicode strings.""" + if self.getArchitecture() in ['i386']: + self.skipTest( + "Skipping because this test is known to crash on i386") + + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Break on the struct declration statement in main.cpp. + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.Launch() failed") + + if expr == 1: + self.expect('expression L"hello"', substrs=['hello']) + + if expr == 2: + self.expect('expression u"hello"', substrs=['hello']) + + if expr == 3: + self.expect('expression U"hello"', substrs=['hello']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/main.cpp new file mode 100644 index 00000000000..a98fb44e5f4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unicode-literals/main.cpp @@ -0,0 +1,20 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + + +int main (int argc, char const *argv[]) +{ + auto cs16 = u"hello world ྒྙྐ"; + auto cs32 = U"hello world ྒྙྐ"; + char16_t *s16 = (char16_t *)u"ﺸﺵۻ"; + char32_t *s32 = (char32_t *)U"ЕЙРГЖО"; + s32 = nullptr; // Set break point at this line. + s32 = (char32_t *)U"෴"; + s16 = (char16_t *)u"色ハ匂ヘト散リヌルヲ"; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py new file mode 100644 index 00000000000..78121c14970 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py @@ -0,0 +1,65 @@ +""" +Test that template instaniations of std::vector<long> and <short> in the same module have the correct types. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class UniqueTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number inside main.cpp. + self.line = line_number( + "main.cpp", + "// Set breakpoint here to verify that std::vector 'longs' and 'shorts' have unique types.") + + def test(self): + """Test for unique types of std::vector<long> and std::vector<short>.""" + self.build() + + compiler = self.getCompiler() + compiler_basename = os.path.basename(compiler) + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Do a "frame variable --show-types longs" and verify "long" is in each + # line of output. + self.runCmd("frame variable --show-types longs") + output = self.res.GetOutput() + for x in [line.strip() for line in output.split(os.linesep)]: + # Skip empty line, closing brace, and messages about more variables + # than can be displayed. + if not x or x == '}' or x == '...' or "Some of your variables have more members than the debugger will show by default" in x: + continue + self.expect(x, "Expect type 'long'", exe=False, + substrs=['long']) + + # Do a "frame variable --show-types shorts" and verify "short" is in + # each line of output. + self.runCmd("frame variable --show-types shorts") + output = self.res.GetOutput() + for x in [line.strip() for line in output.split(os.linesep)]: + # Skip empty line, closing brace, and messages about more variables + # than can be displayed. + if not x or x == '}' or x == '...' or "Some of your variables have more members than the debugger will show by default" in x: + continue + self.expect(x, "Expect type 'short'", exe=False, + substrs=['short']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/main.cpp new file mode 100644 index 00000000000..839fd93f764 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unique-types/main.cpp @@ -0,0 +1,23 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <vector> + +#include <stdio.h> +#include <stdint.h> + +int main (int argc, char const *argv[], char const *envp[]) +{ + std::vector<long> longs; + std::vector<short> shorts; + for (int i=0; i<12; i++) + { + longs.push_back(i); + shorts.push_back(i); + } + return 0; // Set breakpoint here to verify that std::vector 'longs' and 'shorts' have unique types. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py new file mode 100644 index 00000000000..ca754f470da --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py @@ -0,0 +1,60 @@ +""" +Test that variables with unsigned types display correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class UnsignedTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.cpp', '// Set break point at this line.') + + def test(self): + """Test that variables with unsigned types display correctly.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # GCC puts a breakpoint on the last line of a multi-line expression, so + # if GCC is the target compiler, we cannot rely on an exact line match. + need_exact = "gcc" not in self.getCompiler() + # Break on line 19 in main() after the variables are assigned values. + lldbutil.run_break_set_by_file_and_line( + self, + "main.cpp", + self.line, + num_expected_locations=-1, + loc_exact=need_exact) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # Test that unsigned types display correctly. + self.expect( + "frame variable --show-types --no-args", + VARIABLES_DISPLAYED_CORRECTLY, + patterns=["\((short unsigned int|unsigned short)\) the_unsigned_short = 99"], + substrs=[ + "(unsigned char) the_unsigned_char = 'c'", + "(unsigned int) the_unsigned_int = 99", + "(unsigned long) the_unsigned_long = 99", + "(unsigned long long) the_unsigned_long_long = 99", + "(uint32_t) the_uint32 = 99"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/main.cpp new file mode 100644 index 00000000000..8d0a0c386e3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/main.cpp @@ -0,0 +1,21 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +int main (int argc, char const *argv[]) +{ + typedef unsigned int uint32_t; + unsigned char the_unsigned_char = 'c'; + unsigned short the_unsigned_short = 'c'; + unsigned int the_unsigned_int = 'c'; + unsigned long the_unsigned_long = 'c'; + unsigned long long the_unsigned_long_long = 'c'; + uint32_t the_uint32 = 'c'; + + 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; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual-overload/TestVirtualOverload.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual-overload/TestVirtualOverload.py new file mode 100644 index 00000000000..1311a149326 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual-overload/TestVirtualOverload.py @@ -0,0 +1,3 @@ +from lldbsuite.test import lldbinline + +lldbinline.MakeInlineTest(__file__, globals()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual-overload/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual-overload/main.cpp new file mode 100644 index 00000000000..79c482352f9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual-overload/main.cpp @@ -0,0 +1,17 @@ +// Test that lldb doesn't get confused by an overload of a virtual +// function of the same name. +struct Base { + virtual void f(int i) {} + virtual ~Base() {} +}; + +struct Derived : Base { + virtual void f(int i, int j) {} +}; + +int main(int argc, char **argv) { + Derived obj; + obj.f(1, 2); //% self.expect("fr var", "not crashing", substrs = ["obj"]) + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py new file mode 100644 index 00000000000..22fe96b96d2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py @@ -0,0 +1,101 @@ +""" +Test C++ virtual function and virtual inheritance. +""" + +import os +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +def Msg(expr, val): + return "'expression %s' matches the output (from compiled code): %s" % ( + expr, val) + + +class CppVirtualMadness(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # This is the pattern by design to match the "my_expr = 'value'" output from + # printf() stmts (see main.cpp). + pattern = re.compile("^([^=]*) = '([^=]*)'$") + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.cpp. + self.source = 'main.cpp' + self.line = line_number(self.source, '// Set first breakpoint here.') + + @expectedFailureAll( + compiler="icc", + bugnumber="llvm.org/pr16808 lldb does not call the correct virtual function with icc.") + @skipIfWindows # This test will hang on windows llvm.org/pr21753 + @expectedFlakeyNetBSD + def test_virtual_madness(self): + """Test that expression works correctly with virtual inheritance as well as virtual function.""" + self.build() + + # Bring the program to the point where we can issue a series of + # 'expression' command to compare against the golden output. + self.dbg.SetAsync(False) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + + # First, capture the golden output from the program itself. + golden = thread.GetFrameAtIndex(0).FindVariable("golden") + self.assertTrue( + golden.IsValid(), + "Encountered an error reading the process's golden variable") + error = lldb.SBError() + golden_str = process.ReadCStringFromMemory( + golden.AddressOf().GetValueAsUnsigned(), 4096, error) + self.assertTrue(error.Success()) + self.assertTrue("c_as_C" in golden_str) + + # This golden list contains a list of "my_expr = 'value' pairs extracted + # from the golden output. + gl = [] + + # Scan the golden output line by line, looking for the pattern: + # + # my_expr = 'value' + # + for line in golden_str.split(os.linesep): + match = self.pattern.search(line) + if match: + my_expr, val = match.group(1), match.group(2) + gl.append((my_expr, val)) + #print("golden list:", gl) + + # Now iterate through the golden list, comparing against the output from + # 'expression var'. + for my_expr, val in gl: + + self.runCmd("expression %s" % my_expr) + output = self.res.GetOutput() + + # The expression output must match the oracle. + self.expect(output, Msg(my_expr, val), exe=False, + substrs=[val]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/main.cpp new file mode 100644 index 00000000000..0adf4157731 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/virtual/main.cpp @@ -0,0 +1,116 @@ +#include <stdio.h> +#include <stdint.h> + +class A +{ +public: + A () : m_pad ('c') {} + + virtual ~A () {} + + virtual const char * a() + { + return __PRETTY_FUNCTION__; + } + + virtual const char * b() + { + return __PRETTY_FUNCTION__; + } + + virtual const char * c() + { + return __PRETTY_FUNCTION__; + } +protected: + char m_pad; +}; + +class AA +{ +public: + AA () : m_pad('A') {} + virtual ~AA () {} + + virtual const char * aa() + { + return __PRETTY_FUNCTION__; + } + +protected: + char m_pad; +}; + +class B : virtual public A, public AA +{ +public: + B () : m_pad ('c') {} + + virtual ~B () {} + + virtual const char * a() + { + return __PRETTY_FUNCTION__; + } + + virtual const char * b() + { + return __PRETTY_FUNCTION__; + } +protected: + char m_pad; +}; + +class C : public B, virtual public A +{ +public: + C () : m_pad ('c') {} + + virtual ~C () {} + + virtual const char * a() + { + return __PRETTY_FUNCTION__; + } +protected: + char m_pad; +}; + +int main (int argc, char const *argv[], char const *envp[]) +{ + A *a_as_A = new A(); + B *b_as_B = new B(); + A *b_as_A = b_as_B; + C *c_as_C = new C(); + A *c_as_A = c_as_C; + + char golden[4096]; + char *p = golden; + char *end = p + sizeof golden; + p += snprintf(p, end-p, "a_as_A->a() = '%s'\n", a_as_A->a()); + p += snprintf(p, end-p, "a_as_A->b() = '%s'\n", a_as_A->b()); + p += snprintf(p, end-p, "a_as_A->c() = '%s'\n", a_as_A->c()); + p += snprintf(p, end-p, "b_as_A->a() = '%s'\n", b_as_A->a()); + p += snprintf(p, end-p, "b_as_A->b() = '%s'\n", b_as_A->b()); + p += snprintf(p, end-p, "b_as_A->c() = '%s'\n", b_as_A->c()); + p += snprintf(p, end-p, "b_as_B->aa() = '%s'\n", b_as_B->aa()); + p += snprintf(p, end-p, "c_as_A->a() = '%s'\n", c_as_A->a()); + p += snprintf(p, end-p, "c_as_A->b() = '%s'\n", c_as_A->b()); + p += snprintf(p, end-p, "c_as_A->c() = '%s'\n", c_as_A->c()); + p += snprintf(p, end-p, "c_as_C->aa() = '%s'\n", c_as_C->aa()); + puts("");// Set first breakpoint here. + // then evaluate: + // expression a_as_A->a() + // expression a_as_A->b() + // expression a_as_A->c() + // expression b_as_A->a() + // expression b_as_A->b() + // expression b_as_A->c() + // expression b_as_B->aa() + // expression c_as_A->a() + // expression c_as_A->b() + // expression c_as_A->c() + // expression c_as_C->aa() + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/.categories new file mode 100644 index 00000000000..fe1da0247c6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/.categories @@ -0,0 +1 @@ +dataformatters diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/Makefile new file mode 100644 index 00000000000..a4b03ae0aab --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp +CFLAGS := -g -O0 + +clean: OBJECTS+=$(wildcard main.d.*) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py new file mode 100644 index 00000000000..b59d71e8e8e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py @@ -0,0 +1,77 @@ +# coding=utf8 +""" +Test that C++ supports wchar_t correctly. +""" + + + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +class CxxWCharTTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break for main.cpp. + self.source = 'main.cpp' + self.line = line_number( + self.source, '// Set break point at this line.') + + def test(self): + """Test that C++ supports wchar_t correctly.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Break on the struct declration statement in main.cpp. + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.Launch() failed") + + # Check that we correctly report templates on wchar_t + self.expect("frame variable foo_y", + substrs=['(Foo<wchar_t>) foo_y = ']) + + # Check that we correctly report templates on int + self.expect("frame variable foo_x", + substrs=['(Foo<int>) foo_x = ']) + + # Check that we correctly report wchar_t + self.expect("frame variable foo_y.object", + substrs=['(wchar_t) foo_y.object = ']) + + # Check that we correctly report int + self.expect("frame variable foo_x.object", + substrs=['(int) foo_x.object = ']) + + # Check that we can run expressions that return wchar_t + self.expect("expression L'a'", substrs=['(wchar_t) $', "L'a'"]) + + # Mazel Tov if this works! + self.expect("frame variable mazeltov", + substrs=['(const wchar_t *) mazeltov = ', 'L"מזל טוב"']) + + self.expect( + "frame variable ws_NULL", + substrs=['(wchar_t *) ws_NULL = 0x0']) + self.expect("frame variable ws_empty", substrs=[' L""']) + + self.expect("frame variable array", substrs=[ + 'L"Hey, I\'m a super wchar_t string']) + self.expect("frame variable array", substrs=['[0]'], matching=False) + + self.expect('frame variable wchar_zero', substrs=["L'\\0'"]) + self.expect('expression wchar_zero', substrs=["L'\\0'"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/main.cpp new file mode 100644 index 00000000000..4d6a1072d69 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/cpp/wchar_t/main.cpp @@ -0,0 +1,34 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <cstring> + +template <typename T> +class Foo +{ +public: + Foo () : object() {} + Foo (T x) : object(x) {} + T getObject() { return object; } +private: + T object; +}; + + +int main (int argc, char const *argv[]) +{ + Foo<int> foo_x('a'); + Foo<wchar_t> foo_y(L'a'); + const wchar_t *mazeltov = L"מזל טוב"; + wchar_t *ws_NULL = nullptr; + wchar_t *ws_empty = L""; + wchar_t array[200], * array_source = L"Hey, I'm a super wchar_t string, éõñž"; + wchar_t wchar_zero = (wchar_t)0; + memcpy(array, array_source, 39 * sizeof(wchar_t)); + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/Makefile new file mode 100644 index 00000000000..12db32c506f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/Makefile @@ -0,0 +1,4 @@ +CXX_SOURCES := foo.cpp +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py new file mode 100644 index 00000000000..b4fe5396291 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py @@ -0,0 +1,57 @@ +"""Test that lldb works correctly on compile units form different languages.""" + + + +import re +import lldb +from lldbsuite.test.lldbtest import * + + +class MixedLanguagesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_language_of_frame(self): + """Test that the language defaults to the language of the current frame.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Execute the cleanup function during test case tear down + # to restore the frame format. + def cleanup(): + self.runCmd( + "settings set frame-format %s" % + self.format_string, check=False) + self.addTearDownHook(cleanup) + self.runCmd("settings show frame-format") + m = re.match( + '^frame-format \(format-string\) = "(.*)\"$', + self.res.GetOutput()) + self.assertTrue(m, "Bad settings string") + self.format_string = m.group(1) + + # Change the default format to print the language. + format_string = "frame #${frame.index}: ${frame.pc}{ ${module.file.basename}\`${function.name}{${function.pc-offset}}}{, lang=${language}}\n" + self.runCmd("settings set frame-format %s" % format_string) + self.expect("settings show frame-format", SETTING_MSG("frame-format"), + substrs=[format_string]) + + # Run to BP at main (in main.c) and test that the language is C. + self.runCmd("breakpoint set -n main") + self.runCmd("run") + self.expect("thread backtrace", + substrs=["`main", "lang=c"]) + # Make sure evaluation of C++11 fails. + self.expect("expr foo != nullptr", error=True, + startstr="error") + + # Run to BP at foo (in foo.cpp) and test that the language is C++. + self.runCmd("breakpoint set -n foo") + self.runCmd("continue") + self.expect("thread backtrace", + substrs=["`::foo()", "lang=c++"]) + # Make sure we can evaluate an expression requiring C++11 + # (note: C++11 is enabled by default for C++). + self.expect("expr foo != nullptr", + patterns=["true"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/foo.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/foo.cpp new file mode 100644 index 00000000000..8a5a6a2b541 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/foo.cpp @@ -0,0 +1,11 @@ +namespace ns { + int func(void) + { + return 0; + } +} + +extern "C" int foo(void) +{ + return ns::func(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/main.c new file mode 100644 index 00000000000..f5c5d19f2c8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/mixed/main.c @@ -0,0 +1,15 @@ +int foo(void); +static int static_value = 0; + +int +bar() +{ + static_value++; + return static_value; +} + +int main (int argc, char const *argv[]) +{ + bar(); // breakpoint_in_main + return foo(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/.categories new file mode 100644 index 00000000000..72cf07c1efe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/.categories @@ -0,0 +1 @@ +objc diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/TestBitfieldIvars.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/TestBitfieldIvars.py new file mode 100644 index 00000000000..c0d006ee53a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/TestBitfieldIvars.py @@ -0,0 +1,12 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, + globals(), + [ + # This is a Darwin-only failure related to incorrect expression- + # evaluation for single-bit ObjC bitfields. + decorators.skipUnlessDarwin, + decorators.expectedFailureAll( + bugnumber="rdar://problem/17990991")]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/main.m new file mode 100644 index 00000000000..e19f291ecf9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/bitfield_ivars/main.m @@ -0,0 +1,51 @@ +//===-- main.m -------------------------------------------*- Objective-C-*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +@interface HasBitfield : NSObject { +@public + unsigned field1 : 1; + unsigned field2 : 1; +}; + +-(id)init; +@end + +@implementation HasBitfield +-(id)init { + self = [super init]; + field1 = 0; + field2 = 1; + return self; +} +@end + +@interface ContainsAHasBitfield : NSObject { +@public + HasBitfield *hb; +}; +-(id)init; +@end + +@implementation ContainsAHasBitfield +-(id)init { + self = [super init]; + hb = [[HasBitfield alloc] init]; + return self; +} + +@end + +int main(int argc, const char * argv[]) { + ContainsAHasBitfield *chb = [[ContainsAHasBitfield alloc] init]; + printf("%d\n", chb->hb->field2); //% self.expect("expression -- chb->hb->field1", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["= 0"]) + //% self.expect("expression -- chb->hb->field2", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["= 1"]) # this must happen second + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/Makefile new file mode 100644 index 00000000000..df76ed3069f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := ivars-in-blocks.m main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py new file mode 100644 index 00000000000..e790e6e9d96 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py @@ -0,0 +1,131 @@ +"""Test printing ivars and ObjC objects captured in blocks that are made in methods of an ObjC class.""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCIvarsInBlocks(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "main.m" + self.class_source = "ivars-in-blocks.m" + self.class_source_file_spec = lldb.SBFileSpec(self.class_source) + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + @skipIf(dwarf_version=['<', '4']) + @expectedFailureAll( + archs=["i[3-6]86"], + bugnumber="This test requires the 2.0 runtime, so it will fail on i386") + def test_with_python_api(self): + """Test printing the ivars of the self when captured in blocks""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateBySourceRegex( + '// Break here inside the block.', self.class_source_file_spec) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + breakpoint_two = target.BreakpointCreateBySourceRegex( + '// Break here inside the class method block.', self.class_source_file_spec) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, "Created a process.") + self.assertTrue( + process.GetState() == lldb.eStateStopped, + "Stopped it too.") + + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) + thread = thread_list[0] + + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame, "frame 0 is valid") + + # First use the FindVariable API to see if we can find the ivar by + # undecorated name: + direct_blocky = frame.GetValueForVariablePath("blocky_ivar") + self.assertTrue(direct_blocky, "Found direct access to blocky_ivar.") + + # Now get it as a member of "self" and make sure the two values are + # equal: + self_var = frame.GetValueForVariablePath("self") + self.assertTrue(self_var, "Found self in block.") + indirect_blocky = self_var.GetChildMemberWithName("blocky_ivar") + self.assertTrue(indirect_blocky, "Found blocky_ivar through self") + + error = lldb.SBError() + direct_value = direct_blocky.GetValueAsSigned(error) + self.assertTrue(error.Success(), "Got direct value for blocky_ivar") + + indirect_value = indirect_blocky.GetValueAsSigned(error) + self.assertTrue(error.Success(), "Got indirect value for blocky_ivar") + + self.assertTrue( + direct_value == indirect_value, + "Direct and indirect values are equal.") + + # Now make sure that we can get at the captured ivar through the expression parser. + # Doing a little trivial math will force this into the real expression + # parser: + direct_expr = frame.EvaluateExpression("blocky_ivar + 10") + self.assertTrue( + direct_expr, + "Got blocky_ivar through the expression parser") + + # Again, get the value through self directly and make sure they are the + # same: + indirect_expr = frame.EvaluateExpression("self->blocky_ivar + 10") + self.assertTrue( + indirect_expr, + "Got blocky ivar through expression parser using self.") + + direct_value = direct_expr.GetValueAsSigned(error) + self.assertTrue( + error.Success(), + "Got value from direct use of expression parser") + + indirect_value = indirect_expr.GetValueAsSigned(error) + self.assertTrue( + error.Success(), + "Got value from indirect access using the expression parser") + + self.assertTrue( + direct_value == indirect_value, + "Direct ivar access and indirect through expression parser produce same value.") + + process.Continue() + self.assertTrue( + process.GetState() == lldb.eStateStopped, + "Stopped at the second breakpoint.") + + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint_two) + self.assertTrue(len(thread_list) == 1) + thread = thread_list[0] + + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame, "frame 0 is valid") + + expr = frame.EvaluateExpression("(ret)") + self.assertTrue( + expr, "Successfully got a local variable in a block in a class method.") + + ret_value_signed = expr.GetValueAsSigned(error) + # print('ret_value_signed = %i' % (ret_value_signed)) + self.assertTrue( + ret_value_signed == 5, + "The local variable in the block was what we expected.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.h new file mode 100644 index 00000000000..1ceac3361ac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.h @@ -0,0 +1,11 @@ +#import <Foundation/Foundation.h> + +@interface IAmBlocky : NSObject +{ + @public + int blocky_ivar; +} ++ (void) classMethod; +- (IAmBlocky *) init; +- (int) callABlock: (int) block_value; +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.m new file mode 100644 index 00000000000..1098a9136ae --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.m @@ -0,0 +1,57 @@ +#import "ivars-in-blocks.h" + +typedef int (^my_block_ptr_type) (int); + +@interface IAmBlocky() +{ + int _hidden_ivar; + my_block_ptr_type _block_ptr; +} + +@end + +@implementation IAmBlocky + ++ (int) addend +{ + return 3; +} + ++ (void) classMethod +{ + int (^my_block)(int) = ^(int foo) + { + int ret = foo + [self addend]; + return ret; // Break here inside the class method block. + }; + printf("%d\n", my_block(2)); +} + +- (void) makeBlockPtr; +{ + _block_ptr = ^(int inval) + { + _hidden_ivar += inval; + return blocky_ivar * inval; // Break here inside the block. + }; +} + +- (IAmBlocky *) init +{ + blocky_ivar = 10; + _hidden_ivar = 20; + // Interesting... Apparently you can't make a block in your init method. This crashes... + // [self makeBlockPtr]; + return self; +} + +- (int) callABlock: (int) block_value +{ + if (_block_ptr == NULL) + [self makeBlockPtr]; + int ret = _block_ptr (block_value); + [IAmBlocky classMethod]; + return ret; +} +@end + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/main.m new file mode 100644 index 00000000000..0c56f45da46 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/blocks/main.m @@ -0,0 +1,10 @@ +#import "ivars-in-blocks.h" + +int +main (int argc, char **argv) +{ + IAmBlocky *my_blocky = [[IAmBlocky alloc] init]; + int blocky_value; + blocky_value = [my_blocky callABlock: 33]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Makefile new file mode 100644 index 00000000000..00a0769a086 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Makefile @@ -0,0 +1,23 @@ +LD_EXTRAS := -lobjc -framework Foundation -L. -lTest -lTestExt +OBJC_SOURCES := main.m + +all: a.out + +a.out: libTest.dylib libTestExt.dylib + +include Makefile.rules + +libTest.dylib: Test/Test.m + mkdir -p Test + $(MAKE) MAKE_DSYM=YES -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_NAME=Test DYLIB_OBJC_SOURCES=Test/Test.m \ + LD_EXTRAS="-lobjc -framework Foundation" \ + CFLAGS_EXTRAS=-I$(SRCDIR) + +libTestExt.dylib: TestExt/TestExt.m + mkdir -p TestExt + $(MAKE) MAKE_DSYM=YES -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_NAME=TestExt DYLIB_OBJC_SOURCES=TestExt/TestExt.m \ + LD_EXTRAS="-lobjc -framework Foundation -lTest -L." \ + CFLAGS_EXTRAS=-I$(SRCDIR) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Test/Foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Test/Foo.h new file mode 100644 index 00000000000..db07f50d5d6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Test/Foo.h @@ -0,0 +1,9 @@ +#ifndef __Foo_h__ +#define __Foo_h__ + +typedef struct { + float start; + float duration; +} CMTimeRange; + +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Test/Test.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Test/Test.h new file mode 100644 index 00000000000..73928c5fb0d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Test/Test.h @@ -0,0 +1,10 @@ +#import <Foundation/Foundation.h> +#import <Test/Foo.h> + +@interface Test : NSObject { +@public + CMTimeRange _range; +} +- (void) doTest; +@end + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Test/Test.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Test/Test.m new file mode 100644 index 00000000000..6b2cb3af808 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/Test/Test.m @@ -0,0 +1,8 @@ +#import "Test.h" + +@implementation Test +- (void) doTest { + NSLog(@"-[Test doTest]"); +} +@end + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestConflictingDefinition.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestConflictingDefinition.py new file mode 100644 index 00000000000..f49858ca4f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestConflictingDefinition.py @@ -0,0 +1,50 @@ +"""Test that types defined in shared libraries work correctly.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestRealDefinition(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_frame_var_after_stop_at_implementation(self): + """Test that we can find the implementation for an objective C type""" + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + self.build() + self.shlib_names = ["libTestExt.dylib", "libTest.dylib"] + self.common_setup() + + line = line_number('TestExt/TestExt.m', '// break here') + lldbutil.run_break_set_by_file_and_line( + self, 'TestExt.m', line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # This should display correctly. + self.expect( + "expr 42", + "A simple expression should execute correctly", + substrs=[ + "42"]) + + def common_setup(self): + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.registerSharedLibrariesWithTarget(target, self.shlib_names) + + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestExt/Foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestExt/Foo.h new file mode 100644 index 00000000000..7c90e6ca8e3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestExt/Foo.h @@ -0,0 +1,9 @@ +#ifndef __Foo_h__ +#define __Foo_h__ + +typedef struct { + float s; + float d; +} CMTimeRange; + +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestExt/TestExt.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestExt/TestExt.h new file mode 100644 index 00000000000..243443c647b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestExt/TestExt.h @@ -0,0 +1,7 @@ +#import <TestExt/Foo.h> +#import <Test/Test.h> +struct CMTimeRange; + +@interface Test (Stuff) +- (void)doSomethingElse: (CMTimeRange *)range_ptr; +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestExt/TestExt.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestExt/TestExt.m new file mode 100644 index 00000000000..a14c702787d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/TestExt/TestExt.m @@ -0,0 +1,8 @@ +#import "TestExt.h" +#import "Foo.h" + +@implementation Test (Stuff) +- (void)doSomethingElse: (CMTimeRange *)range_ptr { + NSLog(@"doSomethingElse: %p", range_ptr); // break here +} +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/main.m new file mode 100644 index 00000000000..6a714577a35 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/conflicting-definition/main.m @@ -0,0 +1,10 @@ +#import <Test/Test.h> +#import <TestExt/TestExt.h> + +int main() { + @autoreleasepool { + Test *test = [[Test alloc] init]; + [test doSomethingElse:&test->_range]; + } +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/exceptions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/exceptions/Makefile new file mode 100644 index 00000000000..876340159d9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/exceptions/Makefile @@ -0,0 +1,8 @@ +OBJCXX_SOURCES := main.mm + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/exceptions/TestObjCExceptions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/exceptions/TestObjCExceptions.py new file mode 100644 index 00000000000..ce9ee8e027f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/exceptions/TestObjCExceptions.py @@ -0,0 +1,206 @@ +# encoding: utf-8 +""" +Test lldb Obj-C exception support. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCExceptionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_objc_exceptions_at_throw(self): + self.build() + + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + launch_info = lldb.SBLaunchInfo(["a.out", "0"]) + lldbutil.run_to_name_breakpoint(self, "objc_exception_throw", launch_info=launch_info) + + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + self.expect('thread exception', substrs=[ + '(NSException *) exception = ', + '"SomeReason"', + ]) + + target = self.dbg.GetSelectedTarget() + thread = target.GetProcess().GetSelectedThread() + frame = thread.GetSelectedFrame() + + opts = lldb.SBVariablesOptions() + opts.SetIncludeRecognizedArguments(True) + variables = frame.GetVariables(opts) + + self.assertEqual(variables.GetSize(), 1) + self.assertEqual(variables.GetValueAtIndex(0).name, "exception") + self.assertEqual(variables.GetValueAtIndex(0).GetValueType(), lldb.eValueTypeVariableArgument) + + lldbutil.run_to_source_breakpoint(self, "// Set break point at this line.", lldb.SBFileSpec("main.mm"), launch_info=launch_info) + + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + target = self.dbg.GetSelectedTarget() + thread = target.GetProcess().GetSelectedThread() + frame = thread.GetSelectedFrame() + + # No exception being currently thrown/caught at this point + self.assertFalse(thread.GetCurrentException().IsValid()) + self.assertFalse(thread.GetCurrentExceptionBacktrace().IsValid()) + + self.expect( + 'frame variable e1', + substrs=[ + '(NSException *) e1 = ', + '"SomeReason"' + ]) + + self.expect( + 'frame variable --dynamic-type no-run-target *e1', + substrs=[ + '(NSException) *e1 = ', + 'name = ', '"ExceptionName"', + 'reason = ', '"SomeReason"', + 'userInfo = ', '1 key/value pair', + 'reserved = ', 'nil', + ]) + + e1 = frame.FindVariable("e1") + self.assertTrue(e1) + self.assertEqual(e1.type.name, "NSException *") + self.assertEqual(e1.GetSummary(), '"SomeReason"') + self.assertEqual(e1.GetChildMemberWithName("name").description, "ExceptionName") + self.assertEqual(e1.GetChildMemberWithName("reason").description, "SomeReason") + userInfo = e1.GetChildMemberWithName("userInfo").dynamic + self.assertEqual(userInfo.summary, "1 key/value pair") + self.assertEqual(userInfo.GetChildAtIndex(0).GetChildAtIndex(0).description, "some_key") + self.assertEqual(userInfo.GetChildAtIndex(0).GetChildAtIndex(1).description, "some_value") + self.assertEqual(e1.GetChildMemberWithName("reserved").description, "<nil>") + + self.expect( + 'frame variable e2', + substrs=[ + '(NSException *) e2 = ', + '"SomeReason"' + ]) + + self.expect( + 'frame variable --dynamic-type no-run-target *e2', + substrs=[ + '(NSException) *e2 = ', + 'name = ', '"ThrownException"', + 'reason = ', '"SomeReason"', + 'userInfo = ', '1 key/value pair', + 'reserved = ', + ]) + + e2 = frame.FindVariable("e2") + self.assertTrue(e2) + self.assertEqual(e2.type.name, "NSException *") + self.assertEqual(e2.GetSummary(), '"SomeReason"') + self.assertEqual(e2.GetChildMemberWithName("name").description, "ThrownException") + self.assertEqual(e2.GetChildMemberWithName("reason").description, "SomeReason") + userInfo = e2.GetChildMemberWithName("userInfo").dynamic + self.assertEqual(userInfo.summary, "1 key/value pair") + self.assertEqual(userInfo.GetChildAtIndex(0).GetChildAtIndex(0).description, "some_key") + self.assertEqual(userInfo.GetChildAtIndex(0).GetChildAtIndex(1).description, "some_value") + reserved = e2.GetChildMemberWithName("reserved").dynamic + self.assertGreater(reserved.num_children, 0) + callStackReturnAddresses = [reserved.GetChildAtIndex(i).GetChildAtIndex(1) for i in range(0, reserved.GetNumChildren()) + if reserved.GetChildAtIndex(i).GetChildAtIndex(0).description == "callStackReturnAddresses"][0].dynamic + children = [callStackReturnAddresses.GetChildAtIndex(i) for i in range(0, callStackReturnAddresses.num_children)] + + pcs = [i.unsigned for i in children] + names = [target.ResolveSymbolContextForAddress(lldb.SBAddress(pc, target), lldb.eSymbolContextSymbol).GetSymbol().name for pc in pcs] + for n in ["objc_exception_throw", "foo(int)", "main"]: + self.assertTrue(n in names, "%s is in the exception backtrace (%s)" % (n, names)) + + @skipUnlessDarwin + def test_objc_exceptions_at_abort(self): + self.build() + + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + self.runCmd("run 0") + + # We should be stopped at pthread_kill because of an unhandled exception + self.expect("thread list", + substrs=['stopped', 'stop reason = signal SIGABRT']) + + self.expect('thread exception', substrs=[ + '(NSException *) exception = ', + '"SomeReason"', + 'libobjc.A.dylib`objc_exception_throw', + 'a.out`foo', 'at main.mm:24', + 'a.out`rethrow', 'at main.mm:35', + 'a.out`main', + ]) + + process = self.dbg.GetSelectedTarget().process + thread = process.GetSelectedThread() + + # There is an exception being currently processed at this point + self.assertTrue(thread.GetCurrentException().IsValid()) + self.assertTrue(thread.GetCurrentExceptionBacktrace().IsValid()) + + history_thread = thread.GetCurrentExceptionBacktrace() + self.assertGreaterEqual(history_thread.num_frames, 4) + for n in ["objc_exception_throw", "foo(int)", "rethrow(int)", "main"]: + self.assertEqual(len([f for f in history_thread.frames if f.GetFunctionName() == n]), 1) + + self.runCmd("kill") + + self.runCmd("run 1") + # We should be stopped at pthread_kill because of an unhandled exception + self.expect("thread list", + substrs=['stopped', 'stop reason = signal SIGABRT']) + + self.expect('thread exception', substrs=[ + '(MyCustomException *) exception = ', + 'libobjc.A.dylib`objc_exception_throw', + 'a.out`foo', 'at main.mm:26', + 'a.out`rethrow', 'at main.mm:35', + 'a.out`main', + ]) + + process = self.dbg.GetSelectedTarget().process + thread = process.GetSelectedThread() + + history_thread = thread.GetCurrentExceptionBacktrace() + self.assertGreaterEqual(history_thread.num_frames, 4) + for n in ["objc_exception_throw", "foo(int)", "rethrow(int)", "main"]: + self.assertEqual(len([f for f in history_thread.frames if f.GetFunctionName() == n]), 1) + + @skipUnlessDarwin + def test_cxx_exceptions_at_abort(self): + self.build() + + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + self.runCmd("run 2") + + # We should be stopped at pthread_kill because of an unhandled exception + self.expect("thread list", + substrs=['stopped', 'stop reason = signal SIGABRT']) + + self.expect('thread exception', substrs=['exception =']) + + process = self.dbg.GetSelectedTarget().process + thread = process.GetSelectedThread() + + self.assertTrue(thread.GetCurrentException().IsValid()) + + # C++ exception backtraces are not exposed in the API (yet). + self.assertFalse(thread.GetCurrentExceptionBacktrace().IsValid()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/exceptions/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/exceptions/main.mm new file mode 100644 index 00000000000..b5c71f9fcf9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/exceptions/main.mm @@ -0,0 +1,62 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +#import <exception> +#import <stdexcept> + +@interface MyCustomException: NSException +@end +@implementation MyCustomException +@end + +void foo(int n) +{ + NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:@"some_value", @"some_key", nil]; + switch (n) { + case 0: + @throw [[NSException alloc] initWithName:@"ThrownException" reason:@"SomeReason" userInfo:info]; + case 1: + @throw [[MyCustomException alloc] initWithName:@"ThrownException" reason:@"SomeReason" userInfo:info]; + case 2: + throw std::runtime_error("C++ exception"); + } +} + +void rethrow(int n) +{ + @try { + foo(n); + } @catch(NSException *e) { + @throw; + } +} + +int main(int argc, const char * argv[]) +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:@"some_value", @"some_key", nil]; + NSException *e1 = [[NSException alloc] initWithName:@"ExceptionName" reason:@"SomeReason" userInfo:info]; + NSException *e2; + + @try { + foo(atoi(argv[1])); + } @catch(NSException *e) { + e2 = e; + } + + NSLog(@"1"); // Set break point at this line. + + rethrow(atoi(argv[1])); + + [pool drain]; + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.h new file mode 100644 index 00000000000..85bbd06b161 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.h @@ -0,0 +1,13 @@ +#import <Foundation/Foundation.h> + +@class ForwardDeclaredClass; + +@interface Container : NSObject { +@public + ForwardDeclaredClass *member; +} + +-(id)init; +-(ForwardDeclaredClass*)getMember; + +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.m new file mode 100644 index 00000000000..4d2139ff5fc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.m @@ -0,0 +1,27 @@ +#import "Container.h" + +@interface ForwardDeclaredClass : NSObject +{ + int a; + int b; +} +@end + +@implementation ForwardDeclaredClass + +@end + +@implementation Container + +-(id)init +{ + member = [ForwardDeclaredClass alloc]; + return [super init]; +} + +-(ForwardDeclaredClass *)getMember +{ + return member; +} + +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Makefile new file mode 100644 index 00000000000..cfae251ead4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/Makefile @@ -0,0 +1,8 @@ +DYLIB_NAME := Container +DYLIB_OBJC_SOURCES := Container.m +OBJC_SOURCES := main.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py new file mode 100644 index 00000000000..fd35d64c191 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py @@ -0,0 +1,69 @@ +"""Test that a forward-declared class works when its complete definition is in a library""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ForwardDeclTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.m' + self.line = line_number(self.source, '// Set breakpoint 0 here.') + self.shlib_names = ["Container"] + + def do_test(self, dictionary=None): + self.build(dictionary=dictionary) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # This should display correctly. + self.expect("expression [j getMember]", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 0x"]) + + @skipUnlessDarwin + def test_expr(self): + self.do_test() + + @no_debug_info_test + @skipUnlessDarwin + @skipIf(compiler=no_match("clang")) + @skipIf(compiler_version=["<", "7.0"]) + def test_debug_names(self): + """Test that we are able to find complete types when using DWARF v5 + accelerator tables""" + self.do_test( + dict(CFLAGS_EXTRAS="-dwarf-version=5 -mllvm -accel-tables=Dwarf")) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/main.m new file mode 100644 index 00000000000..8e5256e9523 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/forward-decl/main.m @@ -0,0 +1,14 @@ +#import <Foundation/Foundation.h> +#import "Container.h" + +int main(int argc, const char * argv[]) +{ + + @autoreleasepool { + Container *j = [[Container alloc] init]; + + printf("member value = %p", [j getMember]); // Set breakpoint 0 here. + } + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/Makefile new file mode 100644 index 00000000000..e95ebd94a94 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/Makefile @@ -0,0 +1,7 @@ +OBJC_SOURCES := main.m my-base.m +#OBJC_SOURCES := const-strings.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py new file mode 100644 index 00000000000..6e8e9898e19 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py @@ -0,0 +1,57 @@ +""" +Test that objective-c constant strings are generated correctly by the expression +parser. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ConstStringTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + d = {'OBJC_SOURCES': 'const-strings.m'} + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.main_source = "const-strings.m" + self.line = line_number(self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + def test_break(self): + """Test constant string generation amd comparison by the expression parser.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(self.d) + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, + substrs=[" at %s:%d" % (self.main_source, self.line), + "stop reason = breakpoint"]) + + self.expect('expression (int)[str compare:@"hello"]', + startstr="(int) $0 = 0") + self.expect('expression (int)[str compare:@"world"]', + startstr="(int) $1 = -1") + + # Test empty strings, too. + self.expect('expression (int)[@"" length]', + startstr="(int) $2 = 0") + + self.expect('expression (int)[@"123" length]', + startstr="(int) $3 = 3") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py new file mode 100644 index 00000000000..9e39a735f8b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py @@ -0,0 +1,151 @@ +""" +Test the lldb disassemble command on foundation framework. +""" + +import unittest2 +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class FoundationDisassembleTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @skipIfAsan + def test_foundation_disasm(self): + """Do 'disassemble -n func' on each and every 'Code' symbol entry from the Foundation.framework.""" + self.build() + + # Enable synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + foundation_framework = None + for module in target.modules: + if module.file.basename == "Foundation": + foundation_framework = module.file.fullpath + break + + self.assertTrue( + foundation_framework is not None, + "Foundation.framework path located") + self.runCmd("image dump symtab '%s'" % foundation_framework) + raw_output = self.res.GetOutput() + # Now, grab every 'Code' symbol and feed it into the command: + # 'disassemble -n func'. + # + # The symbol name is on the last column and trails the flag column which + # looks like '0xhhhhhhhh', i.e., 8 hexadecimal digits. + codeRE = re.compile(r""" + \ Code\ {9} # ' Code' followed by 9 SPCs, + .* # the wildcard chars, + 0x[0-9a-f]{8} # the flag column, and + \ (.+)$ # finally the function symbol. + """, re.VERBOSE) + for line in raw_output.split(os.linesep): + match = codeRE.search(line) + if match: + func = match.group(1) + self.runCmd('image lookup -s "%s"' % func) + self.runCmd('disassemble -n "%s"' % func) + + @skipIfAsan + def test_simple_disasm(self): + """Test the lldb 'disassemble' command""" + self.build() + + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Stop at +[NSString stringWithFormat:]. + symbol_name = "+[NSString stringWithFormat:]" + break_results = lldbutil.run_break_set_command( + self, "_regexp-break %s" % (symbol_name)) + + lldbutil.check_breakpoint_result( + self, + break_results, + symbol_name=symbol_name, + num_locations=1) + + # Stop at -[MyString initWithNSString:]. + lldbutil.run_break_set_by_symbol( + self, + '-[MyString initWithNSString:]', + num_expected_locations=1, + sym_exact=True) + + # Stop at the "description" selector. + lldbutil.run_break_set_by_selector( + self, + 'description', + num_expected_locations=1, + module_name='a.out') + + # Stop at -[NSAutoreleasePool release]. + break_results = lldbutil.run_break_set_command( + self, "_regexp-break -[NSAutoreleasePool release]") + lldbutil.check_breakpoint_result( + self, + break_results, + symbol_name='-[NSAutoreleasePool release]', + num_locations=1) + + self.runCmd("run", RUN_SUCCEEDED) + + # First stop is +[NSString stringWithFormat:]. + self.expect( + "thread backtrace", + "Stop at +[NSString stringWithFormat:]", + substrs=["Foundation`+[NSString stringWithFormat:]"]) + + # Do the disassemble for the currently stopped function. + self.runCmd("disassemble -f") + + self.runCmd("process continue") + # Skip another breakpoint for +[NSString stringWithFormat:]. + self.runCmd("process continue") + + # Followed by a.out`-[MyString initWithNSString:]. + self.expect( + "thread backtrace", + "Stop at a.out`-[MyString initWithNSString:]", + substrs=["a.out`-[MyString initWithNSString:]"]) + + # Do the disassemble for the currently stopped function. + self.runCmd("disassemble -f") + + self.runCmd("process continue") + + # Followed by -[MyString description]. + self.expect("thread backtrace", "Stop at -[MyString description]", + substrs=["a.out`-[MyString description]"]) + + # Do the disassemble for the currently stopped function. + self.runCmd("disassemble -f") + + self.runCmd("process continue") + # Skip another breakpoint for -[MyString description]. + self.runCmd("process continue") + + # Followed by -[NSAutoreleasePool release]. + self.expect("thread backtrace", "Stop at -[NSAutoreleasePool release]", + substrs=["Foundation`-[NSAutoreleasePool release]"]) + + # Do the disassemble for the currently stopped function. + self.runCmd("disassemble -f") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py new file mode 100644 index 00000000000..7d4990c4f38 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py @@ -0,0 +1,325 @@ +""" +Set breakpoints on objective-c class and instance methods in foundation. +Also lookup objective-c data types and evaluate expressions. +""" + +from __future__ import print_function + + +import os +import os.path +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +file_index = 0 + + +@skipUnlessDarwin +class FoundationTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.main_source = "main.m" + self.line = line_number( + self.main_source, + '// Set break point at this line.') + + def test_break(self): + """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Stop at +[NSString stringWithFormat:]. + break_results = lldbutil.run_break_set_command( + self, "_regexp-break +[NSString stringWithFormat:]") + lldbutil.check_breakpoint_result( + self, + break_results, + symbol_name='+[NSString stringWithFormat:]', + num_locations=1) + + # Stop at -[MyString initWithNSString:]. + lldbutil.run_break_set_by_symbol( + self, + '-[MyString initWithNSString:]', + num_expected_locations=1, + sym_exact=True) + + # Stop at the "description" selector. + lldbutil.run_break_set_by_selector( + self, + 'description', + num_expected_locations=1, + module_name='a.out') + + # Stop at -[NSAutoreleasePool release]. + break_results = lldbutil.run_break_set_command( + self, "_regexp-break -[NSAutoreleasePool release]") + lldbutil.check_breakpoint_result( + self, + break_results, + symbol_name='-[NSAutoreleasePool release]', + num_locations=1) + + self.runCmd("run", RUN_SUCCEEDED) + + # First stop is +[NSString stringWithFormat:]. + self.expect( + "thread backtrace", + "Stop at +[NSString stringWithFormat:]", + substrs=["Foundation`+[NSString stringWithFormat:]"]) + + self.runCmd("process continue") + + # Second stop is still +[NSString stringWithFormat:]. + self.expect( + "thread backtrace", + "Stop at +[NSString stringWithFormat:]", + substrs=["Foundation`+[NSString stringWithFormat:]"]) + + self.runCmd("process continue") + + # Followed by a.out`-[MyString initWithNSString:]. + self.expect( + "thread backtrace", + "Stop at a.out`-[MyString initWithNSString:]", + substrs=["a.out`-[MyString initWithNSString:]"]) + + self.runCmd("process continue") + + # Followed by -[MyString description]. + self.expect("thread backtrace", "Stop at -[MyString description]", + substrs=["a.out`-[MyString description]"]) + + self.runCmd("process continue") + + # Followed by the same -[MyString description]. + self.expect("thread backtrace", "Stop at -[MyString description]", + substrs=["a.out`-[MyString description]"]) + + self.runCmd("process continue") + + # Followed by -[NSAutoreleasePool release]. + self.expect("thread backtrace", "Stop at -[NSAutoreleasePool release]", + substrs=["Foundation`-[NSAutoreleasePool release]"]) + + # rdar://problem/8542091 + # rdar://problem/8492646 + def test_data_type_and_expr(self): + """Lookup objective-c data types and evaluate expressions.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Stop at -[MyString description]. + lldbutil.run_break_set_by_symbol( + self, + '-[MyString description]', + num_expected_locations=1, + sym_exact=True) +# self.expect("breakpoint set -n '-[MyString description]", BREAKPOINT_CREATED, +# startstr = "Breakpoint created: 1: name = '-[MyString description]', +# locations = 1") + + self.runCmd("run", RUN_SUCCEEDED) + + # The backtrace should show we stop at -[MyString description]. + self.expect("thread backtrace", "Stop at -[MyString description]", + substrs=["a.out`-[MyString description]"]) + + # Lookup objc data type MyString and evaluate some expressions. + + self.expect("image lookup -t NSString", DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=['name = "NSString"', + 'compiler_type = "@interface NSString']) + + self.expect("image lookup -t MyString", DATA_TYPES_DISPLAYED_CORRECTLY, + substrs=['name = "MyString"', + 'compiler_type = "@interface MyString', + 'NSString * str;', + 'NSDate * date;']) + + self.expect( + "frame variable --show-types --scope", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["ARG: (MyString *) self"], + patterns=[ + "ARG: \(.*\) _cmd", + "(objc_selector *)|(SEL)"]) + + # rdar://problem/8651752 + # don't crash trying to ask clang how many children an empty record has + self.runCmd("frame variable *_cmd") + + # rdar://problem/8492646 + # test/foundation fails after updating to tot r115023 + # self->str displays nothing as output + self.expect( + "frame variable --show-types 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 --show-types self->date", + VARIABLES_DISPLAYED_CORRECTLY, + startstr="(NSDate *) self->date") + + # This should display the str and date member fields as well. + self.expect( + "frame variable --show-types *self", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(MyString) *self", + "(NSString *) str", + "(NSDate *) date"]) + + # isa should be accessible. + self.expect("expression self->isa", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["(Class)"]) + + # This should fail expectedly. + self.expect( + "expression self->non_existent_member", + COMMAND_FAILED_AS_EXPECTED, + error=True, + substrs=["error:", "'MyString' does not have a member named 'non_existent_member'"]) + + # Use expression parser. + self.runCmd("expression self->str") + self.runCmd("expression self->date") + + # (lldb) expression self->str + # error: instance variable 'str' is protected + # error: 1 errors parsing expression + # + # (lldb) expression self->date + # error: instance variable 'date' is protected + # error: 1 errors parsing expression + # + + self.runCmd("breakpoint delete 1") + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("process continue") + + # 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( + "expression --object-description -- my", + "Object description displayed correctly", + patterns=["Hello from.*a.out.*with timestamp: "]) + + @add_test_categories(['pyapi']) + def test_print_ivars_correctly(self): + self.build() + # See: <rdar://problem/8717050> lldb needs to use the ObjC runtime symbols for ivar offsets + # Only fails for the ObjC 2.0 runtime. + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + break1 = target.BreakpointCreateByLocation(self.main_source, self.line) + self.assertTrue(break1, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread = process.GetThreadAtIndex(0) + if thread.GetStopReason() != lldb.eStopReasonBreakpoint: + from lldbsuite.test.lldbutil import stop_reason_to_str + self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS % + stop_reason_to_str(thread.GetStopReason())) + + # Make sure we stopped at the first breakpoint. + + cur_frame = thread.GetFrameAtIndex(0) + + line_number = cur_frame.GetLineEntry().GetLine() + self.assertTrue(line_number == self.line, "Hit the first breakpoint.") + + my_var = cur_frame.FindVariable("my") + self.assertTrue(my_var, "Made a variable object for my") + + str_var = cur_frame.FindVariable("str") + self.assertTrue(str_var, "Made a variable object for str") + + # Now make sure that the my->str == str: + + my_str_var = my_var.GetChildMemberWithName("str") + self.assertTrue(my_str_var, "Found a str ivar in my") + + str_value = int(str_var.GetValue(), 0) + + my_str_value = int(my_str_var.GetValue(), 0) + + self.assertTrue( + str_value == my_str_value, + "Got the correct value for my->str") + + def test_expression_lookups_objc(self): + """Test running an expression detect spurious debug info lookups (DWARF).""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Stop at -[MyString initWithNSString:]. + lldbutil.run_break_set_by_symbol( + self, + '-[MyString initWithNSString:]', + num_expected_locations=1, + sym_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + global file_index + # Log any DWARF lookups + ++file_index + logfile = os.path.join( + self.getBuildDir(), + "dwarf-lookups-" + + self.getArchitecture() + + "-" + + str(file_index) + + ".txt") + self.runCmd("log enable -f %s dwarf lookups" % (logfile)) + self.runCmd("expr self") + self.runCmd("log disable dwarf lookups") + + def cleanup(): + if os.path.exists(logfile): + os.unlink(logfile) + + self.addTearDownHook(cleanup) + + if os.path.exists(logfile): + f = open(logfile) + lines = f.readlines() + num_errors = 0 + for line in lines: + if "$__lldb" in line: + if num_errors == 0: + print( + "error: found spurious name lookups when evaluating an expression:") + num_errors += 1 + print(line, end='') + self.assertTrue(num_errors == 0, "Spurious lookups detected") + f.close() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py new file mode 100644 index 00000000000..b2d0d190eb0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py @@ -0,0 +1,40 @@ +""" +Test more expression command sequences with objective-c. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class FoundationTestCase2(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test_expr_commands(self): + """More expression commands for objective-c.""" + self.build() + main_spec = lldb.SBFileSpec("main.m") + + (target, process, thread, bp) = lldbutil.run_to_source_breakpoint( + self, "Break here for selector: tests", main_spec) + + # Test_Selector: + self.expect("expression (char *)sel_getName(sel)", + substrs=["(char *)", + "length"]) + + desc_bkpt = target.BreakpointCreateBySourceRegex("Break here for description test", + main_spec) + self.assertEqual(desc_bkpt.GetNumLocations(), 1, "description breakpoint has a location") + lldbutil.continue_to_breakpoint(process, desc_bkpt) + + self.expect("expression (char *)sel_getName(_cmd)", + substrs=["(char *)", + "description"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsNSArray.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsNSArray.py new file mode 100644 index 00000000000..8080029ef02 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsNSArray.py @@ -0,0 +1,36 @@ +""" +Test more expression command sequences with objective-c. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class FoundationTestCaseNSArray(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_NSArray_expr_commands(self): + """Test expression commands for NSArray.""" + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Break here for NSArray tests', + lldb.SBFileSpec('main.m', False)) + + self.runCmd("thread backtrace") + self.expect("expression (int)[nil_mutable_array count]", + patterns=["\(int\) \$.* = 0"]) + self.expect("expression (int)[array1 count]", + patterns=["\(int\) \$.* = 3"]) + self.expect("expression (int)[array2 count]", + patterns=["\(int\) \$.* = 3"]) + self.expect("expression (int)array1.count", + patterns=["\(int\) \$.* = 3"]) + self.expect("expression (int)array2.count", + patterns=["\(int\) \$.* = 3"]) + self.runCmd("process continue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsNSError.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsNSError.py new file mode 100644 index 00000000000..07717926b5e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsNSError.py @@ -0,0 +1,49 @@ +""" +Test more expression command sequences with objective-c. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class FoundationTestCaseNSError(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll(archs=["i[3-6]86"], bugnumber="<rdar://problem/28814052>") + def test_runtime_types(self): + """Test commands that require runtime types""" + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Break here for NSString tests', + lldb.SBFileSpec('main.m', False)) + + # Test_NSString: + self.runCmd("thread backtrace") + self.expect("expression [str length]", + patterns=["\(NSUInteger\) \$.* ="]) + self.expect("expression str.length") + self.expect('expression str = [NSString stringWithCString: "new"]') + self.expect( + 'po [NSError errorWithDomain:@"Hello" code:35 userInfo:@{@"NSDescription" : @"be completed."}]', + substrs=[ + "Error Domain=Hello", + "Code=35", + "be completed."]) + self.runCmd("process continue") + + @expectedFailureAll(archs=["i[3-6]86"], bugnumber="<rdar://problem/28814052>") + def test_NSError_p(self): + """Test that p of the result of an unknown method does require a cast.""" + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Set break point at this line', + lldb.SBFileSpec('main.m', False)) + self.expect("p [NSError thisMethodIsntImplemented:0]", error=True, patterns=[ + "no known method", "cast the message send to the method's return type"]) + self.runCmd("process continue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsString.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsString.py new file mode 100644 index 00000000000..65ccb0c19b5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethodsString.py @@ -0,0 +1,53 @@ +""" +Test more expression command sequences with objective-c. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class FoundationTestCaseString(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def test_NSString_expr_commands(self): + """Test expression commands for NSString.""" + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Break here for NSString tests', + lldb.SBFileSpec('main.m', False)) + + # Test_NSString: + self.runCmd("thread backtrace") + self.expect("expression (int)[str length]", + patterns=["\(int\) \$.* ="]) + self.expect("expression (int)[str_id length]", + patterns=["\(int\) \$.* ="]) + self.expect("expression (id)[str description]", + patterns=["\(id\) \$.* = 0x"]) + self.expect("expression (id)[str_id description]", + patterns=["\(id\) \$.* = 0x"]) + self.expect("expression str.length") + self.expect('expression str = @"new"') + self.runCmd("image lookup -t NSString") + self.expect('expression str = (id)[NSString stringWithCString: "new"]') + self.runCmd("process continue") + + @expectedFailureAll(archs=["i[3-6]86"], bugnumber="<rdar://problem/28814052>") + def test_MyString_dump_with_runtime(self): + """Test dump of a known Objective-C object by dereferencing it.""" + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Set break point at this line', + lldb.SBFileSpec('main.m', False)) + self.expect( + "expression --show-types -- *my", + patterns=[ + "\(MyString\) \$.* = ", + "\(MyBase\)"]) + self.runCmd("process continue") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py new file mode 100644 index 00000000000..803cbfe1218 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py @@ -0,0 +1,75 @@ +""" +Test SBValue.GetObjectDescription() with the value from SBTarget.FindGlobalVariables(). +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjectDescriptionAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.source = 'main.m' + self.line = line_number( + self.source, '// Set break point at this line.') + + # rdar://problem/10857337 + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_find_global_variables_then_object_description(self): + """Exercise SBTarget.FindGlobalVariables() API.""" + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + exe = self.getBuildArtifact('b.out') + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + # Make sure we hit our breakpoint: + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) + + thread = thread_list[0] + frame0 = thread.GetFrameAtIndex(0) + + # Note my_global_str's object description prints fine here. + value_list1 = frame0.GetVariables(True, True, True, True) + for v in value_list1: + self.DebugSBValue(v) + if self.TraceOn(): + print("val:", v) + print("object description:", v.GetObjectDescription()) + if v.GetName() == 'my_global_str': + self.assertTrue(v.GetObjectDescription() == + 'This is a global string') + + # But not here! + value_list2 = target.FindGlobalVariables('my_global_str', 3) + for v in value_list2: + self.DebugSBValue(v) + if self.TraceOn(): + print("val:", v) + print("object description:", v.GetObjectDescription()) + if v.GetName() == 'my_global_str': + self.assertTrue(v.GetObjectDescription() == + 'This is a global string') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py new file mode 100644 index 00000000000..f5cb75b4a6d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py @@ -0,0 +1,59 @@ +""" +Test that Objective-C methods from the runtime work correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class RuntimeTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["macosx"], + debug_info="gmodules", + bugnumber="llvm.org/pr27862") + def test_break(self): + """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'.""" + if self.getArchitecture() != 'x86_64': + self.skipTest("This only applies to the v2 runtime") + + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Stop at -[MyString description]. + lldbutil.run_break_set_by_symbol( + self, + '-[MyString description]', + num_expected_locations=1, + sym_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The backtrace should show we stop at -[MyString description]. + self.expect("thread backtrace", "Stop at -[MyString description]", + substrs=["a.out`-[MyString description]"]) + + # Use runtime information about NSString. + + # The length property should be usable. + self.expect("expression str.length", VARIABLES_DISPLAYED_CORRECTLY, + patterns=[r"(\(unsigned long long\))|\(NSUInteger\)"]) + + # Static methods on NSString should work. + self.expect( + "expr [NSString stringWithCString:\"foo\" encoding:1]", + VALID_TYPE, + substrs=[ + "(id)", + "$1"]) + + self.expect("po $1", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py new file mode 100644 index 00000000000..abfc7621e2e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py @@ -0,0 +1,68 @@ +""" +Test symbol table access for main.m. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class FoundationSymtabTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + symbols_list = ['-[MyString initWithNSString:]', + '-[MyString dealloc]', + '-[MyString description]', + '-[MyString descriptionPauses]', # synthesized property + # synthesized property + '-[MyString setDescriptionPauses:]', + 'Test_Selector', + 'Test_NSString', + 'Test_MyString', + 'Test_NSArray', + 'main' + ] + + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test symbol table access with Python APIs.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # + # Exercise Python APIs to access the symbol table entries. + # + + # Create the filespec by which to locate our a.out module. + filespec = lldb.SBFileSpec(exe, False) + + module = target.FindModule(filespec) + self.assertTrue(module, VALID_MODULE) + + # Create the set of known symbols. As we iterate through the symbol + # table, remove the symbol from the set if it is a known symbol. + expected_symbols = set(self.symbols_list) + for symbol in module: + self.assertTrue(symbol, VALID_SYMBOL) + #print("symbol:", symbol) + name = symbol.GetName() + if name in expected_symbols: + #print("Removing %s from known_symbols %s" % (name, expected_symbols)) + expected_symbols.remove(name) + + # At this point, the known_symbols set should have become an empty set. + # If not, raise an error. + #print("symbols unaccounted for:", expected_symbols) + self.assertTrue(len(expected_symbols) == 0, + "All the known symbols are accounted for") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/const-strings.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/const-strings.m new file mode 100644 index 00000000000..8a43abee7b8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/const-strings.m @@ -0,0 +1,24 @@ +#import <Foundation/Foundation.h> + +// Tests to run: + +// Breakpoint 1 +// -- +// (lldb) expr (int)[str compare:@"hello"] +// (int) $0 = 0 +// (lldb) expr (int)[str compare:@"world"] +// (int) $1 = -1 +// (lldb) expr (int)[@"" length] +// (int) $2 = 0 + +int main () +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSString *str = [NSString stringWithCString:"hello" encoding:NSASCIIStringEncoding]; + + NSLog(@"String \"%@\" has length %lu", str, [str length]); // Set breakpoint here. + + [pool drain]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/main.m new file mode 100644 index 00000000000..519bec5a3e6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/main.m @@ -0,0 +1,141 @@ +#import <Foundation/Foundation.h> +#include <unistd.h> +#import "my-base.h" + +@interface MyString : MyBase { + NSString *str; + NSDate *date; + BOOL _desc_pauses; +} + +@property(retain) NSString * str_property; +@property BOOL descriptionPauses; + +- (id)initWithNSString:(NSString *)string; +@end + +@implementation MyString +@synthesize descriptionPauses = _desc_pauses; +@synthesize str_property = str; + +- (id)initWithNSString:(NSString *)string +{ + if (self = [super init]) + { + str = [NSString stringWithString:string]; + date = [NSDate date]; + } + self.descriptionPauses = NO; + return self; +} + +- (void)dealloc +{ + [date release]; + [str release]; + [super dealloc]; +} + +- (NSString *)description +{ + // Set a breakpoint on '-[MyString description]' and test expressions: + // expression (char *)sel_getName(_cmd) + if (self.descriptionPauses) // Break here for description test + { + printf ("\nAbout to sleep.\n"); + usleep(100000); + } + + return [str stringByAppendingFormat:@" with timestamp: %@", date]; +} +@end + +int +Test_Selector () +{ + SEL sel = @selector(length); + printf("sel = %p\n", sel); + // Expressions to test here for selector: + // expression (char *)sel_getName(sel) + // The expression above should return "sel" as it should be just + // a uniqued C string pointer. We were seeing the result pointer being + // truncated with recent LLDBs. + return 0; // Break here for selector: tests +} + +int +Test_NSString (const char *program) +{ + NSString *str = [NSString stringWithFormat:@"Hello from '%s'", program]; + NSLog(@"NSString instance: %@", str); + printf("str = '%s'\n", [str cStringUsingEncoding: [NSString defaultCStringEncoding]]); + printf("[str length] = %zu\n", (size_t)[str length]); + printf("[str description] = %s\n", [[str description] UTF8String]); + id str_id = str; + // Expressions to test here for NSString: + // expression (char *)sel_getName(sel) + // expression [str length] + // expression [str_id length] + // expression [str description] + // expression [str_id description] + // expression str.length + // expression str.description + // expression str = @"new" + // expression str = [NSString stringWithFormat: @"%cew", 'N'] + return 0; // Break here for NSString tests +} + +NSString *my_global_str = NULL; + +void +Test_MyString (const char *program) +{ + my_global_str = @"This is a global string"; + NSString *str = [NSString stringWithFormat:@"Hello from '%s'", program]; + MyString *my = [[MyString alloc] initWithNSString:str]; + NSLog(@"MyString instance: %@", [my description]); + my.descriptionPauses = YES; // Set break point at this line. Test 'expression -o -- my'. + NSLog(@"MyString instance: %@", [my description]); +} + +int +Test_NSArray () +{ + NSMutableArray *nil_mutable_array = nil; + NSArray *array1 = [NSArray arrayWithObjects: @"array1 object1", @"array1 object2", @"array1 object3", nil]; + NSArray *array2 = [NSArray arrayWithObjects: array1, @"array2 object2", @"array2 object3", nil]; + // Expressions to test here for NSArray: + // expression [nil_mutable_array count] + // expression [array1 count] + // expression array1.count + // expression [array2 count] + // expression array2.count + id obj; + // After each object at index call, use expression and validate object + obj = [array1 objectAtIndex: 0]; // Break here for NSArray tests + obj = [array1 objectAtIndex: 1]; + obj = [array1 objectAtIndex: 2]; + + obj = [array2 objectAtIndex: 0]; + obj = [array2 objectAtIndex: 1]; + obj = [array2 objectAtIndex: 2]; + NSUInteger count = [nil_mutable_array count]; + return 0; +} + + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + Test_Selector(); + Test_NSArray (); + Test_NSString (argv[0]); + Test_MyString (argv[0]); + + printf("sizeof(id) = %zu\n", sizeof(id)); + printf("sizeof(Class) = %zu\n", sizeof(Class)); + printf("sizeof(SEL) = %zu\n", sizeof(SEL)); + + [pool release]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.h new file mode 100644 index 00000000000..53202aa0de3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.h @@ -0,0 +1,8 @@ +@interface MyBase : NSObject +{ +#if !__OBJC2__ + int maybe_used; // The 1.0 runtime needs to have backed properties... +#endif +} +@property int propertyMovesThings; +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.m new file mode 100644 index 00000000000..0c316b244f2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.m @@ -0,0 +1,10 @@ +#import <Foundation/Foundation.h> +#import "my-base.h" +@implementation MyBase +#if __OBJC2__ +@synthesize propertyMovesThings; +#else +@synthesize propertyMovesThings = maybe_used; +#endif +@end + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/Makefile new file mode 100644 index 00000000000..afecbf96948 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/TestGlobalObjects.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/TestGlobalObjects.py new file mode 100644 index 00000000000..5cc6f4e7ba9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/TestGlobalObjects.py @@ -0,0 +1,57 @@ +"""Test that a global ObjC object found before the process is started updates correctly.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCGlobalVar(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.main_source = lldb.SBFileSpec("main.m") + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test that a global ObjC object found before the process is started updates correctly.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + bkpt = target.BreakpointCreateBySourceRegex('NSLog', self.main_source) + self.assertTrue(bkpt, VALID_BREAKPOINT) + + # Before we launch, make an SBValue for our global object pointer: + g_obj_ptr = target.FindFirstGlobalVariable("g_obj_ptr") + self.assertTrue(g_obj_ptr.GetError().Success(), "Made the g_obj_ptr") + self.assertTrue( + g_obj_ptr.GetValueAsUnsigned(10) == 0, + "g_obj_ptr is initially null") + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint(process, bkpt) + if len(threads) != 1: + self.fail("Failed to stop at breakpoint 1.") + + thread = threads[0] + + dyn_value = g_obj_ptr.GetDynamicValue(lldb.eDynamicCanRunTarget) + self.assertTrue( + dyn_value.GetError().Success(), + "Dynamic value is valid") + self.assertTrue(dyn_value.GetObjectDescription() == "Some NSString") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/main.m new file mode 100644 index 00000000000..977a984e06e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/global_ptrs/main.m @@ -0,0 +1,11 @@ +#import <Foundation/Foundation.h> + +id g_obj_ptr = nil; + +int +main() +{ + g_obj_ptr = @"Some NSString"; + NSLog(@"My string was %@.", g_obj_ptr); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.h new file mode 100644 index 00000000000..59652d4b09c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.h @@ -0,0 +1,11 @@ +#import <Foundation/Foundation.h> +#import <stdint.h> + +@interface InternalDefiner : NSObject { +@public + uintptr_t foo; +} + +-(id)initWithFoo:(uintptr_t)f andBar:(uintptr_t)b; + +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.m new file mode 100644 index 00000000000..1a10ce021ce --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.m @@ -0,0 +1,31 @@ +#import "InternalDefiner.h" + +@interface InternalDefiner () { + uintptr_t bar; +} + +@end + +@implementation InternalDefiner + +-(id)init +{ + if (self = [super init]) + { + foo = 2; + bar = 3; + } + return self; +} + +-(id)initWithFoo:(uintptr_t)f andBar:(uintptr_t)b +{ + if (self = [super init]) + { + foo = f; + bar = b; + } + return self; +} + +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/Makefile new file mode 100644 index 00000000000..0664769456e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/Makefile @@ -0,0 +1,7 @@ +DYLIB_NAME := InternalDefiner +DYLIB_OBJC_SOURCES := InternalDefiner.m +OBJC_SOURCES := main.m + +LD_EXTRAS = -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py new file mode 100644 index 00000000000..03a325ac49c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py @@ -0,0 +1,238 @@ +"""Test that hidden ivars in a shared library are visible from the main executable.""" + + + +import unittest2 +import subprocess + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class HiddenIvarsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.source = 'main.m' + self.line = line_number(self.source, '// breakpoint1') + # The makefile names of the shared libraries as they appear in DYLIB_NAME. + # The names should have no loading "lib" or extension as they will be + # localized + self.shlib_names = ["InternalDefiner"] + + @skipUnlessDarwin + @skipIf( + debug_info=no_match("dsym"), + bugnumber="This test requires a stripped binary and a dSYM") + def test_expr_stripped(self): + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + else: + self.build() + self.expr(True) + + @skipUnlessDarwin + def test_expr(self): + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + else: + self.build() + self.expr(False) + + @skipUnlessDarwin + @skipIf( + debug_info=no_match("dsym"), + bugnumber="This test requires a stripped binary and a dSYM") + def test_frame_variable_stripped(self): + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + else: + self.build() + self.frame_var(True) + + @skipUnlessDarwin + def test_frame_variable(self): + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + else: + self.build() + self.frame_var(False) + + @unittest2.expectedFailure("rdar://18683637") + @skipUnlessDarwin + def test_frame_variable_across_modules(self): + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + else: + self.build() + self.common_setup(False) + self.expect( + "frame variable k->bar", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 3"]) + + def common_setup(self, strip): + + if strip: + self.assertTrue(subprocess.call( + ['/usr/bin/strip', '-Sx', + self.getBuildArtifact('libInternalDefiner.dylib')]) == 0, + 'stripping dylib succeeded') + self.assertTrue(subprocess.call( + ['/bin/rm', '-rf', + self.getBuildArtifact('libInternalDefiner.dylib.dSYM')]) == 0, + 'remove dylib dSYM file succeeded') + self.assertTrue(subprocess.call(['/usr/bin/strip', '-Sx', + self.getBuildArtifact("a.out") + ]) == 0, + 'stripping a.out succeeded') + # Create a target by the debugger. + target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + environment = self.registerSharedLibrariesWithTarget( + target, self.shlib_names) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + def expr(self, strip): + self.common_setup(strip) + + # This should display correctly. + self.expect( + "expression (j->_definer->foo)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 4"]) + + self.expect( + "expression (j->_definer->bar)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 5"]) + + if strip: + self.expect( + "expression *(j->_definer)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo = 4"]) + else: + self.expect( + "expression *(j->_definer)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 4", + "bar = 5"]) + + self.expect("expression (k->foo)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 2"]) + + self.expect("expression (k->bar)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 3"]) + + self.expect( + "expression k.filteredDataSource", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + ' = 0x', + '"2 elements"']) + + if strip: + self.expect("expression *(k)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo = 2", ' = 0x', '"2 elements"']) + else: + self.expect( + "expression *(k)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 2", + "bar = 3", + '_filteredDataSource = 0x', + '"2 elements"']) + + def frame_var(self, strip): + self.common_setup(strip) + + # This should display correctly. + self.expect( + "frame variable j->_definer->foo", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 4"]) + + if not strip: + self.expect( + "frame variable j->_definer->bar", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 5"]) + + if strip: + self.expect( + "frame variable *j->_definer", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo = 4"]) + else: + self.expect( + "frame variable *j->_definer", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 4", + "bar = 5"]) + + self.expect("frame variable k->foo", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["= 2"]) + + self.expect( + "frame variable k->_filteredDataSource", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + ' = 0x', + '"2 elements"']) + + if strip: + self.expect( + "frame variable *k", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 2", + '_filteredDataSource = 0x', + '"2 elements"']) + else: + self.expect( + "frame variable *k", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "foo = 2", + "bar = 3", + '_filteredDataSource = 0x', + '"2 elements"']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/main.m new file mode 100644 index 00000000000..1795d56e7d8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/main.m @@ -0,0 +1,54 @@ +#import <Foundation/Foundation.h> +#import "InternalDefiner.h" + +@interface Container : NSObject { +@public + InternalDefiner *_definer; +} + +-(id)init; +@end + +@implementation Container + +-(id)init +{ + if (self = [super init]) + { + _definer = [[InternalDefiner alloc] initWithFoo:4 andBar:5]; + } + return self; +} + +@end + +@interface InheritContainer : InternalDefiner +@property (nonatomic, strong) NSMutableArray *filteredDataSource; +-(id)init; +@end + +@implementation InheritContainer + +-(id)init +{ + if (self = [super initWithFoo:2 andBar:3]) + { + self.filteredDataSource = [NSMutableArray arrayWithObjects:@"hello", @"world", nil]; + } + return self; +} + +@end + +int main(int argc, const char * argv[]) +{ + @autoreleasepool { + Container *j = [[Container alloc] init]; + InheritContainer *k = [[InheritContainer alloc] init]; + + printf("ivar value = %u\n", (unsigned)j->_definer->foo); // breakpoint1 + printf("ivar value = %u\n", (unsigned)k->foo); + } + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/Makefile new file mode 100644 index 00000000000..ba7e23acaba --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/Makefile @@ -0,0 +1,13 @@ +CFLAGS := -g -O0 +CFLAGS_NO_DEBUG = + +all: aout + +aout: + $(CC) $(CFLAGS_NO_DEBUG) $(SRCDIR)/myclass.m -c -o myclass.o + $(CC) $(CFLAGS) myclass.o $(SRCDIR)/repro.m -framework Foundation + +clean:: + rm -f myclass.o + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py new file mode 100644 index 00000000000..3019bcfc5cf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py @@ -0,0 +1,48 @@ +""" +Test that dynamically discovered ivars of type IMP do not crash LLDB +""" + + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCiVarIMPTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIf(archs=['i386']) # objc file does not build for i386 + @no_debug_info_test + def test_imp_ivar_type(self): + """Test that dynamically discovered ivars of type IMP do not crash LLDB""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target from the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set up our breakpoint + + bkpt = lldbutil.run_break_set_by_source_regexp(self, "break here") + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + self.expect( + 'frame variable --ptr-depth=1 --show-types -d run -- object', + substrs=[ + '(MyClass *) object = 0x', + '(void *) myImp = 0x']) + self.expect( + 'disassemble --start-address `((MyClass*)object)->myImp`', + substrs=['-[MyClass init]']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.h new file mode 100644 index 00000000000..da28d1e0518 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.h @@ -0,0 +1,6 @@ +#import <Foundation/Foundation.h> + +@interface MyClass : NSObject +{} +- (id)init; +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.m new file mode 100644 index 00000000000..85b2fcfe9b3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.m @@ -0,0 +1,16 @@ +#import <Foundation/Foundation.h> +#import "myclass.h" + +@implementation MyClass +{ + IMP myImp; +} +- (id)init { + if (self = [super init]) + { + SEL theSelector = @selector(init); + self->myImp = [self methodForSelector:theSelector]; + } + return self; +} +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/repro.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/repro.m new file mode 100644 index 00000000000..14f911f07dd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/repro.m @@ -0,0 +1,7 @@ +#import <Foundation/Foundation.h> +#import "myclass.h" + +int main() { + id object = [MyClass new]; + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/Makefile new file mode 100644 index 00000000000..0d8068b3085 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/Makefile @@ -0,0 +1,5 @@ +CFLAGS_EXTRAS = -I$(BUILDDIR) +USE_PRIVATE_MODULE_CACHE := YES +OBJC_SOURCES := main.m foo.m + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/TestClangModulesAppUpdate.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/TestClangModulesAppUpdate.py new file mode 100644 index 00000000000..4bd136b7285 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/TestClangModulesAppUpdate.py @@ -0,0 +1,57 @@ + +import unittest2 +import os +import shutil + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestClangModuleAppUpdate(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIf(debug_info=no_match(["gmodules"])) + def test_rebuild_app_modules_untouched(self): + with open(self.getBuildArtifact("module.modulemap"), "w") as f: + f.write(""" + module Foo { header "f.h" } + """) + with open(self.getBuildArtifact("f.h"), "w") as f: + f.write(""" + @import Foundation; + @interface Foo : NSObject { + int i; + } + +(instancetype)init; + @end + """) + + mod_cache = self.getBuildArtifact("private-module-cache") + import os + if os.path.isdir(mod_cache): + shutil.rmtree(mod_cache) + self.build() + self.assertTrue(os.path.isdir(mod_cache), "module cache exists") + + target, process, _, bkpt = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec("main.m")) + bar = target.FindTypes('Bar').GetTypeAtIndex(0) + foo = bar.GetDirectBaseClassAtIndex(0).GetType() + self.assertEqual(foo.GetNumberOfFields(), 1) + self.assertEqual(foo.GetFieldAtIndex(0).GetName(), "i") + + # Rebuild. + process.Kill() + os.remove(self.getBuildArtifact('main.o')) + os.remove(self.getBuildArtifact('a.out')) + self.build() + + # Reattach. + target, process, _, _ = lldbutil.run_to_breakpoint_do_run(self, target, bkpt) + bar = target.FindTypes('Bar').GetTypeAtIndex(0) + foo = bar.GetDirectBaseClassAtIndex(0).GetType() + self.assertEqual(foo.GetNumberOfFields(), 1) + self.assertEqual(foo.GetFieldAtIndex(0).GetName(), "i") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/foo.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/foo.m new file mode 100644 index 00000000000..83a5abc04e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/foo.m @@ -0,0 +1,7 @@ +@import Foundation; +@import Foo; +@implementation Foo ++(instancetype)init { + return [super init]; +} +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/main.m new file mode 100644 index 00000000000..37ec1f37b57 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/main.m @@ -0,0 +1,17 @@ +@import Umbrella; + +@interface Bar : Foo ++(instancetype)init; +@end + +@implementation Bar ++(instancetype)init { + return [super init]; +} +@end + +int main(int argc, char **argv) { + id bar = [Bar new]; + [bar i]; // break here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/module.modulemap b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/module.modulemap new file mode 100644 index 00000000000..c142410cd07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/module.modulemap @@ -0,0 +1,4 @@ +module Umbrella { + header "umbrella.h" + export * +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/umbrella.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/umbrella.h new file mode 100644 index 00000000000..375d3ea2a04 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-app-update/umbrella.h @@ -0,0 +1 @@ +@import Foo; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/Makefile new file mode 100644 index 00000000000..3b2bd504c89 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/Makefile @@ -0,0 +1,5 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS = $(MANDATORY_MODULE_BUILD_CFLAGS) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py new file mode 100644 index 00000000000..449e5b50d05 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py @@ -0,0 +1,48 @@ +"""Test that importing modules in Objective-C works as expected.""" + + + +import unittest2 +import lldb + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCModulesAutoImportTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.m', '// Set breakpoint 0 here.') + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + def test_expr(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.runCmd("settings set target.auto-import-clang-modules true") + + self.expect("p getpid()", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["pid_t"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/main.m new file mode 100644 index 00000000000..5452ffd9bd1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/main.m @@ -0,0 +1,7 @@ +@import Darwin; + +int main() +{ + size_t ret = printf("Stop here\n"); // Set breakpoint 0 here. + return ret; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/Makefile new file mode 100644 index 00000000000..d0aadc1af9e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/Makefile @@ -0,0 +1,2 @@ +OBJC_SOURCES := main.m +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/TestClangModulesCache.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/TestClangModulesCache.py new file mode 100644 index 00000000000..3a12b23a79c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/TestClangModulesCache.py @@ -0,0 +1,35 @@ +"""Test that the clang modules cache directory can be controlled.""" + + + +import unittest2 +import os +import shutil + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCModulesTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_expr(self): + self.build() + self.main_source_file = lldb.SBFileSpec("main.m") + self.runCmd("settings set target.auto-import-clang-modules true") + mod_cache = self.getBuildArtifact("my-clang-modules-cache") + if os.path.isdir(mod_cache): + shutil.rmtree(mod_cache) + self.assertFalse(os.path.isdir(mod_cache), + "module cache should not exist") + self.runCmd('settings set symbols.clang-modules-cache-path "%s"' % mod_cache) + self.runCmd('settings set target.clang-module-search-paths "%s"' + % self.getSourceDir()) + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, "Set breakpoint here", self.main_source_file) + self.runCmd("expr @import Foo") + self.assertTrue(os.path.isdir(mod_cache), "module cache exists") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/f.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/f.h new file mode 100644 index 00000000000..56757a701bf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/f.h @@ -0,0 +1 @@ +void f() {} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/main.m new file mode 100644 index 00000000000..6009d28d81b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/main.m @@ -0,0 +1,5 @@ +#include "f.h" +int main() { + f(); // Set breakpoint here. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/module.modulemap b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/module.modulemap new file mode 100644 index 00000000000..f54534a1c07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-cache/module.modulemap @@ -0,0 +1,3 @@ +module Foo { + header "f.h" +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/Makefile new file mode 100644 index 00000000000..59bf009f686 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/Makefile @@ -0,0 +1,16 @@ +OBJC_SOURCES := main.m +CFLAGS_EXTRAS = -I$(BUILDDIR) +USE_PRIVATE_MODULE_CACHE = YES + +.PHONY: update-module + +all: $(EXE) + $(MAKE) -f $(SRCDIR)/Makefile update-module + +include Makefile.rules + +update-module: + echo "forcing an update of f.pcm" + echo "typedef int something_other;" > $(BUILDDIR)/f.h + $(CC) $(CFLAGS) $(MANDATORY_MODULE_BUILD_CFLAGS) \ + -c $(SRCDIR)/other.m -o $(BUILDDIR)/other.o diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/TestClangModulesHashMismatch.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/TestClangModulesHashMismatch.py new file mode 100644 index 00000000000..606bd300c24 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/TestClangModulesHashMismatch.py @@ -0,0 +1,45 @@ + +import unittest2 +import os +import shutil + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestClangModuleHashMismatch(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIf(debug_info=no_match(["gmodules"])) + def test_expr(self): + with open(self.getBuildArtifact("module.modulemap"), "w") as f: + f.write(""" + module Foo { header "f.h" } + """) + with open(self.getBuildArtifact("f.h"), "w") as f: + f.write(""" + typedef int my_int; + void f() {} + """) + + mod_cache = self.getBuildArtifact("private-module-cache") + if os.path.isdir(mod_cache): + shutil.rmtree(mod_cache) + self.build() + self.assertTrue(os.path.isdir(mod_cache), "module cache exists") + + logfile = self.getBuildArtifact("host.log") + self.runCmd("log enable -v -f %s lldb host" % logfile) + target, _, _, _ = lldbutil.run_to_source_breakpoint( + self, "break here", lldb.SBFileSpec("main.m")) + target.GetModuleAtIndex(0).FindTypes('my_int') + + found = False + with open(logfile, 'r') as f: + for line in f: + if "hash mismatch" in line and "Foo" in line: + found = True + self.assertTrue(found) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/main.m new file mode 100644 index 00000000000..5065222731e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/main.m @@ -0,0 +1,6 @@ +#include "f.h" +int main(int argc, char **argv) { + my_int i = argc; + f(); // break here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/other.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/other.m new file mode 100644 index 00000000000..0afd3eb078d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-hash-mismatch/other.m @@ -0,0 +1,4 @@ +#include "f.h" +something_other f() { + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/Makefile new file mode 100644 index 00000000000..abb36e281b2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/Makefile @@ -0,0 +1,5 @@ +OBJC_SOURCES := main.m myModule.m + +CFLAGS_EXTRAS = $(MANDATORY_MODULE_BUILD_CFLAGS) +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py new file mode 100644 index 00000000000..8fed6133f7d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py @@ -0,0 +1,61 @@ +"""Test that DWARF types are trusted over module types""" + + + +import unittest2 + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class IncompleteModulesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.m', '// Set breakpoint 0 here.') + + @skipUnlessDarwin + @skipIf(debug_info=no_match(["gmodules"])) + def test_expr(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.runCmd( + "settings set target.clang-module-search-paths \"" + + self.getSourceDir() + + "\"") + + self.expect("expr @import myModule; 3", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["int", "3"]) + + self.expect( + "expr private_func()", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "int", + "5"]) + + self.expect("expr MY_MIN(2,3)", "#defined macro was found", + substrs=["int", "2"]) + + self.expect("expr MY_MAX(2,3)", "#undefd macro was correctly not found", + error=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/main.m new file mode 100644 index 00000000000..bfa0b06f1a1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/main.m @@ -0,0 +1,7 @@ +@import myModule; +@import minmax; + +int main(int argc, char **argv) { + public_func(); // Set breakpoint 0 here. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/minmax.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/minmax.h new file mode 100644 index 00000000000..efad1201695 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/minmax.h @@ -0,0 +1,2 @@ +#define MY_MIN(A, B) (((A) < (B)) ? (A) : (B)) +#define MY_MAX(A, B) (((A) < (B)) ? (B) : (A)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/module.map b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/module.map new file mode 100644 index 00000000000..0dd9fadb262 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/module.map @@ -0,0 +1,9 @@ +module myModule { + header "myModule.h" + export * +} + +module minmax { + header "minmax.h" + export * +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.h new file mode 100644 index 00000000000..04ec3885c83 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.h @@ -0,0 +1,5 @@ +@import minmax; + +#undef MY_MAX + +extern void public_func(); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.m new file mode 100644 index 00000000000..372a3288932 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.m @@ -0,0 +1,8 @@ +#include "myModule.h" + +void public_func() {} + +int private_func() { + return 5; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/Makefile new file mode 100644 index 00000000000..b4afe2cb3e8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/Makefile @@ -0,0 +1,7 @@ +C_SOURCES := myModule.c + +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS = $(MANDATORY_MODULE_BUILD_CFLAGS) -I$(BUILDDIR) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py new file mode 100644 index 00000000000..e2e335a1c43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py @@ -0,0 +1,38 @@ +"""Test that inline functions from modules are imported correctly""" + + + + +import unittest2 + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ModulesInlineFunctionsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"], debug_info=no_match(["gmodules"])) + def test_expr(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_to_source_breakpoint( + self, '// Set breakpoint here.', lldb.SBFileSpec('main.m')) + + self.runCmd( + "settings set target.clang-module-search-paths \"" + + self.getSourceDir() + + "\"") + + self.expect("expr @import myModule; 3", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["int", "3"]) + + self.expect("expr isInline(2)", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["4"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/main.m new file mode 100644 index 00000000000..13a5bf316ee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/main.m @@ -0,0 +1,9 @@ +@import Darwin; +@import myModule; + +int main() +{ + int a = isInline(2); + int b = notInline(); + printf("%d %d\n", a, b); // Set breakpoint here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/module.map b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/module.map new file mode 100644 index 00000000000..2ef8064d15b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/module.map @@ -0,0 +1,4 @@ +module myModule { + header "myModule.h" + export * +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.c new file mode 100644 index 00000000000..ad3c85d155e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.c @@ -0,0 +1,7 @@ +#include "myModule.h" + +int notInline() +{ + return 3; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.h new file mode 100644 index 00000000000..d50d0101f64 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.h @@ -0,0 +1,7 @@ +int notInline(); + +static __inline__ __attribute__ ((always_inline)) int isInline(int a) +{ + int b = a + a; + return b; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/Makefile new file mode 100644 index 00000000000..5d0a2209ef7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/Makefile @@ -0,0 +1,3 @@ +CFLAGS_EXTRAS = -I$(BUILDDIR) +USE_PRIVATE_MODULE_CACHE = YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/TestClangModulesUpdate.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/TestClangModulesUpdate.py new file mode 100644 index 00000000000..e36a2278daa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/TestClangModulesUpdate.py @@ -0,0 +1,65 @@ + +import unittest2 +import os +import shutil + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestClangModuleUpdate(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIf(debug_info=no_match(["gmodules"])) + def test_expr(self): + with open(self.getBuildArtifact("module.modulemap"), "w") as f: + f.write(""" + module Foo { header "f.h" } + """) + with open(self.getBuildArtifact("f.h"), "w") as f: + f.write(""" + struct Q { int i; }; + void f() {} + """) + + mod_cache = self.getBuildArtifact("private-module-cache") + if os.path.isdir(mod_cache): + shutil.rmtree(mod_cache) + d = {'OBJC_SOURCES': 'first.m'} + self.build(dictionary=d) + self.assertTrue(os.path.isdir(mod_cache), "module cache exists") + + logfile = self.getBuildArtifact("modules.log") + self.runCmd("log enable -f %s lldb module" % logfile) + target, process, _, bkpt = lldbutil.run_to_name_breakpoint(self, "main") + self.assertIn("int i", str(target.FindTypes('Q').GetTypeAtIndex(0))) + self.expect("image list -g", patterns=[r'first\.o', r'Foo.*\.pcm']) + + # Update the module. + with open(self.getBuildArtifact("f.h"), "w") as f: + f.write(""" + struct S { int i; }; + struct S getS() { struct S r = {1}; return r; } + void f() {} + """) + + # Rebuild. + d = {'OBJC_SOURCES': 'second.m'} + self.build(dictionary=d) + + # Reattach. + process.Kill() + target, process, _, _ = lldbutil.run_to_breakpoint_do_run(self, target, bkpt) + self.assertIn("int i", str(target.FindTypes('S').GetTypeAtIndex(0))) + self.expect("image list -g", patterns=[r'second\.o', r'Foo.*\.pcm']) + + # Check log file. + found = False + with open(logfile, 'r') as f: + for line in f: + if "module changed" in line and "Foo" in line: + found = True + self.assertTrue(found) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/first.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/first.m new file mode 100644 index 00000000000..bcc458ffb8e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/first.m @@ -0,0 +1,5 @@ +@import Umbrella; +int main(int argc, char **argv) { + f(); // break here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/module.modulemap b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/module.modulemap new file mode 100644 index 00000000000..c142410cd07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/module.modulemap @@ -0,0 +1,4 @@ +module Umbrella { + header "umbrella.h" + export * +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/second.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/second.m new file mode 100644 index 00000000000..bce925cb057 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/second.m @@ -0,0 +1,5 @@ +@import Umbrella; +int main() { + struct S s = getS(); // break here + return s.i; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/umbrella.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/umbrella.h new file mode 100644 index 00000000000..375d3ea2a04 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules-update/umbrella.h @@ -0,0 +1 @@ +@import Foo; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules/Makefile new file mode 100644 index 00000000000..37dd8f40a9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py new file mode 100644 index 00000000000..695eac9ee85 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py @@ -0,0 +1,79 @@ +"""Test that importing modules in Objective-C works as expected.""" + + + +import unittest2 + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCModulesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.m', '// Set breakpoint 0 here.') + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + def test_expr(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.expect("expr @import Darwin; 3", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["int", "3"]) + + self.expect("expr getpid()", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["pid_t"]) + + self.expect( + "expr @import Foundation; 4", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "int", + "4"]) + + # Type lookup should still work and print something reasonable + # for types from the module. + self.expect("type lookup NSObject", substrs=["instanceMethod"]) + + self.expect("expr string.length", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["NSUInteger", "5"]) + + self.expect("expr array.count", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["NSUInteger", "3"]) + + self.expect( + "p *[NSURL URLWithString:@\"http://lldb.llvm.org\"]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "NSURL", + "isa", + "_urlString"]) + + self.expect( + "p [NSURL URLWithString:@\"http://lldb.llvm.org\"].scheme", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["http"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules/main.m new file mode 100644 index 00000000000..99b50f9620d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/modules/main.m @@ -0,0 +1,12 @@ +#import <Foundation/Foundation.h> + +int main() +{ + @autoreleasepool + { + NSString *string = @"Hello"; + NSArray *array = @[ @1, @2, @3 ]; + + NSLog(@"Stop here"); // Set breakpoint 0 here. + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/Makefile new file mode 100644 index 00000000000..e8a4b0cc29c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/Makefile @@ -0,0 +1,4 @@ +OBJCXX_SOURCES := main.mm +LD_EXTRAS = -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py new file mode 100644 index 00000000000..344af99f589 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py @@ -0,0 +1,33 @@ +""" +Make sure that ivars of Objective-C++ classes are visible in LLDB. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCXXTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_break(self): + """Test ivars of Objective-C++ classes""" + if self.getArchitecture() == 'i386': + self.skipTest("requires Objective-C 2.0 runtime") + + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp( + self, 'breakpoint 1', num_expected_locations=1) + + self.runCmd("run", RUN_SUCCEEDED) + + self.expect("expr f->f", "Found ivar in class", + substrs=["= 3"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/main.mm new file mode 100644 index 00000000000..50d2f0a8df3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc++/main.mm @@ -0,0 +1,19 @@ +#include <Foundation/NSObject.h> + +@interface F : NSObject +@end + +@implementation F +{ +@public + int f; +} + +@end + +int main(int argc, char* argv[]) +{ + F* f = [F new]; + f->f = 3; + return 0; // breakpoint 1 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/Makefile new file mode 100644 index 00000000000..ad28ecfeb5d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS = -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py new file mode 100644 index 00000000000..8f974f03838 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py @@ -0,0 +1,64 @@ +""" +Use lldb Python API to test base class resolution for ObjC classes +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCDynamicValueTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + self.line = line_number('main.m', '// Set breakpoint here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_get_baseclass(self): + """Test fetching ObjC dynamic values.""" + if self.getArchitecture() == 'i386': + # rdar://problem/9946499 + self.skipTest("Dynamic types for ObjC V1 runtime not implemented") + + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target from the debugger. + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set up our breakpoints: + + target.BreakpointCreateByLocation('main.m', self.line) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + var = self.frame().FindVariable("foo") + var_ptr_type = var.GetType() + var_pte_type = var_ptr_type.GetPointeeType() + self.assertTrue( + var_ptr_type.GetNumberOfDirectBaseClasses() == 1, + "Foo * has one base class") + self.assertTrue( + var_pte_type.GetNumberOfDirectBaseClasses() == 1, + "Foo has one base class") + + self.assertTrue(var_ptr_type.GetDirectBaseClassAtIndex( + 0).IsValid(), "Foo * has a valid base class") + self.assertTrue(var_pte_type.GetDirectBaseClassAtIndex( + 0).IsValid(), "Foo * has a valid base class") + + self.assertTrue(var_ptr_type.GetDirectBaseClassAtIndex(0).GetName() == var_pte_type.GetDirectBaseClassAtIndex( + 0).GetName(), "Foo and its pointer type don't agree on their base class") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/main.m new file mode 100644 index 00000000000..3ec78fd0bd6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/main.m @@ -0,0 +1,22 @@ +#import <Foundation/Foundation.h> + +@interface Foo : NSObject {} + +-(id) init; + +@end + +@implementation Foo + +-(id) init +{ + return self = [super init]; +} +@end +int main () +{ + Foo *foo = [Foo new]; + NSLog(@"a"); // Set breakpoint here. + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py new file mode 100644 index 00000000000..d07b827e771 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py @@ -0,0 +1,61 @@ +"""Test that the expression parser doesn't get confused by 'id' and 'Class'""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCBuiltinTypes(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "main.cpp" + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + #<rdar://problem/10591460> [regression] Can't print ivar value: error: reference to 'id' is ambiguous + def test_with_python_api(self): + """Test expression parser respect for ObjC built-in types.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) + self.assertTrue(bpt, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) + + # Make sure we stopped at the first breakpoint. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the class method we've + # stopped in. + frame = thread_list[0].GetFrameAtIndex(0) + self.assertTrue(frame, "Got a valid frame 0 frame.") + + self.expect("expr (foo)", patterns=["\(ns::id\) \$.* = 0"]) + + self.expect("expr id my_id = 0; my_id", patterns=["\(id\) \$.* = nil"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/main.cpp new file mode 100644 index 00000000000..6dd8cbc6e9f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/main.cpp @@ -0,0 +1,9 @@ +namespace ns { + typedef int id; +}; + +int main() +{ + ns::id foo = 0; + return foo; // Set breakpoint here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/Makefile new file mode 100644 index 00000000000..afecbf96948 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py new file mode 100644 index 00000000000..ac2dc2a3899 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py @@ -0,0 +1,90 @@ +""" +Use lldb Python API to make sure the dynamic checkers are doing their jobs. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCCheckerTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # Find the line number to break for main.c. + self.source_name = 'main.m' + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_objc_checker(self): + """Test that checkers catch unrecognized selectors""" + if self.getArchitecture() == 'i386': + self.skipTest("requires Objective-C 2.0 runtime") + + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target from the debugger. + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set up our breakpoints: + + main_bkpt = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here.", lldb.SBFileSpec(self.source_name)) + self.assertTrue(main_bkpt and + main_bkpt.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, main_bkpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + + # + # The class Simple doesn't have a count method. Make sure that we don't + # actually try to send count but catch it as an unrecognized selector. + + frame = thread.GetFrameAtIndex(0) + expr_value = frame.EvaluateExpression("(int) [my_simple count]", False) + expr_error = expr_value.GetError() + + self.assertTrue(expr_error.Fail()) + + # Make sure the call produced no NSLog stdout. + stdout = process.GetSTDOUT(100) + self.assertTrue(stdout is None or (len(stdout) == 0)) + + # Make sure the error is helpful: + err_string = expr_error.GetCString() + self.assertTrue("selector" in err_string) + + # + # Check that we correctly insert the checker for an + # ObjC method with the struct return convention. + # Getting this wrong would cause us to call the checker + # with the wrong arguments, and the checker would crash + # So I'm just checking "expression runs successfully" here: + # + expr_value = frame.EvaluateExpression("[my_simple getBigStruct]", False) + expr_error = expr_value.GetError() + + self.assertTrue(expr_error.Success()) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/main.m new file mode 100644 index 00000000000..de73e688f25 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-checker/main.m @@ -0,0 +1,47 @@ +#import <Foundation/Foundation.h> + +// This should be a big enough struct that it will force +// the struct return convention: +typedef struct BigStruct { + float a, b, c, d, e, f, g, h, i, j, k, l; +} BigStruct; + + +@interface Simple : NSObject +{ + int _value; +} +- (int) value; +- (void) setValue: (int) newValue; +- (BigStruct) getBigStruct; +@end + +@implementation Simple +- (int) value +{ + return _value; +} + +- (void) setValue: (int) newValue +{ + _value = newValue; +} + +- (BigStruct) getBigStruct +{ + BigStruct big_struct = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, + 7.0, 8.0, 9.0, 10.0, 11.0, 12.0}; + return big_struct; +} +@end + +int main () +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + Simple *my_simple = [[Simple alloc] init]; + my_simple.value = 20; + // Set a breakpoint here. + NSLog (@"Object has value: %d.", my_simple.value); + [pool drain]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/Makefile new file mode 100644 index 00000000000..e6db3dee37b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := class.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py new file mode 100644 index 00000000000..46cddd635c0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py @@ -0,0 +1,66 @@ +"""Test calling functions in class methods.""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCClassMethod(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "class.m" + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test calling functions in class methods.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) + self.assertTrue(bpt, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) + + # Make sure we stopped at the first breakpoint. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the class method we've + # stopped in. + frame = thread_list[0].GetFrameAtIndex(0) + self.assertTrue(frame, "Got a valid frame 0 frame.") + + cmd_value = frame.EvaluateExpression( + "(int)[Foo doSomethingWithString:@\"Hello\"]") + if self.TraceOn(): + if cmd_value.IsValid(): + print("cmd_value is valid") + print("cmd_value has the value %d" % cmd_value.GetValueAsUnsigned()) + self.assertTrue(cmd_value.IsValid()) + self.assertTrue(cmd_value.GetValueAsUnsigned() == 5) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/class.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/class.m new file mode 100644 index 00000000000..18a2c2729be --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-class-method/class.m @@ -0,0 +1,24 @@ +#import <Foundation/Foundation.h> + +@interface Foo : NSObject ++(int) doSomethingWithString: (NSString *) string; +-(int) doSomethingInstance: (NSString *) string; +@end + +@implementation Foo ++(int) doSomethingWithString: (NSString *) string +{ + NSLog (@"String is: %@.", string); + return [string length]; +} + +-(int) doSomethingInstance: (NSString *)string +{ + return [Foo doSomethingWithString:string]; +} +@end + +int main() +{ + return 0; // Set breakpoint here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/.categories new file mode 100644 index 00000000000..9526bab96fb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/.categories @@ -0,0 +1 @@ +dyntype diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/Makefile new file mode 100644 index 00000000000..9ff3ce6e4a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/Makefile @@ -0,0 +1,5 @@ +OBJC_SOURCES := main.m + +include Makefile.rules + +LD_EXTRAS = -framework Foundation diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py new file mode 100644 index 00000000000..1851bc33264 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py @@ -0,0 +1,90 @@ +""" +Test that we are able to properly report a usable dynamic type +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class ObjCDynamicSBTypeTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to break inside main(). + self.main_source = "main.m" + self.line = line_number(self.main_source, '// Set breakpoint here.') + + @skipIf(archs="i[3-6]86") + def test_dyn(self): + """Test that we are able to properly report a usable dynamic type.""" + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + v_object = self.frame().FindVariable( + "object").GetDynamicValue(lldb.eDynamicCanRunTarget) + v_base = self.frame().FindVariable( + "base").GetDynamicValue(lldb.eDynamicCanRunTarget) + self.assertTrue( + v_object.GetTypeName() == "MyDerivedClass *", + "The NSObject is properly type-named") + self.assertTrue( + v_base.GetTypeName() == "MyDerivedClass *", + "The Base is properly type-named") + object_type = v_object.GetType() + base_type = v_base.GetType() + self.assertTrue( + object_type.GetName() == "MyDerivedClass *", + "The dynamic SBType for NSObject is for the correct type") + self.assertTrue( + base_type.GetName() == "MyDerivedClass *", + "The dynamic SBType for Base is for the correct type") + object_pointee_type = object_type.GetPointeeType() + base_pointee_type = base_type.GetPointeeType() + self.assertTrue( + object_pointee_type.GetName() == "MyDerivedClass", + "The dynamic type for NSObject figures out its pointee type just fine") + self.assertTrue( + base_pointee_type.GetName() == "MyDerivedClass", + "The dynamic type for Base figures out its pointee type just fine") + + self.assertTrue( + object_pointee_type.GetDirectBaseClassAtIndex(0).GetName() == "MyBaseClass", + "The dynamic type for NSObject can go back to its base class") + self.assertTrue( + base_pointee_type.GetDirectBaseClassAtIndex(0).GetName() == "MyBaseClass", + "The dynamic type for Base can go back to its base class") + + self.assertTrue(object_pointee_type.GetDirectBaseClassAtIndex(0).GetType().GetDirectBaseClassAtIndex( + 0).GetName() == "NSObject", "The dynamic type for NSObject can go up the hierarchy") + self.assertTrue(base_pointee_type.GetDirectBaseClassAtIndex(0).GetType().GetDirectBaseClassAtIndex( + 0).GetName() == "NSObject", "The dynamic type for Base can go up the hierarchy") + + self.assertTrue( + object_pointee_type.GetNumberOfFields() == 2, + "The dynamic type for NSObject has 2 fields") + self.assertTrue( + base_pointee_type.GetNumberOfFields() == 2, + "The dynamic type for Base has 2 fields") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/main.m new file mode 100644 index 00000000000..f3587b52cd5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/main.m @@ -0,0 +1,53 @@ +#import <Foundation/Foundation.h> + +@interface MyBaseClass : NSObject +{} +-(id) init; +-(int) getInt; +@end + +@implementation MyBaseClass +- (id) init { + return (self = [super init]); +} + +- (int) getInt { + return 1; +} +@end + +@interface MyDerivedClass : MyBaseClass +{ + int x; + int y; +} +-(id) init; +-(int) getInt; +@end + +@implementation MyDerivedClass +- (id) init { + self = [super init]; + if (self) { + self-> x = 0; + self->y = 1; + } + return self; +} + +- (int) getInt { + y = x++; + return x; +} +@end + + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + NSObject* object = [[MyDerivedClass alloc] init]; + MyBaseClass* base = [[MyDerivedClass alloc] init]; + [pool release]; // Set breakpoint here. + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/Makefile new file mode 100644 index 00000000000..a34977712c3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := dynamic-value.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py new file mode 100644 index 00000000000..5a6ec4ed39d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py @@ -0,0 +1,207 @@ +""" +Use lldb Python API to test dynamic values in ObjC +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCDynamicValueTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # Find the line number to break for main.c. + + self.source_name = 'dynamic-value.m' + self.set_property_line = line_number( + self.source_name, + '// This is the line in setProperty, make sure we step to here.') + self.handle_SourceBase = line_number( + self.source_name, '// Break here to check dynamic values.') + self.main_before_setProperty_line = line_number( + self.source_name, '// Break here to see if we can step into real method.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + @expectedFailureDarwin("llvm.org/pr20271 rdar://18684107") + def test_get_objc_dynamic_vals(self): + """Test fetching ObjC dynamic values.""" + if self.getArchitecture() == 'i386': + # rdar://problem/9946499 + self.skipTest("Dynamic types for ObjC V1 runtime not implemented") + + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target from the debugger. + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set up our breakpoints: + + handle_SourceBase_bkpt = target.BreakpointCreateByLocation( + self.source_name, self.handle_SourceBase) + self.assertTrue(handle_SourceBase_bkpt and + handle_SourceBase_bkpt.GetNumLocations() == 1, + VALID_BREAKPOINT) + + main_before_setProperty_bkpt = target.BreakpointCreateByLocation( + self.source_name, self.main_before_setProperty_line) + self.assertTrue(main_before_setProperty_bkpt and + main_before_setProperty_bkpt.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, main_before_setProperty_bkpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + + # + # At this point, myObserver has a Source pointer that is actually a KVO swizzled SourceDerived + # make sure we can get that properly: + + frame = thread.GetFrameAtIndex(0) + myObserver = frame.FindVariable( + 'myObserver', lldb.eDynamicCanRunTarget) + self.assertTrue(myObserver) + myObserver_source = myObserver.GetChildMemberWithName( + '_source', lldb.eDynamicCanRunTarget) + self.examine_SourceDerived_ptr(myObserver_source) + + # + # Make sure a static value can be correctly turned into a dynamic + # value. + + frame = thread.GetFrameAtIndex(0) + myObserver_static = frame.FindVariable( + 'myObserver', lldb.eNoDynamicValues) + self.assertTrue(myObserver_static) + myObserver = myObserver_static.GetDynamicValue( + lldb.eDynamicCanRunTarget) + myObserver_source = myObserver.GetChildMemberWithName( + '_source', lldb.eDynamicCanRunTarget) + self.examine_SourceDerived_ptr(myObserver_source) + + # The "frame var" code uses another path to get into children, so let's + # make sure that works as well: + + result = lldb.SBCommandReturnObject() + + self.expect( + 'frame var -d run-target myObserver->_source', + 'frame var finds its way into a child member', + patterns=['\(SourceDerived \*\)']) + + # check that our ObjC GetISA() does a good job at hiding KVO swizzled + # classes + + self.expect( + 'frame var -d run-target myObserver->_source -T', + 'the KVO-ed class is hidden', + substrs=['SourceDerived']) + + self.expect( + 'frame var -d run-target myObserver->_source -T', + 'the KVO-ed class is hidden', + matching=False, + substrs=['NSKVONotify']) + + # This test is not entirely related to the main thrust of this test case, but since we're here, + # try stepping into setProperty, and make sure we get into the version + # in Source: + + thread.StepInto() + + threads = lldbutil.get_stopped_threads( + process, lldb.eStopReasonPlanComplete) + self.assertTrue(len(threads) == 1) + line_entry = threads[0].GetFrameAtIndex(0).GetLineEntry() + + self.assertEqual(line_entry.GetLine(), self.set_property_line) + self.assertEqual( + line_entry.GetFileSpec().GetFilename(), + self.source_name) + + # Okay, back to the main business. Continue to the handle_SourceBase + # and make sure we get the correct dynamic value. + + threads = lldbutil.continue_to_breakpoint( + process, handle_SourceBase_bkpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + + frame = thread.GetFrameAtIndex(0) + + # Get "object" using FindVariable: + + noDynamic = lldb.eNoDynamicValues + useDynamic = lldb.eDynamicCanRunTarget + + object_static = frame.FindVariable('object', noDynamic) + object_dynamic = frame.FindVariable('object', useDynamic) + + # Delete this object to make sure that this doesn't cause havoc with + # the dynamic object that depends on it. + del (object_static) + + self.examine_SourceDerived_ptr(object_dynamic) + + # Get "this" using FindValue, make sure that works too: + object_static = frame.FindValue( + 'object', lldb.eValueTypeVariableArgument, noDynamic) + object_dynamic = frame.FindValue( + 'object', lldb.eValueTypeVariableArgument, useDynamic) + del (object_static) + self.examine_SourceDerived_ptr(object_dynamic) + + # Get "this" using the EvaluateExpression: + object_static = frame.EvaluateExpression('object', noDynamic) + object_dynamic = frame.EvaluateExpression('object', useDynamic) + del (object_static) + self.examine_SourceDerived_ptr(object_dynamic) + + # Continue again to the handle_SourceBase and make sure we get the correct dynamic value. + # This one looks exactly the same, but in fact this is an "un-KVO'ed" version of SourceBase, so + # its isa pointer points to SourceBase not NSKVOSourceBase or + # whatever... + + threads = lldbutil.continue_to_breakpoint( + process, handle_SourceBase_bkpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + + frame = thread.GetFrameAtIndex(0) + + # Get "object" using FindVariable: + + object_static = frame.FindVariable('object', noDynamic) + object_dynamic = frame.FindVariable('object', useDynamic) + + # Delete this object to make sure that this doesn't cause havoc with + # the dynamic object that depends on it. + del (object_static) + + self.examine_SourceDerived_ptr(object_dynamic) + + def examine_SourceDerived_ptr(self, object): + self.assertTrue(object) + self.assertTrue(object.GetTypeName().find('SourceDerived') != -1) + derivedValue = object.GetChildMemberWithName('_derivedValue') + self.assertTrue(derivedValue) + self.assertTrue(int(derivedValue.GetValue(), 0) == 30) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/dynamic-value.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/dynamic-value.m new file mode 100644 index 00000000000..2bcb76b1d9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/dynamic-value.m @@ -0,0 +1,147 @@ +#import <Foundation/Foundation.h> + +// SourceBase will be the base class of Source. We'll pass a Source object into a +// function as a SourceBase, and then see if the dynamic typing can get us through the KVO +// goo and all the way back to Source. + +@interface SourceBase: NSObject +{ + uint32_t _value; +} +- (SourceBase *) init; +- (uint32_t) getValue; +@end + +@implementation SourceBase +- (SourceBase *) init +{ + [super init]; + _value = 10; + return self; +} +- (uint32_t) getValue +{ + return _value; +} +@end + +// Source is a class that will be observed by the Observer class below. +// When Observer sets itself up to observe this property (in initWithASource) +// the KVO system will overwrite the "isa" pointer of the object with the "kvo'ed" +// one. + +@interface Source : SourceBase +{ + int _property; +} +- (Source *) init; +- (void) setProperty: (int) newValue; +@end + +@implementation Source +- (Source *) init +{ + [super init]; + _property = 20; + return self; +} +- (void) setProperty: (int) newValue +{ + _property = newValue; // This is the line in setProperty, make sure we step to here. +} +@end + +@interface SourceDerived : Source +{ + int _derivedValue; +} +- (SourceDerived *) init; +- (uint32_t) getValue; +@end + +@implementation SourceDerived +- (SourceDerived *) init +{ + [super init]; + _derivedValue = 30; + return self; +} +- (uint32_t) getValue +{ + return _derivedValue; +} +@end + +// Observer is the object that will watch Source and cause KVO to swizzle it... + +@interface Observer : NSObject +{ + Source *_source; +} ++ (Observer *) observerWithSource: (Source *) source; +- (Observer *) initWithASource: (Source *) source; +- (void) observeValueForKeyPath: (NSString *) path + ofObject: (id) object + change: (NSDictionary *) change + context: (void *) context; +@end + +@implementation Observer + ++ (Observer *) observerWithSource: (Source *) inSource; +{ + Observer *retval; + + retval = [[Observer alloc] initWithASource: inSource]; + return retval; +} + +- (Observer *) initWithASource: (Source *) source +{ + [super init]; + _source = source; + [_source addObserver: self + forKeyPath: @"property" + options: (NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) + context: NULL]; + return self; +} + +- (void) observeValueForKeyPath: (NSString *) path + ofObject: (id) object + change: (NSDictionary *) change + context: (void *) context +{ + printf ("Observer function called.\n"); + return; +} +@end + +uint32_t +handle_SourceBase (SourceBase *object) +{ + return [object getValue]; // Break here to check dynamic values. +} + +int main () +{ + Source *mySource; + Observer *myObserver; + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + mySource = [[SourceDerived alloc] init]; + myObserver = [Observer observerWithSource: mySource]; + + [mySource setProperty: 5]; // Break here to see if we can step into real method. + + uint32_t return_value = handle_SourceBase (mySource); + + SourceDerived *unwatchedSource = [[SourceDerived alloc] init]; + + return_value = handle_SourceBase (unwatchedSource); + + [pool release]; + return 0; + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-foundation-dictionary-empty/TestNSDictionary0.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-foundation-dictionary-empty/TestNSDictionary0.py new file mode 100644 index 00000000000..562d9ae01e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-foundation-dictionary-empty/TestNSDictionary0.py @@ -0,0 +1,7 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, + decorators.skipIfWindows, decorators.skipIfNetBSD]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-foundation-dictionary-empty/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-foundation-dictionary-empty/main.m new file mode 100644 index 00000000000..14a792b3776 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-foundation-dictionary-empty/main.m @@ -0,0 +1,7 @@ +#import <Foundation/Foundation.h> + +int main(void) +{ + NSDictionary *emptyDictionary = [[NSDictionary alloc] init]; + return 0; //% self.expect("frame var emptyDictionary", substrs = ["0 key/value pairs"]); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/Makefile new file mode 100644 index 00000000000..5408f4199f2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := objc-ivar-offsets.m main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py new file mode 100644 index 00000000000..749c7137dc9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py @@ -0,0 +1,83 @@ +"""Test printing ObjC objects that use unbacked properties - so that the static ivar offsets are incorrect.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCIvarOffsets(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "main.m" + self.stop_line = line_number( + self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test printing ObjC objects that use unbacked properties""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation( + self.main_source, self.stop_line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, "Created a process.") + self.assertTrue( + process.GetState() == lldb.eStateStopped, + "Stopped it too.") + + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) + thread = thread_list[0] + + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame, "frame 0 is valid") + + mine = thread.GetFrameAtIndex(0).FindVariable("mine") + self.assertTrue(mine, "Found local variable mine.") + + # Test the value object value for BaseClass->_backed_int + + error = lldb.SBError() + + mine_backed_int = mine.GetChildMemberWithName("_backed_int") + self.assertTrue( + mine_backed_int, + "Found mine->backed_int local variable.") + backed_value = mine_backed_int.GetValueAsSigned(error) + self.assertTrue(error.Success()) + self.assertTrue(backed_value == 1111) + + # Test the value object value for DerivedClass->_derived_backed_int + + mine_derived_backed_int = mine.GetChildMemberWithName( + "_derived_backed_int") + self.assertTrue(mine_derived_backed_int, + "Found mine->derived_backed_int local variable.") + derived_backed_value = mine_derived_backed_int.GetValueAsSigned(error) + self.assertTrue(error.Success()) + self.assertTrue(derived_backed_value == 3333) + + # Make sure we also get bit-field offsets correct: + + mine_flag2 = mine.GetChildMemberWithName("flag2") + self.assertTrue(mine_flag2, "Found mine->flag2 local variable.") + flag2_value = mine_flag2.GetValueAsUnsigned(error) + self.assertTrue(error.Success()) + self.assertTrue(flag2_value == 7) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/main.m new file mode 100644 index 00000000000..41943f48aef --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/main.m @@ -0,0 +1,15 @@ +#include "objc-ivar-offsets.h" + +int +main () +{ + DerivedClass *mine = [[DerivedClass alloc] init]; + mine.backed_int = 1111; + mine.unbacked_int = 2222; + mine.derived_backed_int = 3333; + mine.derived_unbacked_int = 4444; + mine->flag1 = 1; + mine->flag2 = 7; + + return 0; // Set breakpoint here. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.h new file mode 100644 index 00000000000..99bbd427b06 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.h @@ -0,0 +1,27 @@ +#import <Foundation/Foundation.h> + +@interface BaseClass : NSObject +{ + int _backed_int; +#if !__OBJC2__ + int _unbacked_int; +#endif +} +@property int backed_int; +@property int unbacked_int; +@end + +@interface DerivedClass : BaseClass +{ + int _derived_backed_int; +#if !__OBJC2__ + int _derived_unbacked_int; +#endif + @public + uint32_t flag1 : 1; + uint32_t flag2 : 3; +} + +@property int derived_backed_int; +@property int derived_unbacked_int; +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.m new file mode 100644 index 00000000000..db87adea3d1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.m @@ -0,0 +1,19 @@ +#import "objc-ivar-offsets.h" + +@implementation BaseClass +@synthesize backed_int = _backed_int; +#if __OBJC2__ +@synthesize unbacked_int; +#else +@synthesize unbacked_int = _unbacked_int; +#endif +@end + +@implementation DerivedClass +@synthesize derived_backed_int = _derived_backed_int; +#if __OBJC2__ +@synthesize derived_unbacked_int; +#else +@synthesize derived_unbacked_int = _derived_unbacked_int; +#endif +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py new file mode 100644 index 00000000000..562d9ae01e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py @@ -0,0 +1,7 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, + decorators.skipIfWindows, decorators.skipIfNetBSD]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/main.m new file mode 100644 index 00000000000..aa6c4715c33 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/main.m @@ -0,0 +1,33 @@ +#import <Foundation/Foundation.h> + +@protocol MyProtocol +-(void)aMethod; +@end + +@interface MyClass : NSObject { + id <MyProtocol> myId; + NSObject <MyProtocol> *myObject; +}; + +-(void)doSomething; + +@end + +@implementation MyClass + +-(void)doSomething +{ + NSLog(@"Hello"); //% self.expect("expression -- myId", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["id"]); + //% self.expect("expression -- myObject", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["NSObject"]); +} + +@end + +int main () +{ + @autoreleasepool + { + MyClass *c = [MyClass alloc]; + [c doSomething]; + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/Makefile new file mode 100644 index 00000000000..a218ce37e61 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/Makefile @@ -0,0 +1,13 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -lobjc -framework Foundation + +all: a.out.stripped + +a.out.stripped: a.out.dSYM + strip -o a.out.stripped a.out + +clean:: + rm -f a.out.stripped + rm -rf a.out.stripped.dSYM + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py new file mode 100644 index 00000000000..12a22f6b903 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py @@ -0,0 +1,67 @@ +"""Test printing ObjC objects that use unbacked properties - so that the static ivar offsets are incorrect.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCIvarStripped(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "main.m" + self.stop_line = line_number( + self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + @skipIf( + debug_info=no_match("dsym"), + bugnumber="This test requires a stripped binary and a dSYM") + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test that we can find stripped Objective-C ivars in the runtime""" + self.build() + exe = self.getBuildArtifact("a.out.stripped") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.dbg.HandleCommand("add-dsym "+self.getBuildArtifact("a.out.dSYM")) + + breakpoint = target.BreakpointCreateByLocation( + self.main_source, self.stop_line) + self.assertTrue( + breakpoint.IsValid() and breakpoint.GetNumLocations() > 0, + VALID_BREAKPOINT) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, "Created a process.") + self.assertTrue( + process.GetState() == lldb.eStateStopped, + "Stopped it too.") + + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) + thread = thread_list[0] + + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame, "frame 0 is valid") + + # Test the expression for mc->_foo + + error = lldb.SBError() + + ivar = frame.EvaluateExpression("(mc->_foo)") + self.assertTrue(ivar, "Got result for mc->_foo") + ivar_value = ivar.GetValueAsSigned(error) + self.assertTrue(error.Success()) + self.assertTrue(ivar_value == 3) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/main.m new file mode 100644 index 00000000000..ed9c1d9ec42 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/main.m @@ -0,0 +1,33 @@ +#import <Foundation/Foundation.h> + +@interface MyClass : NSObject { +@public + int _foo; +}; + +-(id)init; +@end + +@implementation MyClass + +-(id)init +{ + if ([super init]) + { + _foo = 3; + } + + return self; +} + +@end + +int main () +{ + @autoreleasepool + { + MyClass *mc = [[MyClass alloc] init]; + + NSLog(@"%d", mc->_foo); // Set breakpoint here. + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/Makefile new file mode 100644 index 00000000000..37dd8f40a9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/ObjCNewSyntaxTest.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/ObjCNewSyntaxTest.py new file mode 100644 index 00000000000..5fa9336b731 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/ObjCNewSyntaxTest.py @@ -0,0 +1,29 @@ +"""Test that the Objective-C syntax for dictionary/array literals and indexing works""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCNewSyntaxTest(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def runToBreakpoint(self): + self.build() + self.target, process, thread, bkpt = lldbutil.run_to_source_breakpoint( + self, '// Set breakpoint 0 here.', lldb.SBFileSpec( + 'main.m', False)) + + # The stop reason of the thread should be breakpoint. + self.expect( + "thread list", + STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect( + "breakpoint list -f", + BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxArray.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxArray.py new file mode 100644 index 00000000000..cf638c7a108 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxArray.py @@ -0,0 +1,58 @@ +"""Test that the Objective-C syntax for dictionary/array literals and indexing works""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCNewSyntaxTest import ObjCNewSyntaxTest + + +class ObjCNewSyntaxTestCaseArray(ObjCNewSyntaxTest): + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_read_array(self): + self.runToBreakpoint() + + self.expect( + "expr --object-description -- immutable_array[0]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo"]) + + self.expect( + "expr --object-description -- mutable_array[0]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["foo"]) + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_update_array(self): + self.runToBreakpoint() + + self.expect( + "expr --object-description -- mutable_array[0] = @\"bar\"", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["bar"]) + + self.expect( + "expr --object-description -- mutable_array[0]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["bar"]) + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_array_literal(self): + self.runToBreakpoint() + + self.expect( + "expr --object-description -- @[ @\"foo\", @\"bar\" ]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "NSArray", + "foo", + "bar"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxDictionary.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxDictionary.py new file mode 100644 index 00000000000..5291b46da2f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxDictionary.py @@ -0,0 +1,57 @@ +"""Test that the Objective-C syntax for dictionary/array literals and indexing works""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCNewSyntaxTest import ObjCNewSyntaxTest + + +class ObjCNewSyntaxTestCaseDictionary(ObjCNewSyntaxTest): + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_read_dictionary(self): + self.runToBreakpoint() + + self.expect( + "expr --object-description -- immutable_dictionary[@\"key\"]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["value"]) + + self.expect( + "expr --object-description -- mutable_dictionary[@\"key\"]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["value"]) + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_update_dictionary(self): + self.runToBreakpoint() + + self.expect( + "expr --object-description -- mutable_dictionary[@\"key\"] = @\"object\"", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["object"]) + + self.expect( + "expr --object-description -- mutable_dictionary[@\"key\"]", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["object"]) + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_dictionary_literal(self): + self.runToBreakpoint() + + self.expect( + "expr --object-description -- @{ @\"key\" : @\"object\" }", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "key", + "object"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxLiteral.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxLiteral.py new file mode 100644 index 00000000000..e17343bed72 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxLiteral.py @@ -0,0 +1,78 @@ +"""Test that the Objective-C syntax for dictionary/array literals and indexing works""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +from ObjCNewSyntaxTest import ObjCNewSyntaxTest + + +class ObjCNewSyntaxTestCaseLiteral(ObjCNewSyntaxTest): + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_char_literal(self): + self.runToBreakpoint() + + self.expect("expr --object-description -- @'a'", + VARIABLES_DISPLAYED_CORRECTLY, substrs=[str(ord('a'))]) + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_integer_literals(self): + self.runToBreakpoint() + + self.expect( + "expr --object-description -- @1", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) + + self.expect( + "expr --object-description -- @1l", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) + + self.expect( + "expr --object-description -- @1ul", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) + + self.expect( + "expr --object-description -- @1ll", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) + + self.expect( + "expr --object-description -- @1ull", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["1"]) + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_float_literal(self): + self.runToBreakpoint() + + self.expect("expr -- @123.45", VARIABLES_DISPLAYED_CORRECTLY, + substrs=["NSNumber", "123.45"]) + + @skipUnlessDarwin + @skipIf(macos_version=["<", "10.12"]) + @expectedFailureAll(archs=["i[3-6]86"]) + def test_expressions_in_literals(self): + self.runToBreakpoint() + + self.expect( + "expr --object-description -- @( 1 + 3 )", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=["4"]) + self.expect( + "expr -- @((char*)\"Hello world\" + 6)", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "NSString", + "world"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/main.m new file mode 100644 index 00000000000..d77ba5b10de --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/main.m @@ -0,0 +1,21 @@ +#import <Foundation/Foundation.h> + +int main() +{ + @autoreleasepool + { + // NSArrays + NSArray *immutable_array = @[ @"foo", @"bar" ]; + NSMutableArray *mutable_array = [NSMutableArray arrayWithCapacity:2]; + [mutable_array addObjectsFromArray:immutable_array]; + + // NSDictionaries + NSDictionary *immutable_dictionary = @{ @"key" : @"value" }; + NSMutableDictionary *mutable_dictionary = [NSMutableDictionary dictionaryWithCapacity:1]; + [mutable_dictionary addEntriesFromDictionary:immutable_dictionary]; + + NSNumber *one = @1; + + NSLog(@"Stop here"); // Set breakpoint 0 here. + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/Makefile new file mode 100644 index 00000000000..5fb128dcc7e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + +CFLAGS ?= -arch $(ARCH) -g -O2 +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py new file mode 100644 index 00000000000..6209f14e7e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py @@ -0,0 +1,72 @@ +""" +Test that objective-c expression parser continues to work for optimized build. + +Fixed a bug in the expression parser where the 'this' +or 'self' variable was not properly read if the compiler +optimized it into a register. +""" + + + +import lldb +import re + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +# rdar://problem/9087739 +# test failure: objc_optimized does not work for "-C clang -A i386" + + +@skipUnlessDarwin +class ObjcOptimizedTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + myclass = "MyClass" + mymethod = "description" + method_spec = "-[%s %s]" % (myclass, mymethod) + + def test_break(self): + """Test 'expr member' continues to work for optimized build.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_symbol( + self, + self.method_spec, + num_expected_locations=1, + sym_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + self.expect( + "thread backtrace", + STOPPED_DUE_TO_BREAKPOINT, + substrs=["stop reason = breakpoint"], + patterns=[ + "frame.*0:.*%s %s" % + (self.myclass, + self.mymethod)]) + + self.expect('expression member', + startstr="(int) $0 = 5") + + # <rdar://problem/12693963> + interp = self.dbg.GetCommandInterpreter() + result = lldb.SBCommandReturnObject() + interp.HandleCommand('frame variable self', result) + output = result.GetOutput() + + desired_pointer = "0x0" + + mo = re.search("0x[0-9a-f]+", output) + + if mo: + desired_pointer = mo.group(0) + + self.expect('expression (self)', + substrs=[("(%s *) $1 = " % self.myclass), desired_pointer]) + + self.expect('expression self->non_member', error=True, + substrs=["does not have a member named 'non_member'"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/main.m new file mode 100644 index 00000000000..df88eea0f86 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-optimized/main.m @@ -0,0 +1,44 @@ +#import <Foundation/Foundation.h> + +@interface MyClass : NSObject { + int member; +} + +- (id)initWithMember:(int)_member; +- (NSString*)description; +@end + +@implementation MyClass + +- (id)initWithMember:(int)_member +{ + if (self = [super init]) + { + member = _member; + } + return self; +} + +- (void)dealloc +{ + [super dealloc]; +} + +// Set a breakpoint on '-[MyClass description]' and test expressions: expr member +- (NSString *)description +{ + return [NSString stringWithFormat:@"%d", member]; +} +@end + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + MyClass *my_object = [[MyClass alloc] initWithMember:5]; + + NSLog(@"MyObject %@", [my_object description]); + + [pool release]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/Makefile new file mode 100644 index 00000000000..afecbf96948 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py new file mode 100644 index 00000000000..3092c3f086a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py @@ -0,0 +1,135 @@ +""" +Use lldb Python API to verify that expression evaluation for property references uses the correct getters and setters +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCPropertyTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # Find the line number to break for main.c. + self.source_name = 'main.m' + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_objc_properties(self): + """Test that expr uses the correct property getters and setters""" + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target from the debugger. + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set up our breakpoints: + + main_bkpt = target.BreakpointCreateBySourceRegex( + "Set a breakpoint here.", lldb.SBFileSpec(self.source_name)) + self.assertTrue(main_bkpt and + main_bkpt.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, main_bkpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + frame = thread.GetFrameAtIndex(0) + + mine = frame.FindVariable("mine") + self.assertTrue(mine.IsValid()) + access_count = mine.GetChildMemberWithName("_access_count") + self.assertTrue(access_count.IsValid()) + start_access_count = access_count.GetValueAsUnsigned(123456) + self.assertTrue(start_access_count != 123456) + + # + # The first set of tests test calling the getter & setter of + # a property that actually only has a getter & setter and no + # @property. + # + nonexistant_value = frame.EvaluateExpression( + "mine.nonexistantInt", False) + nonexistant_error = nonexistant_value.GetError() + self.assertTrue(nonexistant_error.Success()) + nonexistant_int = nonexistant_value.GetValueAsUnsigned(123456) + self.assertTrue(nonexistant_int == 6) + + # Calling the getter function would up the access count, so make sure + # that happened. + + new_access_count = access_count.GetValueAsUnsigned(123456) + self.assertTrue(new_access_count - start_access_count == 1) + start_access_count = new_access_count + + # + # Now call the setter, then make sure that + nonexistant_change = frame.EvaluateExpression( + "mine.nonexistantInt = 10", False) + nonexistant_error = nonexistant_change.GetError() + self.assertTrue(nonexistant_error.Success()) + + # Calling the setter function would up the access count, so make sure + # that happened. + + new_access_count = access_count.GetValueAsUnsigned(123456) + self.assertTrue(new_access_count - start_access_count == 1) + start_access_count = new_access_count + + # + # Now we call the getter of a property that is backed by an ivar, + # make sure it works and that we actually update the backing ivar. + # + + backed_value = frame.EvaluateExpression("mine.backedInt", False) + backed_error = backed_value.GetError() + self.assertTrue(backed_error.Success()) + backing_value = mine.GetChildMemberWithName("_backedInt") + self.assertTrue(backing_value.IsValid()) + self.assertTrue(backed_value.GetValueAsUnsigned(12345) + == backing_value.GetValueAsUnsigned(23456)) + + unbacked_value = frame.EvaluateExpression("mine.unbackedInt", False) + unbacked_error = unbacked_value.GetError() + self.assertTrue(unbacked_error.Success()) + + idWithProtocol_value = frame.EvaluateExpression( + "mine.idWithProtocol", False) + idWithProtocol_error = idWithProtocol_value.GetError() + self.assertTrue(idWithProtocol_error.Success()) + self.assertTrue(idWithProtocol_value.GetTypeName() == "id") + + # Make sure that class property getter works as expected + value = frame.EvaluateExpression("BaseClass.classInt", False) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsUnsigned(11111) == 123) + + # Make sure that class property setter works as expected + value = frame.EvaluateExpression("BaseClass.classInt = 234", False) + self.assertTrue(value.GetError().Success()) + + # Verify that setter above actually worked + value = frame.EvaluateExpression("BaseClass.classInt", False) + self.assertTrue(value.GetError().Success()) + self.assertTrue(value.GetValueAsUnsigned(11111) == 234) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/main.m new file mode 100644 index 00000000000..8d14759fb38 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-property/main.m @@ -0,0 +1,113 @@ +#import <Foundation/Foundation.h> + +@protocol MyProtocol + +-(const char *)hello; + +@end + +static int _class_int = 123; + +@interface BaseClass : NSObject +{ + int _backedInt; + int _access_count; +} + +- (int) nonexistantInt; +- (void) setNonexistantInt: (int) in_int; + +- (int) myGetUnbackedInt; +- (void) mySetUnbackedInt: (int) in_int; + +- (int) getAccessCount; + ++(BaseClass *) baseClassWithBackedInt: (int) inInt andUnbackedInt: (int) inOtherInt; + +@property(getter=myGetUnbackedInt,setter=mySetUnbackedInt:) int unbackedInt; +@property int backedInt; +@property (nonatomic, assign) id <MyProtocol> idWithProtocol; +@property(class) int classInt; +@end + +@implementation BaseClass +@synthesize unbackedInt; +@synthesize backedInt = _backedInt; + ++ (BaseClass *) baseClassWithBackedInt: (int) inInt andUnbackedInt: (int) inOtherInt +{ + BaseClass *new = [[BaseClass alloc] init]; + + new->_backedInt = inInt; + new->unbackedInt = inOtherInt; + + return new; +} + +- (int) myGetUnbackedInt +{ + // NSLog (@"Getting BaseClass::unbackedInt - %d.\n", unbackedInt); + _access_count++; + return unbackedInt; +} + +- (void) mySetUnbackedInt: (int) in_int +{ + // NSLog (@"Setting BaseClass::unbackedInt from %d to %d.", unbackedInt, in_int); + _access_count++; + unbackedInt = in_int; +} + +- (int) nonexistantInt +{ + // NSLog (@"Getting BaseClass::nonexistantInt - %d.\n", 5); + _access_count++; + return 6; +} + +- (void) setNonexistantInt: (int) in_int +{ + // NSLog (@"Setting BaseClass::nonexistantInt from 7 to %d.", in_int); + _access_count++; +} + ++ (int) classInt +{ + return _class_int; +} + ++ (void) setClassInt:(int) n +{ + _class_int = n; +} + +- (int) getAccessCount +{ + return _access_count; +} +@end + +int +main () +{ + BaseClass *mine = [BaseClass baseClassWithBackedInt: 10 andUnbackedInt: 20]; + + // Set a breakpoint here. + int nonexistant = mine.nonexistantInt; + + int backedInt = mine.backedInt; + + int unbackedInt = mine.unbackedInt; + + id idWithProtocol = mine.idWithProtocol; + + NSLog (@"Results for %p: nonexistant: %d backed: %d unbacked: %d accessCount: %d.", + mine, + nonexistant, + backedInt, + unbackedInt, + [mine getAccessCount]); + return 0; + +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/Makefile new file mode 100644 index 00000000000..afecbf96948 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py new file mode 100644 index 00000000000..f1b36943ece --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py @@ -0,0 +1,8 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, + decorators.skipIfWindows, decorators.skipIfNetBSD, + decorators.skipIf(archs=["i386", "i686"])]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/main.m new file mode 100644 index 00000000000..1f5a9b077e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/main.m @@ -0,0 +1,10 @@ +#import <Foundation/Foundation.h> + +int main () +{ + @autoreleasepool + { + NSLog(@"Hello"); //% self.expect("expression -- *((NSConcretePointerArray*)[NSPointerArray strongObjectsPointerArray])", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["count", "capacity", "options", "mutations"]); + //% self.expect("expression -- ((NSConcretePointerArray*)[NSPointerArray strongObjectsPointerArray])->count", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["unsigned"]); + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/Makefile new file mode 100644 index 00000000000..0ad7e356316 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/Makefile @@ -0,0 +1,14 @@ +OBJC_SOURCES := static.m +LD_EXTRAS := -lobjc -framework Foundation + +default: a.out.stripped + +a.out.stripped: a.out.dSYM + strip -o a.out.stripped a.out + ln -sf a.out.dSYM a.out.stripped.dSYM + +clean:: + rm -f a.out.stripped + rm -rf $(wildcard *.dSYM) + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py new file mode 100644 index 00000000000..8ee73eda3f7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py @@ -0,0 +1,77 @@ +"""Test calling functions in static methods with a stripped binary.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCStaticMethodStripped(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "static.m" + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + @skipIf( + debug_info=no_match("dsym"), + bugnumber="This test requires a stripped binary and a dSYM") + #<rdar://problem/12042992> + def test_with_python_api(self): + """Test calling functions in static methods with a stripped binary.""" + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) + self.assertTrue(bpt, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) + + # Make sure we stopped at the first breakpoint. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the static method we've + # stopped in. + frame = thread_list[0].GetFrameAtIndex(0) + self.assertTrue(frame, "Got a valid frame 0 frame.") + + cmd_value = frame.EvaluateExpression("(char *) sel_getName (_cmd)") + self.assertTrue(cmd_value.IsValid()) + sel_name = cmd_value.GetSummary() + self.assertTrue( + sel_name == "\"doSomethingWithString:\"", + "Got the right value for the selector as string.") + + cmd_value = frame.EvaluateExpression( + "[Foo doSomethingElseWithString:string]") + self.assertTrue(cmd_value.IsValid()) + string_length = cmd_value.GetValueAsUnsigned() + self.assertTrue( + string_length == 27, + "Got the right value from another class method on the same class.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/static.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/static.m new file mode 100644 index 00000000000..ec7b2ef6719 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/static.m @@ -0,0 +1,29 @@ +#import <Foundation/Foundation.h> + +@interface Foo : NSObject ++(void) doSomethingWithString: (NSString *) string; +-(void) doSomethingWithNothing; +@end + +@implementation Foo ++(void) doSomethingWithString: (NSString *) string +{ + NSLog (@"String is: %@.", string); // Set breakpoint here. +} + ++(int) doSomethingElseWithString: (NSString *) string +{ + NSLog (@"String is still: %@.", string); + return [string length]; +} + +-(void) doSomethingWithNothing +{ +} +@end + +int main() +{ + [Foo doSomethingWithString: @"Some string I have in mind."]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/Makefile new file mode 100644 index 00000000000..954dea47b32 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := static.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py new file mode 100644 index 00000000000..ce18a07394b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py @@ -0,0 +1,72 @@ +"""Test calling functions in static methods.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCStaticMethod(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "static.m" + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + #<rdar://problem/9745789> "expression" can't call functions in class methods + def test_with_python_api(self): + """Test calling functions in static methods.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) + self.assertTrue(bpt, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) + + # Make sure we stopped at the first breakpoint. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the static method we've + # stopped in. + frame = thread_list[0].GetFrameAtIndex(0) + self.assertTrue(frame, "Got a valid frame 0 frame.") + + cmd_value = frame.EvaluateExpression("(char *) sel_getName (_cmd)") + self.assertTrue(cmd_value.IsValid()) + sel_name = cmd_value.GetSummary() + self.assertTrue( + sel_name == "\"doSomethingWithString:\"", + "Got the right value for the selector as string.") + + cmd_value = frame.EvaluateExpression( + "[self doSomethingElseWithString:string]") + self.assertTrue(cmd_value.IsValid()) + string_length = cmd_value.GetValueAsUnsigned() + self.assertTrue( + string_length == 27, + "Got the right value from another class method on the same class.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/static.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/static.m new file mode 100644 index 00000000000..ec7b2ef6719 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-static-method/static.m @@ -0,0 +1,29 @@ +#import <Foundation/Foundation.h> + +@interface Foo : NSObject ++(void) doSomethingWithString: (NSString *) string; +-(void) doSomethingWithNothing; +@end + +@implementation Foo ++(void) doSomethingWithString: (NSString *) string +{ + NSLog (@"String is: %@.", string); // Set breakpoint here. +} + ++(int) doSomethingElseWithString: (NSString *) string +{ + NSLog (@"String is still: %@.", string); + return [string length]; +} + +-(void) doSomethingWithNothing +{ +} +@end + +int main() +{ + [Foo doSomethingWithString: @"Some string I have in mind."]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/Makefile new file mode 100644 index 00000000000..9906470d530 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := stepping-tests.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py new file mode 100644 index 00000000000..bf80995b109 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py @@ -0,0 +1,220 @@ +"""Test stepping through ObjC method dispatch in various forms.""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCStepping(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers that we will step to in main: + self.main_source = "stepping-tests.m" + self.source_randomMethod_line = line_number( + self.main_source, '// Source randomMethod start line.') + self.sourceBase_randomMethod_line = line_number( + self.main_source, '// SourceBase randomMethod start line.') + self.source_returnsStruct_start_line = line_number( + self.main_source, '// Source returnsStruct start line.') + self.sourceBase_returnsStruct_start_line = line_number( + self.main_source, '// SourceBase returnsStruct start line.') + self.stepped_past_nil_line = line_number( + self.main_source, '// Step over nil should stop here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi', 'basic_process']) + def test_with_python_api(self): + """Test stepping through ObjC method dispatch in various forms.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + breakpoints_to_disable = [] + + break1 = target.BreakpointCreateBySourceRegex( + "// Set first breakpoint here.", self.main_source_spec) + self.assertTrue(break1, VALID_BREAKPOINT) + breakpoints_to_disable.append(break1) + + break2 = target.BreakpointCreateBySourceRegex( + "// Set second breakpoint here.", self.main_source_spec) + self.assertTrue(break2, VALID_BREAKPOINT) + breakpoints_to_disable.append(break2) + + break3 = target.BreakpointCreateBySourceRegex( + '// Set third breakpoint here.', self.main_source_spec) + self.assertTrue(break3, VALID_BREAKPOINT) + breakpoints_to_disable.append(break3) + + break4 = target.BreakpointCreateBySourceRegex( + '// Set fourth breakpoint here.', self.main_source_spec) + self.assertTrue(break4, VALID_BREAKPOINT) + breakpoints_to_disable.append(break4) + + break5 = target.BreakpointCreateBySourceRegex( + '// Set fifth breakpoint here.', self.main_source_spec) + self.assertTrue(break5, VALID_BREAKPOINT) + breakpoints_to_disable.append(break5) + + break_returnStruct_call_super = target.BreakpointCreateBySourceRegex( + '// Source returnsStruct call line.', self.main_source_spec) + self.assertTrue(break_returnStruct_call_super, VALID_BREAKPOINT) + breakpoints_to_disable.append(break_returnStruct_call_super) + + break_step_nil = target.BreakpointCreateBySourceRegex( + '// Set nil step breakpoint here.', self.main_source_spec) + self.assertTrue(break_step_nil, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) + if len(threads) != 1: + self.fail("Failed to stop at breakpoint 1.") + + thread = threads[0] + + mySource = thread.GetFrameAtIndex(0).FindVariable("mySource") + self.assertTrue(mySource, "Found mySource local variable.") + mySource_isa = mySource.GetChildMemberWithName("isa") + self.assertTrue(mySource_isa, "Found mySource->isa local variable.") + className = mySource_isa.GetSummary() + + if self.TraceOn(): + print(mySource_isa) + + # Lets delete mySource so we can check that after stepping a child variable + # with no parent persists and is useful. + del (mySource) + + # Now step in, that should leave us in the Source randomMethod: + thread.StepInto() + line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() + self.assertTrue( + line_number == self.source_randomMethod_line, + "Stepped into Source randomMethod.") + + # Now step in again, through the super call, and that should leave us + # in the SourceBase randomMethod: + thread.StepInto() + line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() + self.assertTrue( + line_number == self.sourceBase_randomMethod_line, + "Stepped through super into SourceBase randomMethod.") + + threads = lldbutil.continue_to_breakpoint(process, break2) + self.assertTrue( + len(threads) == 1, + "Continued to second breakpoint in main.") + + # Again, step in twice gets us to a stret method and a stret super + # call: + thread = threads[0] + thread.StepInto() + line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() + self.assertTrue( + line_number == self.source_returnsStruct_start_line, + "Stepped into Source returnsStruct.") + + threads = lldbutil.continue_to_breakpoint( + process, break_returnStruct_call_super) + self.assertTrue( + len(threads) == 1, + "Stepped to the call super line in Source returnsStruct.") + thread = threads[0] + + thread.StepInto() + line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() + self.assertTrue( + line_number == self.sourceBase_returnsStruct_start_line, + "Stepped through super into SourceBase returnsStruct.") + + # Cool now continue to get past the call that initializes the Observer, and then do our steps in again to see that + # we can find our way when we're stepping through a KVO swizzled + # object. + + threads = lldbutil.continue_to_breakpoint(process, break3) + self.assertTrue( + len(threads) == 1, + "Continued to third breakpoint in main, our object should now be swizzled.") + + newClassName = mySource_isa.GetSummary() + + if self.TraceOn(): + print("className is %s, newClassName is %s" % (className, newClassName)) + print(mySource_isa) + + self.assertTrue( + newClassName != className, + "The isa did indeed change, swizzled!") + + # Now step in, that should leave us in the Source randomMethod: + thread = threads[0] + thread.StepInto() + line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() + self.assertTrue( + line_number == self.source_randomMethod_line, + "Stepped into Source randomMethod in swizzled object.") + + # Now step in again, through the super call, and that should leave us + # in the SourceBase randomMethod: + thread.StepInto() + line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() + self.assertTrue( + line_number == self.sourceBase_randomMethod_line, + "Stepped through super into SourceBase randomMethod in swizzled object.") + + threads = lldbutil.continue_to_breakpoint(process, break4) + self.assertTrue( + len(threads) == 1, + "Continued to fourth breakpoint in main.") + thread = threads[0] + + # Again, step in twice gets us to a stret method and a stret super + # call: + thread.StepInto() + line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() + self.assertTrue( + line_number == self.source_returnsStruct_start_line, + "Stepped into Source returnsStruct in swizzled object.") + + threads = lldbutil.continue_to_breakpoint( + process, break_returnStruct_call_super) + self.assertTrue( + len(threads) == 1, + "Stepped to the call super line in Source returnsStruct - second time.") + thread = threads[0] + + thread.StepInto() + line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() + self.assertTrue( + line_number == self.sourceBase_returnsStruct_start_line, + "Stepped through super into SourceBase returnsStruct in swizzled object.") + + for bkpt in breakpoints_to_disable: + bkpt.SetEnabled(False) + + threads = lldbutil.continue_to_breakpoint(process, break_step_nil) + self.assertTrue(len(threads) == 1, "Continued to step nil breakpoint.") + + thread.StepInto() + line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine() + self.assertTrue( + line_number == self.stepped_past_nil_line, + "Step in over dispatch to nil stepped over.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/stepping-tests.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/stepping-tests.m new file mode 100644 index 00000000000..63db536dee4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-stepping/stepping-tests.m @@ -0,0 +1,138 @@ +#import <Foundation/Foundation.h> +#include <stdio.h> + +struct return_me +{ + int first; + int second; +}; + +@interface SourceBase: NSObject +{ + struct return_me my_return; +} +- (SourceBase *) initWithFirst: (int) first andSecond: (int) second; +- (void) randomMethod; +- (struct return_me) returnsStruct; +@end + +@implementation SourceBase +- (void) randomMethod +{ + printf ("Called in SourceBase version of randomMethod.\n"); // SourceBase randomMethod start line. +} + +- (struct return_me) returnsStruct +{ + return my_return; // SourceBase returnsStruct start line. +} + +- (SourceBase *) initWithFirst: (int) first andSecond: (int) second +{ + my_return.first = first; + my_return.second = second; + + return self; +} +@end + +@interface Source : SourceBase +{ + int _property; +} +- (void) setProperty: (int) newValue; +- (void) randomMethod; +- (struct return_me) returnsStruct; +@end + +@implementation Source +- (void) setProperty: (int) newValue +{ + _property = newValue; +} + +- (void) randomMethod +{ + [super randomMethod]; // Source randomMethod start line. + printf ("Called in Source version of random method."); +} + +- (struct return_me) returnsStruct +{ + printf ("Called in Source version of returnsStruct.\n"); // Source returnsStruct start line. + return [super returnsStruct]; // Source returnsStruct call line. +} + +@end + +@interface Observer : NSObject +{ + Source *_source; +} ++ (Observer *) observerWithSource: (Source *) source; +- (Observer *) initWithASource: (Source *) source; +- (void) observeValueForKeyPath: (NSString *) path + ofObject: (id) object + change: (NSDictionary *) change + context: (void *) context; +@end + +@implementation Observer + ++ (Observer *) observerWithSource: (Source *) inSource; +{ + Observer *retval; + + retval = [[Observer alloc] initWithASource: inSource]; + return retval; +} + +- (Observer *) initWithASource: (Source *) source +{ + [super init]; + _source = source; + [_source addObserver: self + forKeyPath: @"property" + options: (NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) + context: NULL]; + return self; +} + +- (void) observeValueForKeyPath: (NSString *) path + ofObject: (id) object + change: (NSDictionary *) change + context: (void *) context +{ + printf ("Observer function called.\n"); + return; +} +@end + +int main () +{ + Source *mySource; + Observer *myObserver; + struct return_me ret_val; + + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + mySource = [[Source alloc] init]; + + [mySource randomMethod]; // Set first breakpoint here. + ret_val = [mySource returnsStruct]; // Set second breakpoint here. + + myObserver = [Observer observerWithSource: mySource]; + + [mySource randomMethod]; // Set third breakpoint here. + ret_val = [mySource returnsStruct]; // Set fourth breakpoint here. + [mySource setProperty: 5]; // Set fifth breakpoint here. + + // We also had a bug where stepping into a method dispatch to nil turned + // into continue. So make sure that works here: + + mySource = nil; + [mySource randomMethod]; // Set nil step breakpoint here. + [pool release]; // Step over nil should stop here. + return 0; + +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/Makefile new file mode 100644 index 00000000000..d059a5c1c29 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := test.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py new file mode 100644 index 00000000000..28188afc142 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py @@ -0,0 +1,66 @@ +"""Test passing structs to Objective-C methods.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCStructArgument(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "test.m" + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + @skipIf(debug_info=no_match(["gmodules"]), oslist=['ios', 'watchos', 'tvos', 'bridgeos'], archs=['armv7', 'arm64']) # this test program only builds for ios with -gmodules + def test_with_python_api(self): + """Test passing structs to Objective-C methods.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) + self.assertTrue(bpt, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) + + # Make sure we stopped at the first breakpoint. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + frame = thread_list[0].GetFrameAtIndex(0) + self.assertTrue(frame, "Got a valid frame 0 frame.") + + self.expect("p [summer sumThings:tts]", substrs=['9']) + + self.expect( + "po [NSValue valueWithRect:rect]", + substrs=['NSRect: {{0, 0}, {10, 20}}']) + + # Now make sure we can call a method that returns a struct without + # crashing. + cmd_value = frame.EvaluateExpression("[provider getRange]") + self.assertTrue(cmd_value.IsValid()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/test.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/test.m new file mode 100644 index 00000000000..6b13a3a3d59 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/test.m @@ -0,0 +1,40 @@ +#import <Foundation/Foundation.h> +#include <TargetConditionals.h> + +#if TARGET_OS_IPHONE +@import CoreGraphics; +typedef CGRect NSRect; +#endif + +struct things_to_sum { + int a; + int b; + int c; +}; + +@interface ThingSummer : NSObject { +}; +-(int)sumThings:(struct things_to_sum)tts; +@end + +@implementation ThingSummer +-(int)sumThings:(struct things_to_sum)tts +{ + return tts.a + tts.b + tts.c; +} +@end + +int main() +{ + @autoreleasepool + { + ThingSummer *summer = [ThingSummer alloc]; + struct things_to_sum tts = { 2, 3, 4 }; + int ret = [summer sumThings:tts]; + NSRect rect = {{0, 0}, {10, 20}}; + // The Objective-C V1 runtime won't read types from metadata so we need + // NSValue in our debug info to use it in our test. + NSValue *v = [NSValue valueWithRect:rect]; + return rect.origin.x; // Set breakpoint here. + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/Makefile new file mode 100644 index 00000000000..d059a5c1c29 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := test.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py new file mode 100644 index 00000000000..c8c54848a99 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py @@ -0,0 +1,59 @@ +"""Test calling functions in class methods.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCClassMethod(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "test.m" + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test calling functions in class methods.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) + self.assertTrue(bpt, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) + + # Make sure we stopped at the first breakpoint. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + frame = thread_list[0].GetFrameAtIndex(0) + self.assertTrue(frame, "Got a valid frame 0 frame.") + + # Now make sure we can call a method that returns a struct without + # crashing. + cmd_value = frame.EvaluateExpression("[provider getRange]") + self.assertTrue(cmd_value.IsValid()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/test.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/test.m new file mode 100644 index 00000000000..aafe231ea81 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/test.m @@ -0,0 +1,23 @@ +#import <Foundation/Foundation.h> + +@interface RangeProvider : NSObject { +}; +-(NSRange)getRange; +@end + +@implementation RangeProvider +-(NSRange)getRange +{ + return NSMakeRange(0, 3); +} +@end + +int main() +{ + @autoreleasepool + { + RangeProvider *provider = [RangeProvider alloc]; + NSRange range = [provider getRange]; // Set breakpoint here. + return 0; + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/Makefile new file mode 100644 index 00000000000..e6db3dee37b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := class.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py new file mode 100644 index 00000000000..5cb46e007d8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py @@ -0,0 +1,64 @@ +"""Test calling methods on super.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestObjCSuperMethod(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.main_source = "class.m" + self.break_line = line_number( + self.main_source, '// Set breakpoint here.') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test calling methods on super.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + bpt = target.BreakpointCreateByLocation( + self.main_source, self.break_line) + self.assertTrue(bpt, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + thread_list = lldbutil.get_threads_stopped_at_breakpoint(process, bpt) + + # Make sure we stopped at the first breakpoint. + self.assertTrue( + len(thread_list) != 0, + "No thread stopped at our breakpoint.") + self.assertTrue(len(thread_list) == 1, + "More than one thread stopped at our breakpoint.") + + # Now make sure we can call a function in the class method we've + # stopped in. + frame = thread_list[0].GetFrameAtIndex(0) + self.assertTrue(frame, "Got a valid frame 0 frame.") + + cmd_value = frame.EvaluateExpression("[self get]") + self.assertTrue(cmd_value.IsValid()) + self.assertTrue(cmd_value.GetValueAsUnsigned() == 2) + + cmd_value = frame.EvaluateExpression("[super get]") + self.assertTrue(cmd_value.IsValid()) + self.assertTrue(cmd_value.GetValueAsUnsigned() == 1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/class.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/class.m new file mode 100644 index 00000000000..b55b649aaae --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc-super/class.m @@ -0,0 +1,39 @@ +#import <Foundation/Foundation.h> + +@interface Foo : NSObject { +} +-(int)get; +@end + +@implementation Foo +-(int)get +{ + return 1; +} +@end + +@interface Bar : Foo { +} +-(int)get; +@end + +@implementation Bar +-(int)get +{ + return 2; +} + +-(int)callme +{ + return [self get]; // Set breakpoint here. +} +@end + +int main() +{ + @autoreleasepool + { + Bar *bar = [Bar alloc]; + return [bar callme]; + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc_direct-methods/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc_direct-methods/Makefile new file mode 100644 index 00000000000..afecbf96948 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc_direct-methods/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc_direct-methods/TestObjCDirectMethods.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc_direct-methods/TestObjCDirectMethods.py new file mode 100644 index 00000000000..f0152de1ac3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc_direct-methods/TestObjCDirectMethods.py @@ -0,0 +1,5 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [decorators.skipUnlessDarwin]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc_direct-methods/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc_direct-methods/main.m new file mode 100644 index 00000000000..6799f22500c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/objc_direct-methods/main.m @@ -0,0 +1,92 @@ +#import <Foundation/Foundation.h> + +int side_effect = 0; + +NSString *str = @"some string"; + +const char *directCallConflictingName() { + return "wrong function"; +} + +@interface Foo : NSObject { + int instance_var; +} +-(int) entryPoint; +@end + +@implementation Foo +-(int) entryPoint +{ + // Try calling directly with self. Same as in the main method otherwise. + return 0; //%self.expect("expr [self directCallNoArgs]", substrs=["called directCallNoArgs"]) + //%self.expect("expr [self directCallArgs: 1111]", substrs=["= 2345"]) + //%self.expect("expr side_effect = 0; [self directCallVoidReturn]; side_effect", substrs=["= 4321"]) + //%self.expect("expr [self directCallNSStringArg: str]", substrs=['@"some string"']) + //%self.expect("expr [self directCallIdArg: (id)str]", substrs=['@"some string appendix"']) + //%self.expect("expr [self directCallConflictingName]", substrs=["correct function"]) + //%self.expect("expr [self directCallWithCategory]", substrs=["called function with category"]) +} + +// Declare several objc_direct functions we can test. +-(const char *) directCallNoArgs __attribute__((objc_direct)) +{ + return "called directCallNoArgs"; +} + +-(void) directCallVoidReturn __attribute__((objc_direct)) +{ + side_effect = 4321; +} + +-(int) directCallArgs:(int)i __attribute__((objc_direct)) +{ + // Use the arg in some way to make sure that gets passed correctly. + return i + 1234; +} + +-(NSString *) directCallNSStringArg:(NSString *)str __attribute__((objc_direct)) +{ + return str; +} + +-(NSString *) directCallIdArg:(id)param __attribute__((objc_direct)) +{ + return [param stringByAppendingString:@" appendix"]; +} + +// We have another function with the same name above. Make sure this doesn't influence +// what we call. +-(const char *) directCallConflictingName __attribute__((objc_direct)) +{ + return "correct function"; +} +@end + + +@interface Foo (Cat) +@end + +@implementation Foo (Cat) +-(const char *) directCallWithCategory __attribute__((objc_direct)) +{ + return "called function with category"; +} +@end + +int main() +{ + Foo *foo = [[Foo alloc] init]; + [foo directCallNoArgs]; + [foo directCallArgs: 1]; + [foo directCallVoidReturn]; + [foo directCallNSStringArg: str]; + [foo directCallIdArg: (id)str]; + [foo entryPoint]; //%self.expect("expr [foo directCallNoArgs]", substrs=["called directCallNoArgs"]) + //%self.expect("expr [foo directCallArgs: 1111]", substrs=["= 2345"]) + //%self.expect("expr side_effect = 0; [foo directCallVoidReturn]; side_effect", substrs=["= 4321"]) + //%self.expect("expr [foo directCallNSStringArg: str]", substrs=['@"some string"']) + //%self.expect("expr [foo directCallIdArg: (id)str]", substrs=['@"some string appendix"']) + //%self.expect("expr [foo directCallConflictingName]", substrs=["correct function"]) + //%self.expect("expr [foo directCallWithCategory]", substrs=["called function with category"]) + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/orderedset/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/orderedset/Makefile new file mode 100644 index 00000000000..afecbf96948 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/orderedset/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/orderedset/TestOrderedSet.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/orderedset/TestOrderedSet.py new file mode 100644 index 00000000000..90c6bc32f77 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/orderedset/TestOrderedSet.py @@ -0,0 +1,18 @@ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestOrderedSet(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_ordered_set(self): + self.build() + src_file = "main.m" + src_file_spec = lldb.SBFileSpec(src_file) + (target, process, thread, main_breakpoint) = lldbutil.run_to_source_breakpoint(self, + "break here", src_file_spec, exe_name = "a.out") + frame = thread.GetSelectedFrame() + self.expect("expr -d run -- orderedSet", substrs=["3 elements"]) + self.expect("expr -d run -- *orderedSet", substrs=["(int)1", "(int)2", "(int)3"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/orderedset/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/orderedset/main.m new file mode 100644 index 00000000000..e3f01622693 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/orderedset/main.m @@ -0,0 +1,8 @@ +#import <Foundation/Foundation.h> + +int main() { + NSOrderedSet *orderedSet = + [NSOrderedSet orderedSetWithArray:@[@1,@2,@3,@1]]; + NSLog(@"%@",orderedSet); + return 0; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/Makefile new file mode 100644 index 00000000000..2eab56265f5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := blocked.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py new file mode 100644 index 00000000000..9b3ec33db4e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py @@ -0,0 +1,91 @@ +""" +Test "print object" where another thread blocks the print object from making progress. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class PrintObjTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # My source program. + self.source = "blocked.m" + # Find the line numbers to break at. + self.line = line_number(self.source, '// Set a breakpoint here.') + + def test_print_obj(self): + """ + Test "print object" where another thread blocks the print object from making progress. + + Set a breakpoint on the line in my_pthread_routine. Then switch threads + to the main thread, and do print the lock_me object. Since that will + try to get the lock already gotten by my_pthread_routime thread, it will + have to switch to running all threads, and that should then succeed. + """ + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + exe = self.getBuildArtifact('b.out') + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + self.runCmd("breakpoint list") + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.runCmd("thread backtrace all") + + # Let's get the current stopped thread. We'd like to switch to the + # other thread to issue our 'po lock_me' command. + import lldbsuite.test.lldbutil as lldbutil + this_thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue(this_thread) + + # Find the other thread. The iteration protocol of SBProcess and the + # rich comparison methods (__eq__/__ne__) of SBThread come in handy. + other_thread = None + for t in process: + if t != this_thread: + other_thread = t + break + + # Set the other thread as the selected thread to issue our 'po' + # command.other + self.assertTrue(other_thread) + process.SetSelectedThread(other_thread) + if self.TraceOn(): + print("selected thread:" + lldbutil.get_description(other_thread)) + self.runCmd("thread backtrace") + + # We want to traverse the frame to the one corresponding to blocked.m to + # issue our 'po lock_me' command. + + depth = other_thread.GetNumFrames() + for i in range(depth): + frame = other_thread.GetFrameAtIndex(i) + name = frame.GetFunctionName() + if name == 'main': + other_thread.SetSelectedFrame(i) + if self.TraceOn(): + print("selected frame:" + lldbutil.get_description(frame)) + break + + self.expect("po lock_me", OBJECT_PRINTED_CORRECTLY, + substrs=['I am pretty special.']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/blocked.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/blocked.m new file mode 100644 index 00000000000..58771264062 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/print-obj/blocked.m @@ -0,0 +1,72 @@ +//===-- blocked.m --------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This file is for testing running "print object" in a case where another thread +// blocks the print object from making progress. Set a breakpoint on the line in +// my_pthread_routine as indicated. Then switch threads to the main thread, and +// do print the lock_me object. Since that will try to get the lock already gotten +// by my_pthread_routime thread, it will have to switch to running all threads, and +// that should then succeed. +// + +#include <Foundation/Foundation.h> +#include <pthread.h> + +static pthread_mutex_t test_mutex; + +static void Mutex_Init (void) +{ + pthread_mutexattr_t tmp_mutex_attr; + pthread_mutexattr_init(&tmp_mutex_attr); + pthread_mutex_init(&test_mutex, &tmp_mutex_attr); +} + +@interface LockMe :NSObject +{ + +} +- (NSString *) description; +@end + +@implementation LockMe +- (NSString *) description +{ + printf ("LockMe trying to get the lock.\n"); + pthread_mutex_lock(&test_mutex); + printf ("LockMe got the lock.\n"); + pthread_mutex_unlock(&test_mutex); + return @"I am pretty special.\n"; +} +@end + +void * +my_pthread_routine (void *data) +{ + printf ("my_pthread_routine about to enter.\n"); + pthread_mutex_lock(&test_mutex); + printf ("Releasing Lock.\n"); // Set a breakpoint here. + pthread_mutex_unlock(&test_mutex); + return NULL; +} + +int +main () +{ + pthread_attr_t tmp_attr; + pthread_attr_init (&tmp_attr); + pthread_t my_pthread; + + Mutex_Init (); + + LockMe *lock_me = [[LockMe alloc] init]; + pthread_create (&my_pthread, &tmp_attr, my_pthread_routine, NULL); + + pthread_join (my_pthread, NULL); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ptr_refs/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ptr_refs/Makefile new file mode 100644 index 00000000000..845553d5e3f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ptr_refs/Makefile @@ -0,0 +1,3 @@ +OBJC_SOURCES := main.m + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ptr_refs/TestPtrRefsObjC.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ptr_refs/TestPtrRefsObjC.py new file mode 100644 index 00000000000..aade40c06b6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ptr_refs/TestPtrRefsObjC.py @@ -0,0 +1,47 @@ +""" +Test the ptr_refs tool on Darwin with Objective-C +""" + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestPtrRefsObjC(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_ptr_refs(self): + """Test the ptr_refs tool on Darwin with Objective-C""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + main_file_spec = lldb.SBFileSpec('main.m') + breakpoint = target.BreakpointCreateBySourceRegex( + 'break', main_file_spec) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.line1 and the break condition should hold. + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + + frame = thread.GetFrameAtIndex(0) + + self.dbg.HandleCommand("script import lldb.macosx.heap") + self.expect("ptr_refs self", substrs=["malloc", "stack"]) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ptr_refs/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ptr_refs/main.m new file mode 100644 index 00000000000..94bf0fb9fc5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/ptr_refs/main.m @@ -0,0 +1,38 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +@interface MyClass : NSObject { +}; +-(void)test; +@end + +@implementation MyClass +-(void)test { + printf("%p\n", self); // break here +} +@end + +@interface MyOwner : NSObject { + @public id ownedThing; // should be id, to test <rdar://problem/31363513> +}; +@end + +@implementation MyOwner +@end + +int main (int argc, char const *argv[]) { + @autoreleasepool { + MyOwner *owner = [[MyOwner alloc] init]; + owner->ownedThing = [[MyClass alloc] init]; + [(MyClass*)owner->ownedThing test]; + } + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/Makefile new file mode 100644 index 00000000000..37dd8f40a9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py new file mode 100644 index 00000000000..632ef7bfe73 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py @@ -0,0 +1,45 @@ +""" +Test that objective-c method returning BOOL works correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class MethodReturningBOOLTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to break inside main(). + self.main_source = "main.m" + self.line = line_number(self.main_source, '// Set breakpoint here.') + + def test_method_ret_BOOL(self): + """Test that objective-c method returning BOOL works correctly.""" + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, + substrs=[" at %s:%d" % (self.main_source, self.line), + "stop reason = breakpoint"]) + + # rdar://problem/9691614 + self.runCmd('p (int)[my isValid]') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/main.m new file mode 100644 index 00000000000..bb87d673452 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/radar-9691614/main.m @@ -0,0 +1,67 @@ +#import <Foundation/Foundation.h> +#include <stdio.h> + +@interface MyString : NSObject { + NSString *str; + NSDate *date; + BOOL _is_valid; +} + +- (id)initWithNSString:(NSString *)string; +- (BOOL)isValid; +@end + +@implementation MyString +- (id)initWithNSString:(NSString *)string +{ + if (self = [super init]) + { + str = [NSString stringWithString:string]; + date = [NSDate date]; + } + _is_valid = YES; + return self; +} + +- (BOOL)isValid +{ + return _is_valid; +} + +- (void)dealloc +{ + [date release]; + [str release]; + [super dealloc]; +} + +- (NSString *)description +{ + return [str stringByAppendingFormat:@" with timestamp: %@", date]; +} +@end + +void +Test_MyString (const char *program) +{ + NSString *str = [NSString stringWithFormat:@"Hello from '%s'", program]; + MyString *my = [[MyString alloc] initWithNSString:str]; + if ([my isValid]) + printf("my is valid!\n"); + + NSLog(@"NSString instance: %@", [str description]); // Set breakpoint here. + // Test 'p (int)[my isValid]'. + // The expression parser should not crash -- rdar://problem/9691614. + + NSLog(@"MyString instance: %@", [my description]); +} + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + Test_MyString (argv[0]); + + [pool release]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/Makefile new file mode 100644 index 00000000000..37dd8f40a9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py new file mode 100644 index 00000000000..c6633b7fe52 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py @@ -0,0 +1,70 @@ +""" +Test that CoreFoundation classes CFGregorianDate and CFRange are not improperly uniqued +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class Rdar10967107TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to break inside main(). + self.main_source = "main.m" + self.line = line_number(self.main_source, '// Set breakpoint here.') + + def test_cfrange_diff_cfgregoriandate(self): + """Test that CoreFoundation classes CFGregorianDate and CFRange are not improperly uniqued.""" + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + # check that each type is correctly bound to its list of children + self.expect( + "frame variable cf_greg_date --raw", + substrs=[ + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second']) + self.expect( + "frame variable cf_range --raw", + substrs=[ + 'location', + 'length']) + # check that printing both does not somehow confuse LLDB + self.expect( + "frame variable --raw", + substrs=[ + 'year', + 'month', + 'day', + 'hour', + 'minute', + 'second', + 'location', + 'length']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/main.m new file mode 100644 index 00000000000..386a458950b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/main.m @@ -0,0 +1,13 @@ +#import <Foundation/Foundation.h> + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + NSDate *date1 = [NSDate date]; + CFGregorianDate cf_greg_date = CFAbsoluteTimeGetGregorianDate(CFDateGetAbsoluteTime((CFDateRef)date1), NULL); + CFRange cf_range = {4,4}; + + [pool release]; // Set breakpoint here. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/Makefile new file mode 100644 index 00000000000..37dd8f40a9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py new file mode 100644 index 00000000000..f9e825ada43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py @@ -0,0 +1,79 @@ +""" +Test that we do not attempt to make a dynamic type for a 'const char*' +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class Rdar10967107TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to break inside main(). + self.main_source = "main.m" + self.line = line_number(self.main_source, '// Set breakpoint here.') + + def test_charstar_dyntype(self): + """Test that we do not attempt to make a dynamic type for a 'const char*'""" + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + # check that we correctly see the const char*, even with dynamic types + # on + self.expect("frame variable -raw-output my_string", substrs=['const char *']) + self.expect( + "frame variable my_string --raw-output --dynamic-type run-target", + substrs=['const char *']) + # check that expr also gets it right + self.expect("e -R -- my_string", substrs=['const char *']) + self.expect("expr -R -d run -- my_string", substrs=['const char *']) + # but check that we get the real Foolie as such + self.expect("frame variable my_foolie", substrs=['FoolMeOnce *']) + self.expect( + "frame variable my_foolie --dynamic-type run-target", + substrs=['FoolMeOnce *']) + # check that expr also gets it right + self.expect("expr my_foolie", substrs=['FoolMeOnce *']) + self.expect("expr -d run -- my_foolie", substrs=['FoolMeOnce *']) + # now check that assigning a true string does not break anything + self.runCmd("next") + # check that we correctly see the const char*, even with dynamic types + # on + self.expect("frame variable my_string", substrs=['const char *']) + self.expect( + "frame variable my_string --dynamic-type run-target", + substrs=['const char *']) + # check that expr also gets it right + self.expect("expr my_string", substrs=['const char *']) + self.expect("expr -d run -- my_string", substrs=['const char *']) + # but check that we get the real Foolie as such + self.expect("frame variable my_foolie", substrs=['FoolMeOnce *']) + self.expect( + "frame variable my_foolie --dynamic-type run-target", + substrs=['FoolMeOnce *']) + # check that expr also gets it right + self.expect("expr my_foolie", substrs=['FoolMeOnce *']) + self.expect("expr -d run -- my_foolie", substrs=['FoolMeOnce *']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/main.m new file mode 100644 index 00000000000..09b3b18a787 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/main.m @@ -0,0 +1,37 @@ +#import <Foundation/Foundation.h> + +@interface FoolMeOnce : NSObject +{ + int32_t value_one; // ivars needed to make 32-bit happy + int32_t value_two; +} +- (FoolMeOnce *) initWithFirst: (int32_t) first andSecond: (int32_t) second; + +@property int32_t value_one; +@property int32_t value_two; + +@end + +@implementation FoolMeOnce +@synthesize value_one; +@synthesize value_two; +- (FoolMeOnce *) initWithFirst: (int32_t) first andSecond: (int32_t) second +{ + value_one = first; + value_two = second; + return self; +} +@end + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + FoolMeOnce *my_foolie = [[FoolMeOnce alloc] initWithFirst: 20 andSecond: 55]; + const char *my_string = (char *) my_foolie; + + my_string = "Now this is a REAL string..."; // Set breakpoint here. + + [pool release]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/Makefile new file mode 100644 index 00000000000..919000e6402 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/Makefile @@ -0,0 +1,9 @@ +OBJC_SOURCES := main.m + +include Makefile.rules + +ifneq (,$(findstring arm,$(ARCH))) + LD_EXTRAS = -framework Foundation -framework UIKit +else + LD_EXTRAS = -framework Foundation -framework Cocoa +endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py new file mode 100644 index 00000000000..8f262a3413d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py @@ -0,0 +1,69 @@ +""" +Test that we are able to find out how many children NSWindow has +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +# TODO: The Jenkins testers on OS X fail running this test because they don't +# have access to WindowServer so NSWindow doesn't work. We should disable this +# test if WindowServer isn't available. +# Note: Simply applying the @skipIf decorator here confuses the test harness +# and gives a spurious failure. +@skipUnlessDarwin +class Rdar12408181TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to break inside main(). + self.main_source = "main.m" + self.line = line_number(self.main_source, '// Set breakpoint here.') + + def test_nswindow_count(self): + """Test that we are able to find out how many children NSWindow has.""" + + self.skipTest("Skipping this test due to timeout flakiness") + + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + + exe = self.getBuildArtifact(self.exe_name) + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + self.main_source, + self.line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + if self.frame().EvaluateExpression( + '(void*)_CGSDefaultConnection()').GetValueAsUnsigned() != 0: + window = self.frame().FindVariable("window") + window_dynamic = window.GetDynamicValue(lldb.eDynamicCanRunTarget) + self.assertTrue( + window.GetNumChildren() > 1, + "NSWindow (static) only has 1 child!") + self.assertTrue( + window_dynamic.GetNumChildren() > 1, + "NSWindow (dynamic) only has 1 child!") + self.assertTrue( + window.GetChildAtIndex(0).IsValid(), + "NSWindow (static) has an invalid child") + self.assertTrue( + window_dynamic.GetChildAtIndex(0).IsValid(), + "NSWindow (dynamic) has an invalid child") + else: + self.skipTest('no WindowServer connection') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/main.m new file mode 100644 index 00000000000..858ba2a4a22 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/main.m @@ -0,0 +1,24 @@ +#import <Foundation/Foundation.h> +#if defined (__i386__) || defined (__x86_64__) +#import <Cocoa/Cocoa.h> +#else +#import <UIKit/UIKit.h> +#endif + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; +#if defined (__i386__) || defined (__x86_64__) + + [NSApplication sharedApplication]; + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0,0,100,100) styleMask:NSBorderlessWindowMask backing:NSBackingStoreRetained defer:NO]; + [window setCanHide:YES]; +#else + [UIApplication sharedApplication]; + CGRect rect = { 0, 0, 100, 100}; + UIWindow* window = [[UIWindow alloc] initWithFrame:rect]; +#endif + [pool release]; // Set breakpoint here. + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.h new file mode 100644 index 00000000000..5ee6acb2425 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.h @@ -0,0 +1,12 @@ +#import <Foundation/Foundation.h> + +@class InternalClass; + +@interface Bar : NSObject { + @private + InternalClass *storage; +} + +- (NSString *)description; + +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.m new file mode 100644 index 00000000000..21c39066f8e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.m @@ -0,0 +1,43 @@ +#import "Bar.h" + +@interface InternalClass : NSObject { + @public + NSString *foo; + NSString *bar; +} +@end + +@implementation InternalClass +@end + +@interface Bar () +{ + NSString *_hidden_ivar; +} + +@end + +@implementation Bar + +- (id)init +{ + self = [super init]; + if (self) { + _hidden_ivar = [NSString stringWithFormat:@"%p: @Bar", self]; + } + return self; // Set breakpoint where Bar is an implementation +} + +- (void)dealloc +{ + [_hidden_ivar release]; + [super dealloc]; +} + +- (NSString *)description +{ + return [_hidden_ivar copyWithZone:NULL]; +} + +@end + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.h new file mode 100644 index 00000000000..d58da600765 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.h @@ -0,0 +1,11 @@ +#import <Foundation/Foundation.h> + +#import "Bar.h" + +@interface Foo : NSObject { + Bar *_bar; +} + +- (NSString *)description; + +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.m new file mode 100644 index 00000000000..bcdeaeffc29 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.m @@ -0,0 +1,25 @@ +#import "Foo.h" + +@implementation Foo + +- (id)init +{ + self = [super init]; + if (self) { + _bar = [[Bar alloc] init]; + } + return self; // Set breakpoint where Bar is an interface +} + +- (void)dealloc +{ + [_bar release]; + [super dealloc]; +} + +- (NSString *)description +{ + return [NSString stringWithFormat:@"%p: @Foo { _bar = %@ }", self, _bar]; +} + +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Makefile new file mode 100644 index 00000000000..f1498efac1d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := Bar.m Foo.m main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py new file mode 100644 index 00000000000..002bc6cbf82 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py @@ -0,0 +1,98 @@ +"""Test that types defined in shared libraries work correctly.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestRealDefinition(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_frame_var_after_stop_at_interface(self): + """Test that we can find the implementation for an objective C type""" + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + self.build() + self.common_setup() + + line = line_number( + 'Foo.m', '// Set breakpoint where Bar is an interface') + lldbutil.run_break_set_by_file_and_line( + self, 'Foo.m', line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Run and stop at Foo + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.runCmd("continue", RUN_SUCCEEDED) + + # Run at stop at main + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # This should display correctly. + self.expect( + "frame variable foo->_bar->_hidden_ivar", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(NSString *)", + "foo->_bar->_hidden_ivar = 0x"]) + + @skipUnlessDarwin + def test_frame_var_after_stop_at_implementation(self): + """Test that we can find the implementation for an objective C type""" + if self.getArchitecture() == 'i386': + self.skipTest("requires modern objc runtime") + self.build() + self.common_setup() + + line = line_number( + 'Bar.m', '// Set breakpoint where Bar is an implementation') + lldbutil.run_break_set_by_file_and_line( + self, 'Bar.m', line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Run and stop at Foo + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + self.runCmd("continue", RUN_SUCCEEDED) + + # Run at stop at main + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + # This should display correctly. + self.expect( + "frame variable foo->_bar->_hidden_ivar", + VARIABLES_DISPLAYED_CORRECTLY, + substrs=[ + "(NSString *)", + "foo->_bar->_hidden_ivar = 0x"]) + + def common_setup(self): + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the foo function which takes a bar_ptr argument. + line = line_number('main.m', '// Set breakpoint in main') + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/main.m new file mode 100644 index 00000000000..8c31dc9abb3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/real-definition/main.m @@ -0,0 +1,13 @@ +#include <stdio.h> +#include <stdint.h> +#import <Foundation/Foundation.h> +#import "Foo.h" + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + Foo *foo = [[Foo alloc] init]; + NSLog (@"foo is %@", foo); // Set breakpoint in main + [pool release]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/sample/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/sample/Makefile new file mode 100644 index 00000000000..afecbf96948 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/sample/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/sample/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/sample/main.m new file mode 100644 index 00000000000..9dffc71aaac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/sample/main.m @@ -0,0 +1,70 @@ +#import <Foundation/Foundation.h> + + +@interface MyString : NSObject { + NSString *_string; + NSDate *_date; +} +- (id)initWithNSString:(NSString *)string; + +@property (copy) NSString *string; +@property (readonly,getter=getTheDate) NSDate *date; + +- (NSDate *) getTheDate; +@end + +@implementation MyString + +@synthesize string = _string; +@synthesize date = _date; + +- (id)initWithNSString:(NSString *)string +{ + if (self = [super init]) + { + _string = [NSString stringWithString:string]; + _date = [NSDate date]; + } + return self; +} + +- (void) dealloc +{ + [_date release]; + [_string release]; + [super dealloc]; +} + +- (NSDate *) getTheDate +{ + return _date; +} + +- (NSString *)description +{ + return [_string stringByAppendingFormat:@" with timestamp: %@", _date]; +} +@end + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + static NSString *g_global_nsstr = @"Howdy"; + + MyString *myStr = [[MyString alloc] initWithNSString: [NSString stringWithFormat:@"string %i", 1]]; + NSString *str1 = myStr.string; + NSString *str2 = [NSString stringWithFormat:@"string %i", 2]; + NSString *str3 = [NSString stringWithFormat:@"string %i", 3]; + NSArray *array = [NSArray arrayWithObjects: str1, str2, str3, nil]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: + str1, @"1", + str2, @"2", + str3, @"3", + myStr.date, @"date", + nil]; + + id str_id = str1; + SEL sel = @selector(length); + [pool release]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/self/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/self/Makefile new file mode 100644 index 00000000000..644046c69ea --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/self/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS ?= -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py new file mode 100644 index 00000000000..81d6b79ad53 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py @@ -0,0 +1,39 @@ +""" +Tests that ObjC member variables are available where they should be. +""" +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCSelfTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_with_run_command(self): + """Test that the appropriate member variables are available when stopped in Objective-C class and instance methods""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + self.set_breakpoint(line_number('main.m', '// breakpoint 1')) + self.set_breakpoint(line_number('main.m', '// breakpoint 2')) + + self.runCmd("process launch", RUN_SUCCEEDED) + + self.expect("expression -- m_a = 2", + startstr="(int) $0 = 2") + + self.runCmd("process continue") + + # This would be disallowed if we enforced const. But we don't. + self.expect("expression -- m_a = 2", + error=True) + + self.expect("expression -- s_a", + startstr="(int) $1 = 5") + + def set_breakpoint(self, line): + lldbutil.run_break_set_by_file_and_line( + self, "main.m", line, num_expected_locations=1, loc_exact=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/self/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/self/main.m new file mode 100644 index 00000000000..8f4e61202a3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/self/main.m @@ -0,0 +1,53 @@ +//===-- main.m ------------------------------------------*- Objective-C -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +@interface A : NSObject +{ + int m_a; +} +-(id)init; +-(void)accessMember:(int)a; ++(void)accessStaticMember:(int)a; +@end + +static int s_a = 5; + +@implementation A +-(id)init +{ + self = [super init]; + + if (self) + m_a = 2; + + return self; +} + +-(void)accessMember:(int)a +{ + m_a = a; // breakpoint 1 +} + ++(void)accessStaticMember:(int)a +{ + s_a = a; // breakpoint 2 +} +@end + +int main() +{ + NSAutoreleasePool *pool = [NSAutoreleasePool alloc]; + A *my_a = [[A alloc] init]; + + [my_a accessMember:3]; + [A accessStaticMember:5]; + + [pool release]; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/Makefile new file mode 100644 index 00000000000..37dd8f40a9d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/Makefile @@ -0,0 +1,6 @@ +OBJC_SOURCES := main.m + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/TestObjCSingleEntryDictionary.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/TestObjCSingleEntryDictionary.py new file mode 100644 index 00000000000..85ad6286716 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/TestObjCSingleEntryDictionary.py @@ -0,0 +1,74 @@ +"""Test that we properly vend children for a single entry NSDictionary""" + + + +import unittest2 + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCSingleEntryDictionaryTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.m', '// break here') + + @skipUnlessDarwin + @expectedFailureAll(oslist=['watchos'], bugnumber="rdar://problem/34642736") # bug in NSDictionary formatting on watchos + def test_single_entry_dict(self): + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break inside the foo function which takes a bar_ptr argument. + lldbutil.run_break_set_by_file_and_line( + self, "main.m", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # The breakpoint should have a hit count of 1. + self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, + substrs=[' resolved, hit count = 1']) + + d1 = self.frame().FindVariable("d1") + d1.SetPreferSyntheticValue(True) + d1.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + + self.assertTrue( + d1.GetNumChildren() == 1, + "dictionary has != 1 child elements") + pair = d1.GetChildAtIndex(0) + pair.SetPreferSyntheticValue(True) + pair.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + + self.assertTrue( + pair.GetNumChildren() == 2, + "pair has != 2 child elements") + + key = pair.GetChildMemberWithName("key") + value = pair.GetChildMemberWithName("value") + + key.SetPreferSyntheticValue(True) + key.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + value.SetPreferSyntheticValue(True) + value.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + + self.assertTrue( + key.GetSummary() == '@"key"', + "key doesn't contain key") + self.assertTrue( + value.GetSummary() == '@"value"', + "value doesn't contain value") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/main.m new file mode 100644 index 00000000000..be472fd43c3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/single-entry-dictionary/main.m @@ -0,0 +1,7 @@ +#import <Foundation/Foundation.h> + +int main() { + NSDictionary *d1 = @{@"key" : @"value"}; + NSLog(@"%@\n", d1); // break here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/unicode-string/TestUnicodeString.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/unicode-string/TestUnicodeString.py new file mode 100644 index 00000000000..c9986aafd7d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/unicode-string/TestUnicodeString.py @@ -0,0 +1,6 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipUnlessDarwin]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/unicode-string/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/unicode-string/main.m new file mode 100644 index 00000000000..e55eb1ede9b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/unicode-string/main.m @@ -0,0 +1,5 @@ +#import <Foundation/Foundation.h> + +int main() { + NSLog(@"凸"); //% self.expect("po @\"凹\"", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["凹"]) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/TestVariadicMethods.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/TestVariadicMethods.py new file mode 100644 index 00000000000..562d9ae01e2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/TestVariadicMethods.py @@ -0,0 +1,7 @@ +from lldbsuite.test import lldbinline +from lldbsuite.test import decorators + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, + decorators.skipIfWindows, decorators.skipIfNetBSD]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/main.m new file mode 100644 index 00000000000..609d783dd59 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objc/variadic_methods/main.m @@ -0,0 +1,30 @@ +//===-- main.m -------------------------------------------*- Objective-C-*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +@interface VarClass : NSObject +- (id) lottaArgs: (id) first, ...; +@end + +@implementation VarClass +- (id) lottaArgs: (id) first, ... +{ + return first; +} +@end + +int +main() +{ + VarClass *my_var = [[VarClass alloc] init]; + id something = [my_var lottaArgs: @"111", @"222", nil]; + NSLog (@"%@ - %@", my_var, something); //% self.expect("expression -O -- [my_var lottaArgs:@\"111\", @\"222\", nil]", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["111"]) + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/Makefile new file mode 100644 index 00000000000..bae88debbb1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/Makefile @@ -0,0 +1,10 @@ +OBJCXX_SOURCES := main.mm myobject.mm +include Makefile.rules +CFLAGS_NO_DEBUG = +ifeq "$(OS)" "Darwin" + CFLAGS_NO_DEBUG += -arch $(ARCH) +endif + +# myobject.o needs to be built without debug info +myobject.o: myobject.mm + $(CXX) $(CFLAGS_NO_DEBUG) -c -o $@ $< diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/TestNameClash.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/TestNameClash.py new file mode 100644 index 00000000000..19832aefee9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/TestNameClash.py @@ -0,0 +1,7 @@ +from lldbsuite.test import decorators +from lldbsuite.test import lldbinline + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, + decorators.skipIfWindows, decorators.skipIfNetBSD]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/main.mm new file mode 100644 index 00000000000..b74871f4270 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/main.mm @@ -0,0 +1,21 @@ +#import <Foundation/Foundation.h> + +namespace NS { + class MyObject { int i = 42; }; + NS::MyObject globalObject; +} + +@interface MyObject: NSObject +@end + +int main () +{ + @autoreleasepool + { + MyObject *o = [MyObject alloc]; + return 0; //% self.expect("fr var o", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["(MyObject"]); + //% self.expect("fr var globalObject", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["42"]); + } +} + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/myobject.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/myobject.mm new file mode 100644 index 00000000000..051c4e5eb1d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/class-name-clash/myobject.mm @@ -0,0 +1,7 @@ +#import <Foundation/Foundation.h> + +@interface MyObject : NSObject +@end + +@implementation MyObject +@end diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/cxx-bridged-po/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/cxx-bridged-po/Makefile new file mode 100644 index 00000000000..7cfe4a3f0fd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/cxx-bridged-po/Makefile @@ -0,0 +1,4 @@ +OBJCXX_SOURCES := main.mm +LD_EXTRAS := -lobjc -framework CoreFoundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/cxx-bridged-po/TestObjCXXBridgedPO.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/cxx-bridged-po/TestObjCXXBridgedPO.py new file mode 100644 index 00000000000..6f3275b861c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/cxx-bridged-po/TestObjCXXBridgedPO.py @@ -0,0 +1,21 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil + +class TestObjCXXBridgedPO(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test_bridged_type_po(self): + self.build() + lldbutil.run_to_source_breakpoint( + self, 'break here', lldb.SBFileSpec('main.mm')) + self.expect('po num', + "did not get the Objective-C object description", + substrs=['CFNumber', '0x', '42']) + pointer_val = str(self.frame().FindVariable('num').GetValue()) + self.expect('po '+pointer_val, + "did not get the Objective-C object description", + substrs=['CFNumber', '0x', '42']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/cxx-bridged-po/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/cxx-bridged-po/main.mm new file mode 100644 index 00000000000..e376456033f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/cxx-bridged-po/main.mm @@ -0,0 +1,12 @@ +#include <CoreFoundation/CoreFoundation.h> + +void stop() {} + +int main(int argc, char **argv) +{ + int value = 42; + CFNumberRef num; + num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &value); + stop(); // break here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/hide-runtime-values/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/hide-runtime-values/Makefile new file mode 100644 index 00000000000..3af75c304c3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/hide-runtime-values/Makefile @@ -0,0 +1,4 @@ +OBJCXX_SOURCES := main.mm +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/hide-runtime-values/TestObjCXXHideRuntimeValues.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/hide-runtime-values/TestObjCXXHideRuntimeValues.py new file mode 100644 index 00000000000..cc6ac20b84b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/hide-runtime-values/TestObjCXXHideRuntimeValues.py @@ -0,0 +1,47 @@ +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import unittest2 + + +class TestObjCXXHideRuntimeSupportValues(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfFreeBSD + @skipIfLinux + @skipIfWindows + @skipIfNetBSD + def test_hide_runtime_support_values(self): + self.build() + _, process, _, _ = lldbutil.run_to_source_breakpoint( + self, 'break here', lldb.SBFileSpec('main.mm')) + + var_opts = lldb.SBVariablesOptions() + var_opts.SetIncludeArguments(True) + var_opts.SetIncludeLocals(True) + var_opts.SetInScopeOnly(True) + var_opts.SetIncludeStatics(False) + var_opts.SetIncludeRuntimeSupportValues(False) + var_opts.SetUseDynamic(lldb.eDynamicCanRunTarget) + values = self.frame().GetVariables(var_opts) + + def shows_var(name): + for value in values: + if value.name == name: + return True + return False + # ObjC method. + values = self.frame().GetVariables(var_opts) + self.assertFalse(shows_var("this")) + self.assertTrue(shows_var("self")) + self.assertTrue(shows_var("_cmd")) + self.assertTrue(shows_var("c")) + + process.Continue() + # C++ method. + values = self.frame().GetVariables(var_opts) + self.assertTrue(shows_var("this")) + self.assertFalse(shows_var("self")) + self.assertFalse(shows_var("_cmd")) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/hide-runtime-values/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/hide-runtime-values/main.mm new file mode 100644 index 00000000000..c192f386f22 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/hide-runtime-values/main.mm @@ -0,0 +1,28 @@ +#import <Foundation/Foundation.h> + +void baz() {} + +struct MyClass { + void bar() { + baz(); // break here + } +}; + +@interface MyObject : NSObject {} +- (void)foo; +@end + +@implementation MyObject +- (void)foo { + MyClass c; + c.bar(); // break here +} +@end + +int main (int argc, char const *argv[]) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + id obj = [MyObject new]; + [obj foo]; + [pool release]; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py new file mode 100644 index 00000000000..19832aefee9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py @@ -0,0 +1,7 @@ +from lldbsuite.test import decorators +from lldbsuite.test import lldbinline + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, + decorators.skipIfWindows, decorators.skipIfNetBSD]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/main.mm new file mode 100644 index 00000000000..36eda1da2ac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/main.mm @@ -0,0 +1,33 @@ +#import <Foundation/Foundation.h> + +#include <vector> + +@interface MyElement : NSObject { +} +@end + +@interface MyClass : NSObject { + std::vector<MyElement *> elements; +}; + +-(void)doSomething; + +@end + +@implementation MyClass + +-(void)doSomething +{ + NSLog(@"Hello"); //% self.expect("expression -- elements", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["vector", "MyElement"]); +} + +@end + +int main () +{ + @autoreleasepool + { + MyClass *c = [MyClass alloc]; + [c doSomething]; + } +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/sample/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/sample/Makefile new file mode 100644 index 00000000000..3af75c304c3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/sample/Makefile @@ -0,0 +1,4 @@ +OBJCXX_SOURCES := main.mm +LD_EXTRAS := -lobjc -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/sample/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/sample/main.mm new file mode 100644 index 00000000000..c9a2172c368 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lang/objcxx/sample/main.mm @@ -0,0 +1,71 @@ +#import <Foundation/Foundation.h> +#include <iostream> + +@interface MyString : NSObject { + NSString *_string; + NSDate *_date; +} +- (id)initWithNSString:(NSString *)string; + +@property (copy) NSString *string; +@property (readonly,getter=getTheDate) NSDate *date; + +- (NSDate *) getTheDate; +@end + +@implementation MyString + +@synthesize string = _string; +@synthesize date = _date; + +- (id)initWithNSString:(NSString *)string +{ + if (self = [super init]) + { + _string = [NSString stringWithString:string]; + _date = [NSDate date]; + } + return self; +} + +- (void) dealloc +{ + [_date release]; + [_string release]; + [super dealloc]; +} + +- (NSDate *) getTheDate +{ + return _date; +} + +- (NSString *)description +{ + return [_string stringByAppendingFormat:@" with timestamp: %@", _date]; +} +@end + +int main (int argc, char const *argv[]) +{ + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + static NSString *g_global_nsstr = @"Howdy"; + + MyString *myStr = [[MyString alloc] initWithNSString: [NSString stringWithFormat:@"string %i", 1]]; + NSString *str1 = myStr.string; + NSString *str2 = [NSString stringWithFormat:@"string %i", 2]; + NSString *str3 = [NSString stringWithFormat:@"string %i", 3]; + NSArray *array = [NSArray arrayWithObjects: str1, str2, str3, nil]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: + str1, @"1", + str2, @"2", + str3, @"3", + myStr.date, @"date", + nil]; + + id str_id = str1; + SEL sel = @selector(length); + [pool release]; + std::cout << "Hello, objc++!\n"; + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/add-symbols/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/add-symbols/Makefile new file mode 100644 index 00000000000..98042d61ea5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/add-symbols/Makefile @@ -0,0 +1,12 @@ +CXX_SOURCES := main.cpp +LD_EXTRAS := -Wl,--build-id=none + +all: stripped.out + +stripped.out : a.out + $(OBJCOPY) --remove-section=.note.gnu.build-id --remove-section=.gnu_debuglink --strip-debug $< $@ + +clean:: + $(RM) stripped.out + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/add-symbols/TestTargetSymbolsAddCommand.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/add-symbols/TestTargetSymbolsAddCommand.py new file mode 100644 index 00000000000..33975d2583d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/add-symbols/TestTargetSymbolsAddCommand.py @@ -0,0 +1,50 @@ +""" Testing explicit symbol loading via target symbols add. """ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TargetSymbolsAddCommand(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + self.source = 'main.c' + + @no_debug_info_test # Prevent the genaration of the dwarf version of this test + @skipUnlessPlatform(['linux']) + def test_target_symbols_add(self): + """Test that 'target symbols add' can load the symbols + even if gnu.build-id and gnu_debuglink are not present in the module. + Similar to test_add_dsym_mid_execution test for macos.""" + self.build() + exe = self.getBuildArtifact("stripped.out") + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + main_bp = self.target.BreakpointCreateByName("main", "stripped.out") + self.assertTrue(main_bp, VALID_BREAKPOINT) + + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(self.process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.assertTrue(self.process.GetState() == lldb.eStateStopped, + STOPPED_DUE_TO_BREAKPOINT) + + exe_module = self.target.GetModuleAtIndex(0) + + # Check that symbols are not loaded and main.c is not know to be + # the source file. + self.expect("frame select", substrs=['main.c'], matching=False) + + # Tell LLDB that a.out has symbols for stripped.out + self.runCmd("target symbols add -s %s %s" % + (exe, self.getBuildArtifact("a.out"))) + + # Check that symbols are now loaded and main.c is in the output. + self.expect("frame select", substrs=['main.c']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/add-symbols/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/add-symbols/main.c new file mode 100644 index 00000000000..5a0915746b7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/add-symbols/main.c @@ -0,0 +1,6 @@ +#include <stdio.h> +static int var = 5; +int main() { + printf("%p is %d\n", &var, var); + return ++var; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py new file mode 100644 index 00000000000..22de873e29f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py @@ -0,0 +1,51 @@ +""" +Test lldb ability to unwind a stack with a function containing a call to the +'__builtin_trap' intrinsic, which GCC (4.6) encodes to an illegal opcode. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BuiltinTrapTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break at. + self.line = line_number('main.cpp', '// Set break point at this line.') + + # gcc generates incorrect linetable + @expectedFailureAll(archs="arm", compiler="gcc", triple=".*-android") + @expectedFailureAll(oslist=['linux'], archs=['arm', 'aarch64']) + @skipIfWindows + def test_with_run_command(self): + """Test that LLDB handles a function with __builtin_trap correctly.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # print backtrace, expect both 'bar' and 'main' functions to be listed + self.expect('bt', substrs=['bar', 'main']) + + # go up one frame + self.runCmd("up", RUN_SUCCEEDED) + + # evaluate a local + self.expect('p foo', substrs=['= 5']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/main.cpp new file mode 100644 index 00000000000..f005e697c8e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/builtin_trap/main.cpp @@ -0,0 +1,16 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +void bar(int const *foo) { + __builtin_trap(); // Set break point at this line. +} + +int main() { + int foo = 5; + bar(&foo); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/Makefile new file mode 100644 index 00000000000..4f3dd568d5f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/Makefile @@ -0,0 +1,8 @@ +C_SOURCES := a.c b.c +a.o: CFLAGS_EXTRAS := -gsplit-dwarf + +include Makefile.rules + +.PHONY: clean +clean:: + $(RM) -f a.dwo a.o b.o main diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/TestMixedDwarfBinary.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/TestMixedDwarfBinary.py new file mode 100644 index 00000000000..7c7c76d682e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/TestMixedDwarfBinary.py @@ -0,0 +1,41 @@ +""" Testing debugging of a binary with "mixed" dwarf (with/without fission). """ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestMixedDwarfBinary(TestBase): + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test # Prevent the genaration of the dwarf version of this test + @add_test_categories(["dwo"]) + @skipUnlessPlatform(["linux"]) + def test_mixed_dwarf(self): + """Test that 'frame variable' works + for the executable built from two source files compiled + with/whithout -gsplit-dwarf correspondingly.""" + + self.build() + exe = self.getBuildArtifact("a.out") + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + main_bp = self.target.BreakpointCreateByName("g", "a.out") + self.assertTrue(main_bp, VALID_BREAKPOINT) + + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(self.process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.assertTrue(self.process.GetState() == lldb.eStateStopped, + STOPPED_DUE_TO_BREAKPOINT) + + frame = self.process.GetThreadAtIndex(0).GetFrameAtIndex(0) + x = frame.FindVariable("x") + self.assertTrue(x.IsValid(), "x is not valid") + y = frame.FindVariable("y") + self.assertTrue(y.IsValid(), "y is not valid") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/a.c new file mode 100644 index 00000000000..047e78a9b29 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/a.c @@ -0,0 +1,3 @@ +int f() { + return 1; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/b.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/b.c new file mode 100644 index 00000000000..d79970e13d4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/mix-dwo-and-regular-objects/b.c @@ -0,0 +1,11 @@ +extern int f(); + +void g() { + int y = 14; + int x = f(); +} + +int main() { + g(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/sepdebugsymlink/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/sepdebugsymlink/Makefile new file mode 100644 index 00000000000..a290c8c6f2e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/sepdebugsymlink/Makefile @@ -0,0 +1,19 @@ +C_SOURCES := main.c + +all: dirsymlink + +dirreal: a.out + $(RM) -r $@ + mkdir $@ + $(OBJCOPY) --only-keep-debug $< $@/stripped.debug + $(OBJCOPY) --strip-all --add-gnu-debuglink=$@/stripped.debug $< $@/stripped.out + +dirsymlink: dirreal + $(RM) -r $@ + mkdir $@ + ln -s ../$</stripped.out $@/stripped.symlink + +clean:: + $(RM) -r dirreal dirsymlink + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/sepdebugsymlink/TestTargetSymbolsSepDebugSymlink.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/sepdebugsymlink/TestTargetSymbolsSepDebugSymlink.py new file mode 100644 index 00000000000..7338332dcfc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/sepdebugsymlink/TestTargetSymbolsSepDebugSymlink.py @@ -0,0 +1,20 @@ +""" Testing separate debug info loading for base binary with a symlink. """ +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestTargetSymbolsSepDebugSymlink(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @no_debug_info_test # Prevent the genaration of the dwarf version of this test + @skipUnlessPlatform(['linux']) + @skipIf(hostoslist=["windows"]) + @skipIfRemote # llvm.org/pr36237 + def test_target_symbols_sepdebug_symlink_case(self): + self.build() + exe = self.getBuildArtifact("dirsymlink/stripped.symlink") + + lldbutil.run_to_name_breakpoint(self, "main", exe_name = exe) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/sepdebugsymlink/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/sepdebugsymlink/main.c new file mode 100644 index 00000000000..4cce7f667ff --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/sepdebugsymlink/main.c @@ -0,0 +1,3 @@ +int main() { + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/Makefile new file mode 100644 index 00000000000..566938ca0cc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp +ENABLE_THREADS := YES +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py new file mode 100644 index 00000000000..c4d6461ddde --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py @@ -0,0 +1,83 @@ +""" +This tests that we do not lose control of the inferior, while doing an instruction-level step +over a thread creation instruction. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CreateDuringInstructionStepTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @skipUnlessPlatform(['linux']) + @expectedFailureAndroid('llvm.org/pr24737', archs=['arm']) + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + bugnumber="llvm.org/pr24737") + def test_step_inst(self): + self.build(dictionary=self.getBuildFlags()) + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target and target.IsValid(), "Target is valid") + + # This should create a breakpoint in the stepping thread. + breakpoint = target.BreakpointCreateByName("main") + self.assertTrue( + breakpoint and breakpoint.IsValid(), + "Breakpoint is valid") + + # Run the program. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertEqual(len(threads), 1, STOPPED_DUE_TO_BREAKPOINT) + + thread = threads[0] + self.assertTrue(thread and thread.IsValid(), "Thread is valid") + + # Make sure we see only one threads + self.assertEqual( + process.GetNumThreads(), + 1, + 'Number of expected threads and actual threads do not match.') + + # Keep stepping until we see the thread creation + while process.GetNumThreads() < 2: + thread.StepInstruction(False) + self.assertEqual( + process.GetState(), + lldb.eStateStopped, + PROCESS_STOPPED) + self.assertEqual( + thread.GetStopReason(), + lldb.eStopReasonPlanComplete, + "Step operation succeeded") + if self.TraceOn(): + self.runCmd("disassemble --pc") + + if self.TraceOn(): + self.runCmd("thread list") + + # We have successfully caught thread creation. Now just run to + # completion + process.Continue() + + # At this point, the inferior process should have exited. + self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/main.cpp new file mode 100644 index 00000000000..4488f2310d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/main.cpp @@ -0,0 +1,54 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// This file deliberately uses low level linux-specific API for thread creation because: +// - instruction-stepping over thread creation using higher-level functions was very slow +// - it was also unreliable due to single-stepping bugs unrelated to this test +// - some threading libraries do not create or destroy threads when we would expect them to + +#include <sched.h> + +#include <atomic> +#include <cstdio> + +enum { STACK_SIZE = 0x2000 }; + +static uint8_t child_stack[STACK_SIZE]; + +pid_t child_tid; + +std::atomic<bool> flag(false); + +int thread_main(void *) +{ + while (! flag) // Make sure the thread does not exit prematurely + ; + + return 0; +} + +int main () +{ + int ret = clone(thread_main, + child_stack + STACK_SIZE/2, // Don't care whether the stack grows up or down, + // just point to the middle + CLONE_CHILD_CLEARTID | CLONE_FILES | CLONE_FS | CLONE_PARENT_SETTID | + CLONE_SIGHAND | CLONE_SYSVSEM | CLONE_THREAD | CLONE_VM, + nullptr, // thread_main argument + &child_tid); + + if (ret == -1) + { + perror("clone"); + return 1; + } + + flag = true; + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldb_pylint_helper.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldb_pylint_helper.py new file mode 100644 index 00000000000..c8b25dfb5ca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldb_pylint_helper.py @@ -0,0 +1,180 @@ +""" +Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +See https://llvm.org/LICENSE.txt for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +Sync lldb and related source from a local machine to a remote machine. + +This facilitates working on the lldb sourcecode on multiple machines +and multiple OS types, verifying changes across all. + +Provides helper support for adding lldb test paths to the python path. +""" + +from __future__ import print_function +from __future__ import absolute_import + +# System modules +import os +import platform +import subprocess +import sys + +# Third-party modules + +# LLDB modules + + +def add_lldb_test_paths(check_dir): + # pylint: disable=line-too-long + """Adds lldb test-related paths to the python path. + + Starting with the given directory and working upward through + each parent directory up to the root, it looks for the lldb + test directory. When found, the lldb test directory and its + child test_runner/lib directory will be added to the python + system path. + + Instructions for use: + + This method supports a simple way of getting pylint to be able + to reliably lint lldb python test scripts (including the test + infrastructure itself). To do so, add the following to a + .pylintrc file in your home directory: + + [Master] + init-hook='import os; import sys; sys.path.append(os.path.expanduser("~/path/to/lldb/packages/Python/lldbsuite/test")); import lldb_pylint_helper; lldb_pylint_helper.add_lldb_test_paths(os.getcwd()); print("sys.path={}\n".format(sys.path))' + + Replace ~/path/to/lldb with a valid path to your local lldb source + tree. Note you can have multiple lldb source trees on your system, and + this will work just fine. The path in your .pylintrc is just needed to + find the paths needed for pylint in whatever lldb source tree you're in. + pylint will use the python files in whichever tree it is run from. + + Note it is critical that the init-hook line be contained on a single line. + You can remove the print line at the end once you know the pythonpath is + getting set up the way you expect. + + With these changes, you will be able to run the following, for example. + + cd lldb/sourcetree/1-of-many/test/lang/c/anonymous + pylint TestAnonymous.py + + This will work, and include all the lldb/sourcetree/1-of-many lldb-specific + python directories to your path. + + You can then run it in another lldb source tree on the same machine like + so: + + cd lldb/sourcetree/2-of-many/test/functionalities/inferior-assert + pyline TestInferiorAssert.py + + and this will properly lint that file, using the lldb-specific python + directories from the 2-of-many source tree. + + Note at the time I'm writing this, our tests are in pretty sad shape + as far as a stock pylint setup goes. But we need to start somewhere :-) + + @param check_dir specifies a directory that will be used to start + looking for the lldb test infrastructure python library paths. + """ + # Add the test-related packages themselves. + add_lldb_test_package_paths(check_dir) + + # Add the lldb directory itself + add_lldb_module_directory() + + +def add_lldb_module_directory(): + """ + Desired Approach: + + Part A: find an lldb + + 1. Walk up the parent chain from the current directory, looking for + a directory matching *build*. If we find that, use it as the + root of a directory search for an lldb[.exe] executable. + + 2. If 1 fails, use the path and look for an lldb[.exe] in there. + + If Part A ends up with an lldb, go to part B. Otherwise, give up + on the lldb python module path. + + Part B: use the output from 'lldb[.exe] -P' to find the lldb dir. + + Current approach: + If Darwin, use 'xcrun lldb -P'; others: find lldb on path. + + Drawback to current approach: + If the tester is changing the SB API (adding new methods), pylint + will not know about them as it is using the wrong lldb python module. + In practice, this should be minor. + """ + try: + lldb_module_path = None + + if platform.system() == 'Darwin': + # Use xcrun to find the selected lldb. + lldb_module_path = subprocess.check_output(["xcrun", "lldb", "-P"]) + elif platform.system() == 'Windows': + lldb_module_path = subprocess.check_output( + ["lldb.exe", "-P"], shell=True) + else: + # Use the shell to run lldb from the path. + lldb_module_path = subprocess.check_output( + ["lldb", "-P"], shell=True) + + # Trim the result. + if lldb_module_path is not None: + lldb_module_path = lldb_module_path.strip() + + # If we have a result, add it to the path + if lldb_module_path is not None and len(lldb_module_path) > 0: + sys.path.insert(0, lldb_module_path) + # pylint: disable=broad-except + except Exception as exception: + print("failed to find python path: {}".format(exception)) + + +def add_lldb_test_package_paths(check_dir): + """Adds the lldb test infrastructure modules to the python path. + + See add_lldb_test_paths for more details. + + @param check_dir the directory of the test. + """ + + def child_dirs(parent_dir): + return [os.path.join(parent_dir, child) + for child in os.listdir(parent_dir) + if os.path.isdir(os.path.join(parent_dir, child))] + + check_dir = os.path.realpath(check_dir) + while check_dir and len(check_dir) > 0: + # If the current directory contains a packages/Python + # directory, add that directory to the path. + packages_python_child_dir = os.path.join( + check_dir, "packages", "Python") + if os.path.exists(packages_python_child_dir): + sys.path.insert(0, packages_python_child_dir) + sys.path.insert(0, os.path.join( + packages_python_child_dir, "test_runner", "lib")) + + # Handle third_party module/package directory. + third_party_module_dir = os.path.join( + check_dir, "third_party", "Python", "module") + for child_dir in child_dirs(third_party_module_dir): + # Yes, we embed the module in the module parent dir + sys.path.insert(0, child_dir) + + # We're done. + break + + # Continue looking up the parent chain until we have no more + # directories to check. + new_check_dir = os.path.dirname(check_dir) + # We're done when the new check dir is not different + # than the current one. + if new_check_dir == check_dir: + break + check_dir = new_check_dir diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbbench.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbbench.py new file mode 100644 index 00000000000..26ee6c21bd9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbbench.py @@ -0,0 +1,118 @@ +from __future__ import absolute_import + +# System modules +import time + +# Third-party modules + +# LLDB modules +from .lldbtest import * + + +class Stopwatch(object): + """Stopwatch provides a simple utility to start/stop your stopwatch multiple + times. Each start/stop is equal to a lap, with its elapsed time accumulated + while measurment is in progress. + + When you're ready to start from scratch for another round of measurements, + be sure to call the reset() method. + + For example, + + sw = Stopwatch() + for i in range(1000): + with sw: + # Do some length operations... + ... + # Get the average time. + avg_time = sw.avg() + + # Reset the stopwatch as we are about to perform other kind of operations. + sw.reset() + ... + """ + + ############################################################# + # + # Context manager interfaces to support the 'with' statement. + # + ############################################################# + + def __enter__(self): + """ + Context management protocol on entry to the body of the with statement. + """ + return self.start() + + def __exit__(self, type, value, tb): + """ + Context management protocol on exit from the body of the with statement. + """ + self.stop() + + def reset(self): + self.__laps__ = 0 + self.__total_elapsed__ = 0.0 + self.__start__ = None + self.__stop__ = None + self.__elapsed__ = 0.0 + self.__nums__ = [] + + def __init__(self): + self.reset() + + def start(self): + if self.__start__ is None: + self.__start__ = time.time() + else: + raise Exception( + "start() already called, did you forget to stop() first?") + # Return self to facilitate the context manager __enter__ protocol. + return self + + def stop(self): + if self.__start__ is not None: + self.__stop__ = time.time() + elapsed = self.__stop__ - self.__start__ + self.__total_elapsed__ += elapsed + self.__laps__ += 1 + self.__nums__.append(elapsed) + self.__start__ = None # Reset __start__ to be None again. + else: + raise Exception("stop() called without first start()?") + + def laps(self): + """Gets the number of laps. One lap is equal to a start/stop action.""" + return self.__laps__ + + def avg(self): + """Equal to total elapsed time divided by the number of laps.""" + return self.__total_elapsed__ / self.__laps__ + + # def sigma(self): + # """Return the standard deviation of the available samples.""" + # if self.__laps__ <= 0: + # return None + # return numpy.std(self.__nums__) + + def __str__(self): + return "Avg: %f (Laps: %d, Total Elapsed Time: %f, min=%f, max=%f)" % (self.avg( + ), self.__laps__, self.__total_elapsed__, min(self.__nums__), max(self.__nums__)) + + +class BenchBase(TestBase): + """ + Abstract base class for benchmark tests. + """ + + def setUp(self): + """Fixture for unittest test case setup.""" + super(BenchBase, self).setUp() + # TestBase.setUp(self) + self.stopwatch = Stopwatch() + + def tearDown(self): + """Fixture for unittest test case teardown.""" + super(BenchBase, self).tearDown() + # TestBase.tearDown(self) + del self.stopwatch diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbdwarf.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbdwarf.py new file mode 100644 index 00000000000..217f8bc0e2b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbdwarf.py @@ -0,0 +1,256 @@ +""" This module implement Dwarf expression opcode parser. """ + +import lldb + +# DWARF Expression operators. +DW_OP_addr = 0x03 +DW_OP_deref = 0x06 +DW_OP_const1u = 0x08 +DW_OP_const1s = 0x09 +DW_OP_const2u = 0x0A +DW_OP_const2s = 0x0B +DW_OP_const4u = 0x0C +DW_OP_const4s = 0x0D +DW_OP_const8u = 0x0E +DW_OP_const8s = 0x0F +DW_OP_constu = 0x10 +DW_OP_consts = 0x11 +DW_OP_dup = 0x12 +DW_OP_drop = 0x13 +DW_OP_over = 0x14 +DW_OP_pick = 0x15 +DW_OP_swap = 0x16 +DW_OP_rot = 0x17 +DW_OP_xderef = 0x18 +DW_OP_abs = 0x19 +DW_OP_and = 0x1A +DW_OP_div = 0x1B +DW_OP_minus = 0x1C +DW_OP_mod = 0x1D +DW_OP_mul = 0x1E +DW_OP_neg = 0x1F +DW_OP_not = 0x20 +DW_OP_or = 0x21 +DW_OP_plus = 0x22 +DW_OP_plus_uconst = 0x23 +DW_OP_shl = 0x24 +DW_OP_shr = 0x25 +DW_OP_shra = 0x26 +DW_OP_xor = 0x27 +DW_OP_skip = 0x2F +DW_OP_bra = 0x28 +DW_OP_eq = 0x29 +DW_OP_ge = 0x2A +DW_OP_gt = 0x2B +DW_OP_le = 0x2C +DW_OP_lt = 0x2D +DW_OP_ne = 0x2E +DW_OP_lit0 = 0x30 +DW_OP_lit1 = 0x31 +DW_OP_lit2 = 0x32 +DW_OP_lit3 = 0x33 +DW_OP_lit4 = 0x34 +DW_OP_lit5 = 0x35 +DW_OP_lit6 = 0x36 +DW_OP_lit7 = 0x37 +DW_OP_lit8 = 0x38 +DW_OP_lit9 = 0x39 +DW_OP_lit10 = 0x3A +DW_OP_lit11 = 0x3B +DW_OP_lit12 = 0x3C +DW_OP_lit13 = 0x3D +DW_OP_lit14 = 0x3E +DW_OP_lit15 = 0x3F +DW_OP_lit16 = 0x40 +DW_OP_lit17 = 0x41 +DW_OP_lit18 = 0x42 +DW_OP_lit19 = 0x43 +DW_OP_lit20 = 0x44 +DW_OP_lit21 = 0x45 +DW_OP_lit22 = 0x46 +DW_OP_lit23 = 0x47 +DW_OP_lit24 = 0x48 +DW_OP_lit25 = 0x49 +DW_OP_lit26 = 0x4A +DW_OP_lit27 = 0x4B +DW_OP_lit28 = 0x4C +DW_OP_lit29 = 0x4D +DW_OP_lit30 = 0x4E +DW_OP_lit31 = 0x4F +DW_OP_reg0 = 0x50 +DW_OP_reg1 = 0x51 +DW_OP_reg2 = 0x52 +DW_OP_reg3 = 0x53 +DW_OP_reg4 = 0x54 +DW_OP_reg5 = 0x55 +DW_OP_reg6 = 0x56 +DW_OP_reg7 = 0x57 +DW_OP_reg8 = 0x58 +DW_OP_reg9 = 0x59 +DW_OP_reg10 = 0x5A +DW_OP_reg11 = 0x5B +DW_OP_reg12 = 0x5C +DW_OP_reg13 = 0x5D +DW_OP_reg14 = 0x5E +DW_OP_reg15 = 0x5F +DW_OP_reg16 = 0x60 +DW_OP_reg17 = 0x61 +DW_OP_reg18 = 0x62 +DW_OP_reg19 = 0x63 +DW_OP_reg20 = 0x64 +DW_OP_reg21 = 0x65 +DW_OP_reg22 = 0x66 +DW_OP_reg23 = 0x67 +DW_OP_reg24 = 0x68 +DW_OP_reg25 = 0x69 +DW_OP_reg26 = 0x6A +DW_OP_reg27 = 0x6B +DW_OP_reg28 = 0x6C +DW_OP_reg29 = 0x6D +DW_OP_reg30 = 0x6E +DW_OP_reg31 = 0x6F +DW_OP_breg0 = 0x70 +DW_OP_breg1 = 0x71 +DW_OP_breg2 = 0x72 +DW_OP_breg3 = 0x73 +DW_OP_breg4 = 0x74 +DW_OP_breg5 = 0x75 +DW_OP_breg6 = 0x76 +DW_OP_breg7 = 0x77 +DW_OP_breg8 = 0x78 +DW_OP_breg9 = 0x79 +DW_OP_breg10 = 0x7A +DW_OP_breg11 = 0x7B +DW_OP_breg12 = 0x7C +DW_OP_breg13 = 0x7D +DW_OP_breg14 = 0x7E +DW_OP_breg15 = 0x7F +DW_OP_breg16 = 0x80 +DW_OP_breg17 = 0x81 +DW_OP_breg18 = 0x82 +DW_OP_breg19 = 0x83 +DW_OP_breg20 = 0x84 +DW_OP_breg21 = 0x85 +DW_OP_breg22 = 0x86 +DW_OP_breg23 = 0x87 +DW_OP_breg24 = 0x88 +DW_OP_breg25 = 0x89 +DW_OP_breg26 = 0x8A +DW_OP_breg27 = 0x8B +DW_OP_breg28 = 0x8C +DW_OP_breg29 = 0x8D +DW_OP_breg30 = 0x8E +DW_OP_breg31 = 0x8F +DW_OP_regx = 0x90 +DW_OP_fbreg = 0x91 +DW_OP_bregx = 0x92 +DW_OP_piece = 0x93 +DW_OP_deref_size = 0x94 +DW_OP_xderef_size = 0x95 +DW_OP_nop = 0x96 +DW_OP_push_object_address = 0x97 +DW_OP_call2 = 0x98 +DW_OP_call4 = 0x99 +DW_OP_call_ref = 0x9A +DW_OP_form_tls_address = 0x9B +DW_OP_call_frame_cfa = 0x9C +DW_OP_bit_piece = 0x9D +DW_OP_implicit_value = 0x9E +DW_OP_stack_value = 0x9F +DW_OP_lo_user = 0xE0 +DW_OP_GNU_push_tls_address = 0xE0 +DW_OP_APPLE_uninit = 0xF0 +DW_OP_hi_user = 0xFF + + +class DwarfOpcodeParser(object): + + def updateRegInfoBitsize(self, reg_info, byte_order): + """ Update the regInfo bit size. """ + + # Evaluate Dwarf Expression + expr_result = self.evaluateDwarfExpression(reg_info["dynamic_size_dwarf_expr_bytes"], + byte_order) + + if expr_result == 0: + reg_info["bitsize"] = 32 + elif expr_result == 1: + reg_info["bitsize"] = 64 + + + def evaluateDwarfExpression(self, dwarf_opcode, byte_order): + """Evaluate Dwarf Expression. """ + + dwarf_opcode = [dwarf_opcode[i:i+2] for i in range(0,len(dwarf_opcode),2)] + dwarf_data = [] + for index in range(len(dwarf_opcode)): + + if index < len(dwarf_opcode): + val = int(dwarf_opcode[index], 16) + else: + break + + if val == DW_OP_regx: + # Read register number + self.assertTrue(len(dwarf_opcode) > (index + 1)) + reg_no = int(dwarf_opcode.pop(index + 1), 16) + + self.reset_test_sequence() + # Read register value + self.test_sequence.add_log_lines( + ["read packet: $p{0:x}#00".format(reg_no), + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", + "capture": {1: "p_response"}}],True) + + Context = self.expect_gdbremote_sequence() + self.assertIsNotNone(Context) + p_response = Context.get("p_response") + self.assertIsNotNone(p_response) + + if byte_order == lldb.eByteOrderLittle: + # In case of little endian + # first decode the HEX ASCII bytes and then reverse it + # to get actual value of SR register + p_response = "".join(reversed([p_response[i:i+2] for i in range(0, + len(p_response),2)])) + # Push register value + dwarf_data.append(int(p_response,16)) + + elif val == DW_OP_lit1: + # Push literal 1 + dwarf_data.append(1) + + elif val == DW_OP_lit26: + # Push literal 26 + dwarf_data.append(26) + + elif val == DW_OP_shl: + # left shift and push the result back + self.assertTrue(len(dwarf_data) > 1) + shift_amount = dwarf_data.pop() + val_to_shift = dwarf_data.pop() + result = val_to_shift << shift_amount + dwarf_data.append(result) + + elif val == DW_OP_shr: + # Right shift and push the result back + self.assertTrue(len(dwarf_data) > 1) + shift_amount = dwarf_data.pop() + val_to_shift = dwarf_data.pop() + result = val_to_shift >> shift_amount + dwarf_data.append(result) + + elif val == DW_OP_and: + # And of topmost 2 elements and push the result back + first_ele = dwarf_data.pop() + second_ele = dwarf_data.pop() + result = first_ele & second_ele + dwarf_data.append(result) + + else: + self.assertTrue(False and "Unprocess Dwarf Opcode") + + self.assertTrue(len(dwarf_data) == 1) + expr_result = dwarf_data.pop() + return expr_result + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbinline.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbinline.py new file mode 100644 index 00000000000..22668b673fd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbinline.py @@ -0,0 +1,207 @@ +from __future__ import print_function +from __future__ import absolute_import + +# System modules +import os + +# Third-party modules +import io + +# LLDB modules +import lldb +from .lldbtest import * +from . import configuration +from . import lldbutil +from .decorators import * + +def source_type(filename): + _, extension = os.path.splitext(filename) + return { + '.c': 'C_SOURCES', + '.cpp': 'CXX_SOURCES', + '.cxx': 'CXX_SOURCES', + '.cc': 'CXX_SOURCES', + '.m': 'OBJC_SOURCES', + '.mm': 'OBJCXX_SOURCES' + }.get(extension, None) + + +class CommandParser: + + def __init__(self): + self.breakpoints = [] + + def parse_one_command(self, line): + parts = line.split('//%') + + command = None + new_breakpoint = True + + if len(parts) == 2: + command = parts[1].strip() # take off whitespace + new_breakpoint = parts[0].strip() != "" + + return (command, new_breakpoint) + + def parse_source_files(self, source_files): + for source_file in source_files: + file_handle = io.open(source_file, encoding='utf-8') + lines = file_handle.readlines() + line_number = 0 + # non-NULL means we're looking through whitespace to find + # additional commands + current_breakpoint = None + for line in lines: + line_number = line_number + 1 # 1-based, so we do this first + (command, new_breakpoint) = self.parse_one_command(line) + + if new_breakpoint: + current_breakpoint = None + + if command is not None: + if current_breakpoint is None: + current_breakpoint = {} + current_breakpoint['file_name'] = source_file + current_breakpoint['line_number'] = line_number + current_breakpoint['command'] = command + self.breakpoints.append(current_breakpoint) + else: + current_breakpoint['command'] = current_breakpoint[ + 'command'] + "\n" + command + + def set_breakpoints(self, target): + for breakpoint in self.breakpoints: + breakpoint['breakpoint'] = target.BreakpointCreateByLocation( + breakpoint['file_name'], breakpoint['line_number']) + + def handle_breakpoint(self, test, breakpoint_id): + for breakpoint in self.breakpoints: + if breakpoint['breakpoint'].GetID() == breakpoint_id: + test.execute_user_command(breakpoint['command']) + return + + +class InlineTest(TestBase): + # Internal implementation + + def BuildMakefile(self): + makefilePath = self.getBuildArtifact("Makefile") + if os.path.exists(makefilePath): + return + + categories = {} + + for f in os.listdir(self.getSourceDir()): + t = source_type(f) + if t: + if t in list(categories.keys()): + categories[t].append(f) + else: + categories[t] = [f] + + makefile = open(makefilePath, 'w+') + + for t in list(categories.keys()): + line = t + " := " + " ".join(categories[t]) + makefile.write(line + "\n") + + if ('OBJCXX_SOURCES' in list(categories.keys())) or ( + 'OBJC_SOURCES' in list(categories.keys())): + makefile.write( + "LDFLAGS = $(CFLAGS) -lobjc -framework Foundation\n") + + if ('CXX_SOURCES' in list(categories.keys())): + makefile.write("CXXFLAGS += -std=c++11\n") + + makefile.write("include Makefile.rules\n") + makefile.write("\ncleanup:\n\trm -f Makefile *.d\n\n") + makefile.flush() + makefile.close() + + def _test(self): + self.BuildMakefile() + self.build() + self.do_test() + + def execute_user_command(self, __command): + exec(__command, globals(), locals()) + + def do_test(self): + exe = self.getBuildArtifact("a.out") + source_files = [f for f in os.listdir(self.getSourceDir()) + if source_type(f)] + target = self.dbg.CreateTarget(exe) + + parser = CommandParser() + parser.parse_source_files(source_files) + parser.set_breakpoints(target) + + process = target.LaunchSimple(None, None, self.get_process_working_directory()) + hit_breakpoints = 0 + + while lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint): + hit_breakpoints += 1 + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + breakpoint_id = thread.GetStopReasonDataAtIndex(0) + parser.handle_breakpoint(self, breakpoint_id) + process.Continue() + + self.assertTrue(hit_breakpoints > 0, + "inline test did not hit a single breakpoint") + # Either the process exited or the stepping plan is complete. + self.assertTrue(process.GetState() in [lldb.eStateStopped, + lldb.eStateExited], + PROCESS_EXITED) + + # Utilities for testcases + + def check_expression(self, expression, expected_result, use_summary=True): + value = self.frame().EvaluateExpression(expression) + self.assertTrue(value.IsValid(), expression + "returned a valid value") + if self.TraceOn(): + print(value.GetSummary()) + print(value.GetValue()) + if use_summary: + answer = value.GetSummary() + else: + answer = value.GetValue() + report_str = "%s expected: %s got: %s" % ( + expression, expected_result, answer) + self.assertTrue(answer == expected_result, report_str) + + +def ApplyDecoratorsToFunction(func, decorators): + tmp = func + if isinstance(decorators, list): + for decorator in decorators: + tmp = decorator(tmp) + elif hasattr(decorators, '__call__'): + tmp = decorators(tmp) + return tmp + + +def MakeInlineTest(__file, __globals, decorators=None): + # Adjust the filename if it ends in .pyc. We want filenames to + # reflect the source python file, not the compiled variant. + if __file is not None and __file.endswith(".pyc"): + # Strip the trailing "c" + __file = __file[0:-1] + + # Derive the test name from the current file name + file_basename = os.path.basename(__file) + + test_name, _ = os.path.splitext(file_basename) + + test_func = ApplyDecoratorsToFunction(InlineTest._test, decorators) + # Build the test case + test_class = type(test_name, (InlineTest,), dict(test=test_func, name=test_name)) + + # Add the test case to the globals, and hide InlineTest + __globals.update({test_name: test_class}) + + # Keep track of the original test filename so we report it + # correctly in test results. + test_class.test_filename = __file + test_class.mydir = TestBase.compute_mydir(__file) + return test_class diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbpexpect.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbpexpect.py new file mode 100644 index 00000000000..d599bc39762 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbpexpect.py @@ -0,0 +1,68 @@ +from __future__ import absolute_import + +# System modules +import os +import sys + +# Third-party modules +import six + +# LLDB Modules +import lldb +from .lldbtest import * +from . import lldbutil + +if sys.platform.startswith('win32'): + # llvm.org/pr22274: need a pexpect replacement for windows + class PExpectTest(object): + pass +else: + import pexpect + + class PExpectTest(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + PROMPT = "(lldb) " + + def expect_prompt(self): + self.child.expect_exact(self.PROMPT) + + def launch(self, executable=None, extra_args=None, timeout=30, dimensions=None): + logfile = getattr(sys.stdout, 'buffer', + sys.stdout) if self.TraceOn() else None + + args = ['--no-lldbinit', '--no-use-colors'] + for cmd in self.setUpCommands(): + args += ['-O', cmd] + if executable is not None: + args += ['--file', executable] + if extra_args is not None: + args.extend(extra_args) + + env = dict(os.environ) + env["TERM"]="vt100" + + self.child = pexpect.spawn( + lldbtest_config.lldbExec, args=args, logfile=logfile, + timeout=timeout, dimensions=dimensions, env=env) + self.expect_prompt() + for cmd in self.setUpCommands(): + self.child.expect_exact(cmd) + self.expect_prompt() + if executable is not None: + self.child.expect_exact("target create") + self.child.expect_exact("Current executable set to") + self.expect_prompt() + + def expect(self, cmd, substrs=None): + self.assertNotIn('\n', cmd) + self.child.sendline(cmd) + if substrs is not None: + for s in substrs: + self.child.expect_exact(s) + self.expect_prompt() + + def quit(self, gracefully=True): + self.child.sendeof() + self.child.close(force=not gracefully) + self.child = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbplatform.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbplatform.py new file mode 100644 index 00000000000..365c752758d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbplatform.py @@ -0,0 +1,48 @@ +""" This module represents an abstraction of an lldb target / host platform. """ + +from __future__ import absolute_import + +# System modules +import itertools + +# Third-party modules +import six + +# LLDB modules +import lldb + +windows, linux, macosx, darwin, ios, tvos, watchos, bridgeos, darwin_all, darwin_embedded, freebsd, netbsd, bsd_all, android = range( + 14) + +__name_lookup = { + windows: ["windows"], + linux: ["linux"], + macosx: ["macosx"], + darwin: ["darwin"], + ios: ["ios"], + tvos: ["tvos"], + watchos: ["watchos"], + bridgeos: ["bridgeos"], + darwin_all: ["macosx", "darwin", "ios", "tvos", "watchos", "bridgeos"], + darwin_embedded: ["ios", "tvos", "watchos", "bridgeos"], + freebsd: ["freebsd"], + netbsd: ["netbsd"], + bsd_all: ["freebsd", "netbsd"], + android: ["android"] +} + + +def translate(values): + + if isinstance(values, six.integer_types): + # This is a value from the platform enumeration, translate it. + return __name_lookup[values] + elif isinstance(values, six.string_types): + # This is a raw string, return it. + return [values] + elif hasattr(values, "__iter__"): + # This is an iterable, convert each item. + result = [translate(x) for x in values] + result = list(itertools.chain(*result)) + return result + return values diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py new file mode 100644 index 00000000000..02946f0398b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbplatformutil.py @@ -0,0 +1,189 @@ +""" This module contains functions used by the test cases to hide the +architecture and/or the platform dependent nature of the tests. """ + +from __future__ import absolute_import + +# System modules +import itertools +import re +import subprocess +import sys +import os + +# Third-party modules +import six +from six.moves.urllib import parse as urlparse + +# LLDB modules +from . import configuration +import lldb +import lldbsuite.test.lldbplatform as lldbplatform + + +def check_first_register_readable(test_case): + arch = test_case.getArchitecture() + + if arch in ['x86_64', 'i386']: + test_case.expect("register read eax", substrs=['eax = 0x']) + elif arch in ['arm', 'armv7', 'armv7k', 'armv8l', 'armv7l']: + test_case.expect("register read r0", substrs=['r0 = 0x']) + elif arch in ['aarch64', 'arm64', 'arm64e', 'arm64_32']: + test_case.expect("register read x0", substrs=['x0 = 0x']) + elif re.match("mips", arch): + test_case.expect("register read zero", substrs=['zero = 0x']) + elif arch in ['s390x']: + test_case.expect("register read r0", substrs=['r0 = 0x']) + elif arch in ['powerpc64le']: + test_case.expect("register read r0", substrs=['r0 = 0x']) + else: + # TODO: Add check for other architectures + test_case.fail( + "Unsupported architecture for test case (arch: %s)" % + test_case.getArchitecture()) + + +def _run_adb_command(cmd, device_id): + device_id_args = [] + if device_id: + device_id_args = ["-s", device_id] + full_cmd = ["adb"] + device_id_args + cmd + p = subprocess.Popen( + full_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + stdout, stderr = p.communicate() + return p.returncode, stdout, stderr + + +def target_is_android(): + if not hasattr(target_is_android, 'result'): + triple = lldb.DBG.GetSelectedPlatform().GetTriple() + match = re.match(".*-.*-.*-android", triple) + target_is_android.result = match is not None + return target_is_android.result + + +def android_device_api(): + if not hasattr(android_device_api, 'result'): + assert configuration.lldb_platform_url is not None + device_id = None + parsed_url = urlparse.urlparse(configuration.lldb_platform_url) + host_name = parsed_url.netloc.split(":")[0] + if host_name != 'localhost': + device_id = host_name + if device_id.startswith('[') and device_id.endswith(']'): + device_id = device_id[1:-1] + retcode, stdout, stderr = _run_adb_command( + ["shell", "getprop", "ro.build.version.sdk"], device_id) + if retcode == 0: + android_device_api.result = int(stdout) + else: + raise LookupError( + ">>> Unable to determine the API level of the Android device.\n" + ">>> stdout:\n%s\n" + ">>> stderr:\n%s\n" % + (stdout, stderr)) + return android_device_api.result + + +def match_android_device(device_arch, valid_archs=None, valid_api_levels=None): + if not target_is_android(): + return False + if valid_archs is not None and device_arch not in valid_archs: + return False + if valid_api_levels is not None and android_device_api() not in valid_api_levels: + return False + + return True + + +def finalize_build_dictionary(dictionary): + if target_is_android(): + if dictionary is None: + dictionary = {} + dictionary["OS"] = "Android" + dictionary["PIE"] = 1 + return dictionary + + +def getHostPlatform(): + """Returns the host platform running the test suite.""" + # Attempts to return a platform name matching a target Triple platform. + if sys.platform.startswith('linux'): + return 'linux' + elif sys.platform.startswith('win32') or sys.platform.startswith('cygwin'): + return 'windows' + elif sys.platform.startswith('darwin'): + return 'darwin' + elif sys.platform.startswith('freebsd'): + return 'freebsd' + elif sys.platform.startswith('netbsd'): + return 'netbsd' + else: + return sys.platform + + +def getDarwinOSTriples(): + return ['darwin', 'macosx', 'ios', 'watchos', 'tvos', 'bridgeos'] + + +def getPlatform(): + """Returns the target platform which the tests are running on.""" + triple = lldb.DBG.GetSelectedPlatform().GetTriple() + if triple is None: + # It might be an unconnected remote platform. + return '' + + platform = triple.split('-')[2] + if platform.startswith('freebsd'): + platform = 'freebsd' + elif platform.startswith('netbsd'): + platform = 'netbsd' + return platform + + +def platformIsDarwin(): + """Returns true if the OS triple for the selected platform is any valid apple OS""" + return getPlatform() in getDarwinOSTriples() + + +def findMainThreadCheckerDylib(): + if not platformIsDarwin(): + return "" + + if getPlatform() in lldbplatform.translate(lldbplatform.darwin_embedded): + return "/Developer/usr/lib/libMainThreadChecker.dylib" + + with os.popen('xcode-select -p') as output: + xcode_developer_path = output.read().strip() + mtc_dylib_path = '%s/usr/lib/libMainThreadChecker.dylib' % xcode_developer_path + if os.path.isfile(mtc_dylib_path): + return mtc_dylib_path + + return "" + + +class _PlatformContext(object): + """Value object class which contains platform-specific options.""" + + def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension): + self.shlib_environment_var = shlib_environment_var + self.shlib_prefix = shlib_prefix + self.shlib_extension = shlib_extension + + +def createPlatformContext(): + if platformIsDarwin(): + return _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib') + elif getPlatform() in ("freebsd", "linux", "netbsd"): + return _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so') + else: + return None + + +def hasChattyStderr(test_case): + """Some targets produce garbage on the standard error output. This utility function + determines whether the tests can be strict about the expected stderr contents.""" + if match_android_device(test_case.getArchitecture(), ['aarch64'], range(22, 25+1)): + return True # The dynamic linker on the device will complain about unknown DT entries + return False diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbtest.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbtest.py new file mode 100644 index 00000000000..2b83d26d234 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbtest.py @@ -0,0 +1,2520 @@ +""" +LLDB module which provides the abstract base class of lldb test case. + +The concrete subclass can override lldbtest.TesBase in order to inherit the +common behavior for unitest.TestCase.setUp/tearDown implemented in this file. + +The subclass should override the attribute mydir in order for the python runtime +to locate the individual test cases when running as part of a large test suite +or when running each test case as a separate python invocation. + +./dotest.py provides a test driver which sets up the environment to run the +entire of part of the test suite . Example: + +# Exercises the test suite in the types directory.... +/Volumes/data/lldb/svn/ToT/test $ ./dotest.py -A x86_64 types +... + +Session logs for test failures/errors/unexpected successes will go into directory '2012-05-16-13_35_42' +Command invoked: python ./dotest.py -A x86_64 types +compilers=['clang'] + +Configuration: arch=x86_64 compiler=clang +---------------------------------------------------------------------- +Collected 72 tests + +........................................................................ +---------------------------------------------------------------------- +Ran 72 tests in 135.468s + +OK +$ +""" + +from __future__ import absolute_import +from __future__ import print_function + +# System modules +import abc +from distutils.version import LooseVersion +from functools import wraps +import gc +import glob +import io +import os.path +import re +import shutil +import signal +from subprocess import * +import sys +import time +import traceback +import distutils.spawn + +# Third-party modules +import unittest2 +from six import add_metaclass +from six import StringIO as SixStringIO +import six + +# LLDB modules +import lldb +from . import configuration +from . import decorators +from . import lldbplatformutil +from . import lldbtest_config +from . import lldbutil +from . import test_categories +from lldbsuite.support import encoded_file +from lldbsuite.support import funcutils + +# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables +# LLDB_COMMAND_TRACE is set from '-t' option. + +# 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. +# + +COMMAND_FAILED_AS_EXPECTED = "Command has failed as expected" + +CURRENT_EXECUTABLE_SET = "Current executable set successfully" + +PROCESS_IS_VALID = "Process is valid" + +PROCESS_KILLED = "Process is killed successfully" + +PROCESS_EXITED = "Process exited successfully" + +PROCESS_STOPPED = "Process status should be stopped" + +RUN_SUCCEEDED = "Process is launched successfully" + +RUN_COMPLETED = "Process exited successfully" + +BACKTRACE_DISPLAYED_CORRECTLY = "Backtrace displayed correctly" + +BREAKPOINT_CREATED = "Breakpoint created successfully" + +BREAKPOINT_STATE_CORRECT = "Breakpoint state is correct" + +BREAKPOINT_PENDING_CREATED = "Pending breakpoint created successfully" + +BREAKPOINT_HIT_ONCE = "Breakpoint resolved with hit count = 1" + +BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit count = 2" + +BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit count = 3" + +MISSING_EXPECTED_REGISTERS = "At least one expected register is unavailable." + +OBJECT_PRINTED_CORRECTLY = "Object printed correctly" + +SOURCE_DISPLAYED_CORRECTLY = "Source code displayed correctly" + +STEP_OUT_SUCCEEDED = "Thread step-out succeeded" + +STOPPED_DUE_TO_EXC_BAD_ACCESS = "Process should be stopped due to bad access exception" + +STOPPED_DUE_TO_ASSERT = "Process should be stopped due to an assertion" + +STOPPED_DUE_TO_BREAKPOINT = "Process should be stopped due to breakpoint" + +STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS = "%s, %s" % ( + STOPPED_DUE_TO_BREAKPOINT, "instead, the actual stop reason is: '%s'") + +STOPPED_DUE_TO_BREAKPOINT_CONDITION = "Stopped due to breakpoint condition" + +STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT = "Stopped due to breakpoint and ignore count" + +STOPPED_DUE_TO_BREAKPOINT_JITTED_CONDITION = "Stopped due to breakpoint jitted condition" + +STOPPED_DUE_TO_SIGNAL = "Process state is stopped due to signal" + +STOPPED_DUE_TO_STEP_IN = "Process state is stopped due to step in" + +STOPPED_DUE_TO_WATCHPOINT = "Process should be stopped due to watchpoint" + +DATA_TYPES_DISPLAYED_CORRECTLY = "Data type(s) displayed correctly" + +VALID_BREAKPOINT = "Got a valid breakpoint" + +VALID_BREAKPOINT_LOCATION = "Got a valid breakpoint location" + +VALID_COMMAND_INTERPRETER = "Got a valid command interpreter" + +VALID_FILESPEC = "Got a valid filespec" + +VALID_MODULE = "Got a valid module" + +VALID_PROCESS = "Got a valid process" + +VALID_SYMBOL = "Got a valid symbol" + +VALID_TARGET = "Got a valid target" + +VALID_PLATFORM = "Got a valid platform" + +VALID_TYPE = "Got a valid type" + +VALID_VARIABLE = "Got a valid variable" + +VARIABLES_DISPLAYED_CORRECTLY = "Variable(s) displayed correctly" + +WATCHPOINT_CREATED = "Watchpoint created successfully" + + +def CMD_MSG(str): + '''A generic "Command '%s' returns successfully" message generator.''' + return "Command '%s' returns successfully" % str + + +def COMPLETION_MSG(str_before, str_after, completions): + '''A generic message generator for the completion mechanism.''' + return ("'%s' successfully completes to '%s', but completions were:\n%s" + % (str_before, str_after, "\n".join(completions))) + + +def EXP_MSG(str, actual, exe): + '''A generic "'%s' returns expected result" message generator if exe. + Otherwise, it generates "'%s' matches expected result" message.''' + + return "'%s' %s expected result, got '%s'" % ( + str, 'returns' if exe else 'matches', actual.strip()) + + +def SETTING_MSG(setting): + '''A generic "Value of setting '%s' is correct" message generator.''' + return "Value of setting '%s' is correct" % setting + + +def line_number(filename, string_to_match): + """Helper function to return the line number of the first matched string.""" + with io.open(filename, mode='r', encoding="utf-8") as f: + for i, line in enumerate(f): + if line.find(string_to_match) != -1: + # Found our match. + return i + 1 + raise Exception( + "Unable to find '%s' within file %s" % + (string_to_match, filename)) + +def get_line(filename, line_number): + """Return the text of the line at the 1-based line number.""" + with io.open(filename, mode='r', encoding="utf-8") as f: + return f.readlines()[line_number - 1] + +def pointer_size(): + """Return the pointer size of the host system.""" + import ctypes + a_pointer = ctypes.c_void_p(0xffff) + return 8 * ctypes.sizeof(a_pointer) + + +def is_exe(fpath): + """Returns true if fpath is an executable.""" + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + +def which(program): + """Returns the full path to a program; None otherwise.""" + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ["PATH"].split(os.pathsep): + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + return None + + +class recording(SixStringIO): + """ + 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 SixStringIO instance; record the session obj and trace flag.""" + SixStringIO.__init__(self) + # The test might not have undergone the 'setUp(self)' phase yet, so that + # the attribute 'session' might not even exist yet. + self.session = getattr(test, "session", None) if test else None + self.trace = trace + + def __enter__(self): + """ + Context management protocol on entry to the body of the with statement. + Just return the SixStringIO 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 SixStringIO object, too. + """ + if self.trace: + print(self.getvalue(), file=sys.stderr) + if self.session: + print(self.getvalue(), file=self.session) + self.close() + + +@add_metaclass(abc.ABCMeta) +class _BaseProcess(object): + + @abc.abstractproperty + def pid(self): + """Returns process PID if has been launched already.""" + + @abc.abstractmethod + def launch(self, executable, args): + """Launches new process with given executable and args.""" + + @abc.abstractmethod + def terminate(self): + """Terminates previously launched process..""" + + +class _LocalProcess(_BaseProcess): + + def __init__(self, trace_on): + self._proc = None + self._trace_on = trace_on + self._delayafterterminate = 0.1 + + @property + def pid(self): + return self._proc.pid + + def launch(self, executable, args): + self._proc = Popen( + [executable] + args, + stdout=open( + os.devnull) if not self._trace_on else None, + stdin=PIPE) + + def terminate(self): + if self._proc.poll() is None: + # Terminate _proc like it does the pexpect + signals_to_try = [ + sig for sig in [ + 'SIGHUP', + 'SIGCONT', + 'SIGINT'] if sig in dir(signal)] + for sig in signals_to_try: + try: + self._proc.send_signal(getattr(signal, sig)) + time.sleep(self._delayafterterminate) + if self._proc.poll() is not None: + return + except ValueError: + pass # Windows says SIGINT is not a valid signal to send + self._proc.terminate() + time.sleep(self._delayafterterminate) + if self._proc.poll() is not None: + return + self._proc.kill() + time.sleep(self._delayafterterminate) + + def poll(self): + return self._proc.poll() + + +class _RemoteProcess(_BaseProcess): + + def __init__(self, install_remote): + self._pid = None + self._install_remote = install_remote + + @property + def pid(self): + return self._pid + + def launch(self, executable, args): + if self._install_remote: + src_path = executable + dst_path = lldbutil.join_remote_paths( + lldb.remote_platform.GetWorkingDirectory(), os.path.basename(executable)) + + dst_file_spec = lldb.SBFileSpec(dst_path, False) + err = lldb.remote_platform.Install( + lldb.SBFileSpec(src_path, True), dst_file_spec) + if err.Fail(): + raise Exception( + "remote_platform.Install('%s', '%s') failed: %s" % + (src_path, dst_path, err)) + else: + dst_path = executable + dst_file_spec = lldb.SBFileSpec(executable, False) + + launch_info = lldb.SBLaunchInfo(args) + launch_info.SetExecutableFile(dst_file_spec, True) + launch_info.SetWorkingDirectory( + lldb.remote_platform.GetWorkingDirectory()) + + # Redirect stdout and stderr to /dev/null + launch_info.AddSuppressFileAction(1, False, True) + launch_info.AddSuppressFileAction(2, False, True) + + err = lldb.remote_platform.Launch(launch_info) + if err.Fail(): + raise Exception( + "remote_platform.Launch('%s', '%s') failed: %s" % + (dst_path, args, err)) + self._pid = launch_info.GetProcessID() + + def terminate(self): + lldb.remote_platform.Kill(self._pid) + +# From 2.7's subprocess.check_output() convenience function. +# Return a tuple (stdoutdata, stderrdata). + + +def system(commands, **kwargs): + r"""Run an os 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) + + # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo'] + commandList = [' '.join(x) for x in commands] + output = "" + error = "" + for shellCommand in commandList: + if 'stdout' in kwargs: + raise ValueError( + 'stdout argument not allowed, it will be overridden.') + if 'shell' in kwargs and kwargs['shell'] == False: + raise ValueError('shell=False not allowed') + process = Popen( + shellCommand, + stdout=PIPE, + stderr=PIPE, + shell=True, + **kwargs) + pid = process.pid + this_output, this_error = process.communicate() + retcode = process.poll() + + if retcode: + cmd = kwargs.get("args") + if cmd is None: + cmd = shellCommand + cpe = CalledProcessError(retcode, cmd) + # Ensure caller can access the stdout/stderr. + cpe.lldb_extensions = { + "stdout_content": this_output, + "stderr_content": this_error, + "command": shellCommand + } + raise cpe + output = output + this_output.decode("utf-8") + error = error + this_error.decode("utf-8") + return (output, error) + + +def getsource_if_available(obj): + """ + Return the text of the source code for an object if available. Otherwise, + a print representation is returned. + """ + import inspect + try: + return inspect.getsource(obj) + except: + return repr(obj) + + +def builder_module(): + if sys.platform.startswith("freebsd"): + return __import__("builder_freebsd") + if sys.platform.startswith("openbsd"): + return __import__("builder_openbsd") + if sys.platform.startswith("netbsd"): + return __import__("builder_netbsd") + if sys.platform.startswith("linux"): + # sys.platform with Python-3.x returns 'linux', but with + # Python-2.x it returns 'linux2'. + return __import__("builder_linux") + return __import__("builder_" + sys.platform) + + +class Base(unittest2.TestCase): + """ + Abstract base for performing lldb (see TestBase) or other generic tests (see + BenchBase for one example). lldbtest.Base works with the test driver to + accomplish things. + + """ + + # The concrete subclass should override this attribute. + mydir = None + + # Keep track of the old current working directory. + oldcwd = None + + @staticmethod + def compute_mydir(test_file): + '''Subclasses should call this function to correctly calculate the + required "mydir" attribute as follows: + + mydir = TestBase.compute_mydir(__file__) + ''' + # /abs/path/to/packages/group/subdir/mytest.py -> group/subdir + rel_prefix = test_file[len(os.environ["LLDB_TEST"]) + 1:] + return os.path.dirname(rel_prefix) + + def TraceOn(self): + """Returns True if we are in trace mode (tracing detailed test execution).""" + return traceAlways + + @classmethod + def setUpClass(cls): + """ + Python unittest framework class setup fixture. + Do current directory manipulation. + """ + # Fail fast if 'mydir' attribute is not overridden. + if not cls.mydir or len(cls.mydir) == 0: + raise Exception("Subclasses must override the 'mydir' attribute.") + + # Save old working directory. + cls.oldcwd = os.getcwd() + + # Change current working directory if ${LLDB_TEST} is defined. + # See also dotest.py which sets up ${LLDB_TEST}. + if ("LLDB_TEST" in os.environ): + full_dir = os.path.join(os.environ["LLDB_TEST"], + cls.mydir) + if traceAlways: + print("Change dir to:", full_dir, file=sys.stderr) + os.chdir(full_dir) + + # Set platform context. + cls.platformContext = lldbplatformutil.createPlatformContext() + + @classmethod + def tearDownClass(cls): + """ + Python unittest framework class teardown fixture. + Do class-wide cleanup. + """ + + if doCleanup: + # First, let's do the platform-specific cleanup. + module = builder_module() + module.cleanup() + + # Subclass might have specific cleanup function defined. + if getattr(cls, "classCleanup", None): + if traceAlways: + print( + "Call class-specific cleanup function for class:", + cls, + file=sys.stderr) + 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: + print("Restore dir to:", cls.oldcwd, file=sys.stderr) + os.chdir(cls.oldcwd) + + def enableLogChannelsForCurrentTest(self): + if len(lldbtest_config.channels) == 0: + return + + # if debug channels are specified in lldbtest_config.channels, + # create a new set of log files for every test + log_basename = self.getLogBasenameForCurrentTest() + + # confirm that the file is writeable + host_log_path = "{}-host.log".format(log_basename) + open(host_log_path, 'w').close() + + log_enable = "log enable -Tpn -f {} ".format(host_log_path) + for channel_with_categories in lldbtest_config.channels: + channel_then_categories = channel_with_categories.split(' ', 1) + channel = channel_then_categories[0] + if len(channel_then_categories) > 1: + categories = channel_then_categories[1] + else: + categories = "default" + + if channel == "gdb-remote" and lldb.remote_platform is None: + # communicate gdb-remote categories to debugserver + os.environ["LLDB_DEBUGSERVER_LOG_FLAGS"] = categories + + self.ci.HandleCommand( + log_enable + channel_with_categories, self.res) + if not self.res.Succeeded(): + raise Exception( + 'log enable failed (check LLDB_LOG_OPTION env variable)') + + # Communicate log path name to debugserver & lldb-server + # For remote debugging, these variables need to be set when starting the platform + # instance. + if lldb.remote_platform is None: + server_log_path = "{}-server.log".format(log_basename) + open(server_log_path, 'w').close() + os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path + + # Communicate channels to lldb-server + os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join( + lldbtest_config.channels) + + self.addTearDownHook(self.disableLogChannelsForCurrentTest) + + def disableLogChannelsForCurrentTest(self): + # close all log files that we opened + for channel_and_categories in lldbtest_config.channels: + # channel format - <channel-name> [<category0> [<category1> ...]] + channel = channel_and_categories.split(' ', 1)[0] + self.ci.HandleCommand("log disable " + channel, self.res) + if not self.res.Succeeded(): + raise Exception( + 'log disable failed (check LLDB_LOG_OPTION env variable)') + + # Retrieve the server log (if any) from the remote system. It is assumed the server log + # is writing to the "server.log" file in the current test directory. This can be + # achieved by setting LLDB_DEBUGSERVER_LOG_FILE="server.log" when starting remote + # platform. If the remote logging is not enabled, then just let the Get() command silently + # fail. + if lldb.remote_platform: + lldb.remote_platform.Get( + lldb.SBFileSpec("server.log"), lldb.SBFileSpec( + self.getLogBasenameForCurrentTest() + "-server.log")) + + def setPlatformWorkingDir(self): + if not lldb.remote_platform or not configuration.lldb_platform_working_dir: + return + + components = self.mydir.split(os.path.sep) + [str(self.test_number), self.getBuildDirBasename()] + remote_test_dir = configuration.lldb_platform_working_dir + for c in components: + remote_test_dir = lldbutil.join_remote_paths(remote_test_dir, c) + error = lldb.remote_platform.MakeDirectory( + remote_test_dir, 448) # 448 = 0o700 + if error.Fail(): + raise Exception("making remote directory '%s': %s" % ( + remote_test_dir, error)) + + lldb.remote_platform.SetWorkingDirectory(remote_test_dir) + + # This function removes all files from the current working directory while leaving + # the directories in place. The cleaup is required to reduce the disk space required + # by the test suite while leaving the directories untouched is neccessary because + # sub-directories might belong to an other test + def clean_working_directory(): + # TODO: Make it working on Windows when we need it for remote debugging support + # TODO: Replace the heuristic to remove the files with a logic what collects the + # list of files we have to remove during test runs. + shell_cmd = lldb.SBPlatformShellCommand( + "rm %s/*" % remote_test_dir) + lldb.remote_platform.Run(shell_cmd) + self.addTearDownHook(clean_working_directory) + + def getSourceDir(self): + """Return the full path to the current test.""" + return os.path.join(os.environ["LLDB_TEST"], self.mydir) + + def getBuildDirBasename(self): + return self.__class__.__module__ + "." + self.testMethodName + + def getBuildDir(self): + """Return the full path to the current test.""" + return os.path.join(os.environ["LLDB_BUILD"], self.mydir, + self.getBuildDirBasename()) + + + def makeBuildDir(self): + """Create the test-specific working directory, deleting any previous + contents.""" + # See also dotest.py which sets up ${LLDB_BUILD}. + bdir = self.getBuildDir() + if os.path.isdir(bdir): + shutil.rmtree(bdir) + lldbutil.mkdir_p(bdir) + + def getBuildArtifact(self, name="a.out"): + """Return absolute path to an artifact in the test's build directory.""" + return os.path.join(self.getBuildDir(), name) + + def getSourcePath(self, name): + """Return absolute path to a file in the test's source directory.""" + return os.path.join(self.getSourceDir(), name) + + @classmethod + def setUpCommands(cls): + commands = [ + # Disable Spotlight lookup. The testsuite creates + # different binaries with the same UUID, because they only + # differ in the debug info, which is not being hashed. + "settings set symbols.enable-external-lookup false", + + # Testsuite runs in parallel and the host can have also other load. + "settings set plugin.process.gdb-remote.packet-timeout 60", + + 'settings set symbols.clang-modules-cache-path "{}"'.format( + configuration.lldb_module_cache_dir), + "settings set use-color false", + ] + # Make sure that a sanitizer LLDB's environment doesn't get passed on. + if cls.platformContext and cls.platformContext.shlib_environment_var in os.environ: + commands.append('settings set target.env-vars {}='.format( + cls.platformContext.shlib_environment_var)) + + # Set environment variables for the inferior. + if lldbtest_config.inferior_env: + commands.append('settings set target.env-vars {}'.format( + lldbtest_config.inferior_env)) + return commands + + def setUp(self): + """Fixture for unittest test case setup. + + It works with the test driver to conditionally skip tests and does other + initializations.""" + #import traceback + # traceback.print_stack() + + if "LIBCXX_PATH" in os.environ: + self.libcxxPath = os.environ["LIBCXX_PATH"] + else: + self.libcxxPath = None + + if "LLDBVSCODE_EXEC" in os.environ: + self.lldbVSCodeExec = os.environ["LLDBVSCODE_EXEC"] + else: + self.lldbVSCodeExec = None + + self.lldbOption = " ".join( + "-o '" + s + "'" for s in self.setUpCommands()) + + # If we spawn an lldb process for test (via pexpect), do not load the + # init file unless told otherwise. + if os.environ.get("NO_LLDBINIT") != "NO": + self.lldbOption += " --no-lldbinit" + + # Assign the test method name to self.testMethodName. + # + # For an example of the use of this attribute, look at test/types dir. + # There are a bunch of test cases under test/types and we don't want the + # module cacheing subsystem to be confused with executable name "a.out" + # used for all the test cases. + self.testMethodName = self._testMethodName + + # This is for the case of directly spawning 'lldb'/'gdb' and interacting + # with it using pexpect. + self.child = None + self.child_prompt = "(lldb) " + # If the child is interacting with the embedded script interpreter, + # there are two exits required during tear down, first to quit the + # embedded script interpreter and second to quit the lldb command + # interpreter. + self.child_in_script_interpreter = False + + # These are for customized teardown cleanup. + self.dict = None + self.doTearDownCleanup = False + # And in rare cases where there are multiple teardown cleanups. + self.dicts = [] + self.doTearDownCleanups = False + + # List of spawned subproces.Popen objects + self.subprocesses = [] + + # List of forked process PIDs + self.forkedProcessPids = [] + + # Create a string buffer to record the session info, to be dumped into a + # test case specific file if test failure is encountered. + self.log_basename = self.getLogBasenameForCurrentTest() + + session_file = "{}.log".format(self.log_basename) + # Python 3 doesn't support unbuffered I/O in text mode. Open buffered. + self.session = encoded_file.open(session_file, "utf-8", mode="w") + + # Optimistically set __errored__, __failed__, __expected__ to False + # initially. If the test errored/failed, the session info + # (self.session) is then dumped into a session specific file for + # diagnosis. + self.__cleanup_errored__ = False + self.__errored__ = False + self.__failed__ = False + self.__expected__ = False + # We are also interested in unexpected success. + self.__unexpected__ = False + # And skipped tests. + self.__skipped__ = False + + # See addTearDownHook(self, hook) which allows the client to add a hook + # function to be run during tearDown() time. + self.hooks = [] + + # See HideStdout(self). + self.sys_stdout_hidden = False + + if self.platformContext: + # set environment variable names for finding shared libraries + self.dylibPath = self.platformContext.shlib_environment_var + + # Create the debugger instance if necessary. + try: + self.dbg = lldb.DBG + except AttributeError: + self.dbg = lldb.SBDebugger.Create() + + if not self.dbg: + raise Exception('Invalid debugger instance') + + # Retrieve the associated command interpreter instance. + self.ci = self.dbg.GetCommandInterpreter() + if not self.ci: + raise Exception('Could not get the command interpreter') + + # And the result object. + self.res = lldb.SBCommandReturnObject() + + self.setPlatformWorkingDir() + self.enableLogChannelsForCurrentTest() + + lib_dir = os.environ["LLDB_LIB_DIR"] + self.dsym = None + self.framework_dir = None + self.darwinWithFramework = self.platformIsDarwin() + if sys.platform.startswith("darwin"): + # Handle the framework environment variable if it is set + if hasattr(lldbtest_config, 'lldb_framework_path'): + framework_path = lldbtest_config.lldb_framework_path + # Framework dir should be the directory containing the framework + self.framework_dir = framework_path[:framework_path.rfind('LLDB.framework')] + # If a framework dir was not specified assume the Xcode build + # directory layout where the framework is in LLDB_LIB_DIR. + else: + self.framework_dir = lib_dir + self.dsym = os.path.join(self.framework_dir, 'LLDB.framework', 'LLDB') + # If the framework binary doesn't exist, assume we didn't actually + # build a framework, and fallback to standard *nix behavior by + # setting framework_dir and dsym to None. + if not os.path.exists(self.dsym): + self.framework_dir = None + self.dsym = None + self.darwinWithFramework = False + self.makeBuildDir() + + def setAsync(self, value): + """ Sets async mode to True/False and ensures it is reset after the testcase completes.""" + old_async = self.dbg.GetAsync() + self.dbg.SetAsync(value) + self.addTearDownHook(lambda: self.dbg.SetAsync(old_async)) + + def cleanupSubprocesses(self): + # Ensure any subprocesses are cleaned up + for p in self.subprocesses: + p.terminate() + del p + del self.subprocesses[:] + # Ensure any forked processes are cleaned up + for pid in self.forkedProcessPids: + if os.path.exists("/proc/" + str(pid)): + os.kill(pid, signal.SIGTERM) + + def spawnSubprocess(self, executable, args=[], install_remote=True): + """ Creates a subprocess.Popen object with the specified executable and arguments, + saves it in self.subprocesses, and returns the object. + NOTE: if using this function, ensure you also call: + + self.addTearDownHook(self.cleanupSubprocesses) + + otherwise the test suite will leak processes. + """ + proc = _RemoteProcess( + install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn()) + proc.launch(executable, args) + self.subprocesses.append(proc) + return proc + + def forkSubprocess(self, executable, args=[]): + """ Fork a subprocess with its own group ID. + NOTE: if using this function, ensure you also call: + + self.addTearDownHook(self.cleanupSubprocesses) + + otherwise the test suite will leak processes. + """ + child_pid = os.fork() + if child_pid == 0: + # If more I/O support is required, this can be beefed up. + fd = os.open(os.devnull, os.O_RDWR) + os.dup2(fd, 1) + os.dup2(fd, 2) + # This call causes the child to have its of group ID + os.setpgid(0, 0) + os.execvp(executable, [executable] + args) + # Give the child time to get through the execvp() call + time.sleep(0.1) + self.forkedProcessPids.append(child_pid) + return child_pid + + def HideStdout(self): + """Hide output to stdout from the user. + + During test execution, there might be cases where we don't want to show the + standard output to the user. For example, + + self.runCmd(r'''sc print("\n\n\tHello!\n")''') + + tests whether command abbreviation for 'script' works or not. There is no + need to show the 'Hello' output to the user as long as the 'script' command + succeeds and we are not in TraceOn() mode (see the '-t' option). + + In this case, the test method calls self.HideStdout(self) to redirect the + sys.stdout to a null device, and restores the sys.stdout upon teardown. + + Note that you should only call this method at most once during a test case + execution. Any subsequent call has no effect at all.""" + if self.sys_stdout_hidden: + return + + self.sys_stdout_hidden = True + old_stdout = sys.stdout + sys.stdout = open(os.devnull, 'w') + + def restore_stdout(): + sys.stdout = old_stdout + self.addTearDownHook(restore_stdout) + + # ======================================================================= + # Methods for customized teardown cleanups as well as execution of hooks. + # ======================================================================= + + def setTearDownCleanup(self, dictionary=None): + """Register a cleanup action at tearDown() time with a dictinary""" + self.dict = dictionary + self.doTearDownCleanup = True + + def addTearDownCleanup(self, dictionary): + """Add a cleanup action at tearDown() time with a dictinary""" + self.dicts.append(dictionary) + self.doTearDownCleanups = True + + def addTearDownHook(self, hook): + """ + Add a function to be run during tearDown() time. + + Hooks are executed in a first come first serve manner. + """ + if six.callable(hook): + with recording(self, traceAlways) as sbuf: + print( + "Adding tearDown hook:", + getsource_if_available(hook), + file=sbuf) + self.hooks.append(hook) + + return self + + def deletePexpectChild(self): + # This is for the case of directly spawning 'lldb' and interacting with it + # using pexpect. + if self.child and self.child.isalive(): + import pexpect + with recording(self, traceAlways) as sbuf: + print("tearing down the child process....", file=sbuf) + try: + if self.child_in_script_interpreter: + self.child.sendline('quit()') + self.child.expect_exact(self.child_prompt) + self.child.sendline( + 'settings set interpreter.prompt-on-quit false') + self.child.sendline('quit') + self.child.expect(pexpect.EOF) + except (ValueError, pexpect.ExceptionPexpect): + # child is already terminated + pass + except OSError as exception: + import errno + if exception.errno != errno.EIO: + # unexpected error + raise + # child is already terminated + finally: + # Give it one final blow to make sure the child is terminated. + self.child.close() + + def tearDown(self): + """Fixture for unittest test case teardown.""" + #import traceback + # traceback.print_stack() + + self.deletePexpectChild() + + # Check and run any hook functions. + for hook in reversed(self.hooks): + with recording(self, traceAlways) as sbuf: + print( + "Executing tearDown hook:", + getsource_if_available(hook), + file=sbuf) + if funcutils.requires_self(hook): + hook(self) + else: + hook() # try the plain call and hope it works + + del self.hooks + + # Perform registered teardown cleanup. + if doCleanup and self.doTearDownCleanup: + self.cleanup(dictionary=self.dict) + + # In rare cases where there are multiple teardown cleanups added. + if doCleanup and self.doTearDownCleanups: + if self.dicts: + for dict in reversed(self.dicts): + self.cleanup(dictionary=dict) + + # ========================================================= + # Various callbacks to allow introspection of test progress + # ========================================================= + + def markError(self): + """Callback invoked when an error (unexpected exception) errored.""" + self.__errored__ = True + with recording(self, False) as sbuf: + # False because there's no need to write "ERROR" to the stderr twice. + # Once by the Python unittest framework, and a second time by us. + print("ERROR", file=sbuf) + + def markCleanupError(self): + """Callback invoked when an error occurs while a test is cleaning up.""" + self.__cleanup_errored__ = True + with recording(self, False) as sbuf: + # False because there's no need to write "CLEANUP_ERROR" to the stderr twice. + # Once by the Python unittest framework, and a second time by us. + print("CLEANUP_ERROR", file=sbuf) + + def markFailure(self): + """Callback invoked when a failure (test assertion failure) occurred.""" + self.__failed__ = True + with recording(self, False) as sbuf: + # 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("FAIL", file=sbuf) + + def markExpectedFailure(self, err, bugnumber): + """Callback invoked when an expected failure/error occurred.""" + self.__expected__ = True + with recording(self, False) as sbuf: + # False because there's no need to write "expected failure" to the + # stderr twice. + # Once by the Python unittest framework, and a second time by us. + if bugnumber is None: + print("expected failure", file=sbuf) + else: + print( + "expected failure (problem id:" + str(bugnumber) + ")", + file=sbuf) + + def markSkippedTest(self): + """Callback invoked when a test is skipped.""" + self.__skipped__ = True + with recording(self, False) as sbuf: + # False because there's no need to write "skipped test" to the + # stderr twice. + # Once by the Python unittest framework, and a second time by us. + print("skipped test", file=sbuf) + + def markUnexpectedSuccess(self, bugnumber): + """Callback invoked when an unexpected success occurred.""" + self.__unexpected__ = True + with recording(self, False) as sbuf: + # False because there's no need to write "unexpected success" to the + # stderr twice. + # Once by the Python unittest framework, and a second time by us. + if bugnumber is None: + print("unexpected success", file=sbuf) + else: + print( + "unexpected success (problem id:" + str(bugnumber) + ")", + file=sbuf) + + def getRerunArgs(self): + return " -f %s.%s" % (self.__class__.__name__, self._testMethodName) + + def getLogBasenameForCurrentTest(self, prefix=None): + """ + returns a partial path that can be used as the beginning of the name of multiple + log files pertaining to this test + + <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method> + """ + dname = os.path.join(os.environ["LLDB_TEST"], + os.environ["LLDB_SESSION_DIRNAME"]) + if not os.path.isdir(dname): + os.mkdir(dname) + + components = [] + if prefix is not None: + components.append(prefix) + for c in configuration.session_file_format: + if c == 'f': + components.append(self.__class__.__module__) + elif c == 'n': + components.append(self.__class__.__name__) + elif c == 'c': + compiler = self.getCompiler() + + if compiler[1] == ':': + compiler = compiler[2:] + if os.path.altsep is not None: + compiler = compiler.replace(os.path.altsep, os.path.sep) + path_components = [x for x in compiler.split(os.path.sep) if x != ""] + + # Add at most 4 path components to avoid generating very long + # filenames + components.extend(path_components[-4:]) + elif c == 'a': + components.append(self.getArchitecture()) + elif c == 'm': + components.append(self.testMethodName) + fname = "-".join(components) + + return os.path.join(dname, fname) + + def dumpSessionInfo(self): + """ + Dump the debugger interactions leading to a test error/failure. This + allows for more convenient postmortem analysis. + + See also LLDBTestResult (dotest.py) which is a singlton class derived + from TextTestResult and overwrites addError, addFailure, and + addExpectedFailure methods to allow us to to mark the test instance as + such. + """ + + # We are here because self.tearDown() detected that this test instance + # either errored or failed. The lldb.test_result singleton contains + # two lists (erros and failures) which get populated by the unittest + # framework. Look over there for stack trace information. + # + # The lists contain 2-tuples of TestCase instances and strings holding + # formatted tracebacks. + # + # See http://docs.python.org/library/unittest.html#unittest.TestResult. + + # output tracebacks into session + pairs = [] + if self.__errored__: + pairs = configuration.test_result.errors + prefix = 'Error' + elif self.__cleanup_errored__: + pairs = configuration.test_result.cleanup_errors + prefix = 'CleanupError' + elif self.__failed__: + pairs = configuration.test_result.failures + prefix = 'Failure' + elif self.__expected__: + pairs = configuration.test_result.expectedFailures + prefix = 'ExpectedFailure' + elif self.__skipped__: + prefix = 'SkippedTest' + elif self.__unexpected__: + prefix = 'UnexpectedSuccess' + else: + prefix = 'Success' + + if not self.__unexpected__ and not self.__skipped__: + for test, traceback in pairs: + if test is self: + print(traceback, file=self.session) + + import datetime + print( + "Session info generated @", + datetime.datetime.now().ctime(), + file=self.session) + self.session.close() + del self.session + + # process the log files + log_files_for_this_test = glob.glob(self.log_basename + "*") + + if prefix != 'Success' or lldbtest_config.log_success: + # keep all log files, rename them to include prefix + dst_log_basename = self.getLogBasenameForCurrentTest(prefix) + for src in log_files_for_this_test: + if os.path.isfile(src): + dst = src.replace(self.log_basename, dst_log_basename) + if os.name == "nt" and os.path.isfile(dst): + # On Windows, renaming a -> b will throw an exception if + # b exists. On non-Windows platforms it silently + # replaces the destination. Ultimately this means that + # atomic renames are not guaranteed to be possible on + # Windows, but we need this to work anyway, so just + # remove the destination first if it already exists. + remove_file(dst) + + lldbutil.mkdir_p(os.path.dirname(dst)) + os.rename(src, dst) + else: + # success! (and we don't want log files) delete log files + for log_file in log_files_for_this_test: + remove_file(log_file) + + # ==================================================== + # Config. methods supported through a plugin interface + # (enables reading of the current test configuration) + # ==================================================== + + def isMIPS(self): + """Returns true if the architecture is MIPS.""" + arch = self.getArchitecture() + if re.match("mips", arch): + return True + return False + + def isPPC64le(self): + """Returns true if the architecture is PPC64LE.""" + arch = self.getArchitecture() + if re.match("powerpc64le", arch): + return True + return False + + def getArchitecture(self): + """Returns the architecture in effect the test suite is running with.""" + module = builder_module() + arch = module.getArchitecture() + if arch == 'amd64': + arch = 'x86_64' + return arch + + def getLldbArchitecture(self): + """Returns the architecture of the lldb binary.""" + if not hasattr(self, 'lldbArchitecture'): + + # spawn local process + command = [ + lldbtest_config.lldbExec, + "-o", + "file " + lldbtest_config.lldbExec, + "-o", + "quit" + ] + + output = check_output(command) + str = output.decode("utf-8") + + for line in str.splitlines(): + m = re.search( + "Current executable set to '.*' \\((.*)\\)\\.", line) + if m: + self.lldbArchitecture = m.group(1) + break + + return self.lldbArchitecture + + def getCompiler(self): + """Returns the compiler in effect the test suite is running with.""" + module = builder_module() + return module.getCompiler() + + def getCompilerBinary(self): + """Returns the compiler binary the test suite is running with.""" + return self.getCompiler().split()[0] + + def getCompilerVersion(self): + """ Returns a string that represents the compiler version. + Supports: llvm, clang. + """ + version = 'unknown' + + compiler = self.getCompilerBinary() + version_output = system([[compiler, "-v"]])[1] + for line in version_output.split(os.linesep): + m = re.search('version ([0-9\.]+)', line) + if m: + version = m.group(1) + return version + + def getDwarfVersion(self): + """ Returns the dwarf version generated by clang or '0'. """ + if configuration.dwarf_version: + return str(configuration.dwarf_version) + if 'clang' in self.getCompiler(): + try: + driver_output = check_output( + [self.getCompiler()] + '-g -c -x c - -o - -###'.split(), + stderr=STDOUT) + driver_output = driver_output.decode("utf-8") + for line in driver_output.split(os.linesep): + m = re.search('dwarf-version=([0-9])', line) + if m: + return m.group(1) + except: pass + return '0' + + def platformIsDarwin(self): + """Returns true if the OS triple for the selected platform is any valid apple OS""" + return lldbplatformutil.platformIsDarwin() + + def hasDarwinFramework(self): + return self.darwinWithFramework + + def getPlatform(self): + """Returns the target platform the test suite is running on.""" + return lldbplatformutil.getPlatform() + + def isIntelCompiler(self): + """ Returns true if using an Intel (ICC) compiler, false otherwise. """ + return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]]) + + def expectedCompilerVersion(self, compiler_version): + """Returns True iff compiler_version[1] matches the current compiler version. + Use compiler_version[0] to specify the operator used to determine if a match has occurred. + Any operator other than the following defaults to an equality test: + '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not' + """ + if (compiler_version is None): + return True + operator = str(compiler_version[0]) + version = compiler_version[1] + + if (version is None): + return True + if (operator == '>'): + return LooseVersion(self.getCompilerVersion()) > LooseVersion(version) + if (operator == '>=' or operator == '=>'): + return LooseVersion(self.getCompilerVersion()) >= LooseVersion(version) + if (operator == '<'): + return LooseVersion(self.getCompilerVersion()) < LooseVersion(version) + if (operator == '<=' or operator == '=<'): + return LooseVersion(self.getCompilerVersion()) <= LooseVersion(version) + if (operator == '!=' or operator == '!' or operator == 'not'): + return str(version) not in str(self.getCompilerVersion()) + return str(version) in str(self.getCompilerVersion()) + + def expectedCompiler(self, compilers): + """Returns True iff any element of compilers is a sub-string of the current compiler.""" + if (compilers is None): + return True + + for compiler in compilers: + if compiler in self.getCompiler(): + return True + + return False + + def expectedArch(self, archs): + """Returns True iff any element of archs is a sub-string of the current architecture.""" + if (archs is None): + return True + + for arch in archs: + if arch in self.getArchitecture(): + return True + + return False + + def getRunOptions(self): + """Command line option for -A and -C to run this test again, called from + self.dumpSessionInfo().""" + arch = self.getArchitecture() + comp = self.getCompiler() + option_str = "" + if arch: + option_str = "-A " + arch + if comp: + option_str += " -C " + comp + return option_str + + def getDebugInfo(self): + method = getattr(self, self.testMethodName) + return getattr(method, "debug_info", None) + + # ================================================== + # Build methods supported through a plugin interface + # ================================================== + + def getstdlibFlag(self): + """ Returns the proper -stdlib flag, or empty if not required.""" + if self.platformIsDarwin() or self.getPlatform() == "freebsd" or self.getPlatform() == "openbsd": + stdlibflag = "-stdlib=libc++" + else: # this includes NetBSD + stdlibflag = "" + return stdlibflag + + def getstdFlag(self): + """ Returns the proper stdflag. """ + if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion(): + stdflag = "-std=c++0x" + else: + stdflag = "-std=c++11" + return stdflag + + def buildDriver(self, sources, exe_name): + """ Platform-specific way to build a program that links with LLDB (via the liblldb.so + or LLDB.framework). + """ + stdflag = self.getstdFlag() + stdlibflag = self.getstdlibFlag() + + lib_dir = os.environ["LLDB_LIB_DIR"] + if self.hasDarwinFramework(): + d = {'CXX_SOURCES': sources, + 'EXE': exe_name, + 'CFLAGS_EXTRAS': "%s %s" % (stdflag, stdlibflag), + 'FRAMEWORK_INCLUDES': "-F%s" % self.framework_dir, + 'LD_EXTRAS': "%s -Wl,-rpath,%s" % (self.dsym, self.framework_dir), + } + elif sys.platform.startswith('win'): + d = { + 'CXX_SOURCES': sources, + 'EXE': exe_name, + 'CFLAGS_EXTRAS': "%s %s -I%s" % (stdflag, + stdlibflag, + os.path.join( + os.environ["LLDB_SRC"], + "include")), + 'LD_EXTRAS': "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]} + else: + d = { + 'CXX_SOURCES': sources, + 'EXE': exe_name, + 'CFLAGS_EXTRAS': "%s %s -I%s" % (stdflag, + stdlibflag, + os.path.join( + os.environ["LLDB_SRC"], + "include")), + 'LD_EXTRAS': "-L%s/../lib -llldb -Wl,-rpath,%s/../lib" % (lib_dir, lib_dir)} + if self.TraceOn(): + print( + "Building LLDB Driver (%s) from sources %s" % + (exe_name, sources)) + + self.buildDefault(dictionary=d) + + def buildLibrary(self, sources, lib_name): + """Platform specific way to build a default library. """ + + stdflag = self.getstdFlag() + + lib_dir = os.environ["LLDB_LIB_DIR"] + if self.hasDarwinFramework(): + d = {'DYLIB_CXX_SOURCES': sources, + 'DYLIB_NAME': lib_name, + 'CFLAGS_EXTRAS': "%s -stdlib=libc++" % stdflag, + 'FRAMEWORK_INCLUDES': "-F%s" % self.framework_dir, + 'LD_EXTRAS': "%s -Wl,-rpath,%s -dynamiclib" % (self.dsym, self.framework_dir), + } + elif self.getPlatform() == 'windows': + d = { + 'DYLIB_CXX_SOURCES': sources, + 'DYLIB_NAME': lib_name, + 'CFLAGS_EXTRAS': "%s -I%s " % (stdflag, + os.path.join( + os.environ["LLDB_SRC"], + "include")), + 'LD_EXTRAS': "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]} + else: + d = { + 'DYLIB_CXX_SOURCES': sources, + 'DYLIB_NAME': lib_name, + 'CFLAGS_EXTRAS': "%s -I%s -fPIC" % (stdflag, + os.path.join( + os.environ["LLDB_SRC"], + "include")), + 'LD_EXTRAS': "-shared -L%s/../lib -llldb -Wl,-rpath,%s/../lib" % (lib_dir, lib_dir)} + if self.TraceOn(): + print( + "Building LLDB Library (%s) from sources %s" % + (lib_name, sources)) + + self.buildDefault(dictionary=d) + + def buildProgram(self, sources, exe_name): + """ Platform specific way to build an executable from C/C++ sources. """ + d = {'CXX_SOURCES': sources, + 'EXE': exe_name} + self.buildDefault(dictionary=d) + + def buildDefault( + self, + architecture=None, + compiler=None, + dictionary=None): + """Platform specific way to build the default binaries.""" + testdir = self.mydir + testname = self.getBuildDirBasename() + if self.getDebugInfo(): + raise Exception("buildDefault tests must set NO_DEBUG_INFO_TESTCASE") + module = builder_module() + dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) + if not module.buildDefault(self, architecture, compiler, + dictionary, testdir, testname): + 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.""" + testdir = self.mydir + testname = self.getBuildDirBasename() + if self.getDebugInfo() != "dsym": + raise Exception("NO_DEBUG_INFO_TESTCASE must build with buildDefault") + + module = builder_module() + dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) + if not module.buildDsym(self, architecture, compiler, + dictionary, testdir, testname): + 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.""" + testdir = self.mydir + testname = self.getBuildDirBasename() + if self.getDebugInfo() != "dwarf": + raise Exception("NO_DEBUG_INFO_TESTCASE must build with buildDefault") + + module = builder_module() + dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) + if not module.buildDwarf(self, architecture, compiler, + dictionary, testdir, testname): + raise Exception("Don't know how to build binary with dwarf") + + def buildDwo( + self, + architecture=None, + compiler=None, + dictionary=None): + """Platform specific way to build binaries with dwarf maps.""" + testdir = self.mydir + testname = self.getBuildDirBasename() + if self.getDebugInfo() != "dwo": + raise Exception("NO_DEBUG_INFO_TESTCASE must build with buildDefault") + + module = builder_module() + dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) + if not module.buildDwo(self, architecture, compiler, + dictionary, testdir, testname): + raise Exception("Don't know how to build binary with dwo") + + def buildGModules( + self, + architecture=None, + compiler=None, + dictionary=None): + """Platform specific way to build binaries with gmodules info.""" + testdir = self.mydir + testname = self.getBuildDirBasename() + if self.getDebugInfo() != "gmodules": + raise Exception("NO_DEBUG_INFO_TESTCASE must build with buildDefault") + + module = builder_module() + dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) + if not module.buildGModules(self, architecture, compiler, + dictionary, testdir, testname): + raise Exception("Don't know how to build binary with gmodules") + + def signBinary(self, binary_path): + if sys.platform.startswith("darwin"): + codesign_cmd = "codesign --force --sign \"%s\" %s" % ( + lldbtest_config.codesign_identity, binary_path) + call(codesign_cmd, shell=True) + + def findBuiltClang(self): + """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler).""" + paths_to_try = [ + "llvm-build/Release+Asserts/x86_64/bin/clang", + "llvm-build/Debug+Asserts/x86_64/bin/clang", + "llvm-build/Release/x86_64/bin/clang", + "llvm-build/Debug/x86_64/bin/clang", + ] + lldb_root_path = os.path.join( + os.path.dirname(__file__), "..", "..", "..", "..") + for p in paths_to_try: + path = os.path.join(lldb_root_path, p) + if os.path.exists(path): + return path + + # Tries to find clang at the same folder as the lldb + lldb_dir = os.path.dirname(lldbtest_config.lldbExec) + path = distutils.spawn.find_executable("clang", lldb_dir) + if path is not None: + return path + + return os.environ["CC"] + + def findYaml2obj(self): + """ + Get the path to the yaml2obj executable, which can be used to create + test object files from easy to write yaml instructions. + + Throws an Exception if the executable cannot be found. + """ + # Tries to find yaml2obj at the same folder as clang + clang_dir = os.path.dirname(self.findBuiltClang()) + path = distutils.spawn.find_executable("yaml2obj", clang_dir) + if path is not None: + return path + raise Exception("yaml2obj executable not found") + + + def yaml2obj(self, yaml_path, obj_path): + """ + Create an object file at the given path from a yaml file. + + Throws subprocess.CalledProcessError if the object could not be created. + """ + yaml2obj = self.findYaml2obj() + command = [yaml2obj, "-o=%s" % obj_path, yaml_path] + system([command]) + + def getBuildFlags( + self, + use_cpp11=True, + use_libcxx=False, + use_libstdcxx=False): + """ Returns a dictionary (which can be provided to build* functions above) which + contains OS-specific build flags. + """ + cflags = "" + ldflags = "" + + # On Mac OS X, unless specifically requested to use libstdc++, use + # libc++ + if not use_libstdcxx and self.platformIsDarwin(): + use_libcxx = True + + if use_libcxx and self.libcxxPath: + cflags += "-stdlib=libc++ " + if self.libcxxPath: + libcxxInclude = os.path.join(self.libcxxPath, "include") + libcxxLib = os.path.join(self.libcxxPath, "lib") + if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib): + cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % ( + libcxxInclude, libcxxLib, libcxxLib) + + if use_cpp11: + cflags += "-std=" + if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion(): + cflags += "c++0x" + else: + cflags += "c++11" + if self.platformIsDarwin() or self.getPlatform() == "freebsd": + cflags += " -stdlib=libc++" + elif self.getPlatform() == "openbsd": + cflags += " -stdlib=libc++" + elif self.getPlatform() == "netbsd": + # NetBSD defaults to libc++ + pass + elif "clang" in self.getCompiler(): + cflags += " -stdlib=libstdc++" + + return {'CFLAGS_EXTRAS': cflags, + 'LD_EXTRAS': ldflags, + } + + def cleanup(self, dictionary=None): + """Platform specific way to do cleanup after build.""" + module = builder_module() + if not module.cleanup(self, dictionary): + raise Exception( + "Don't know how to do cleanup with dictionary: " + + dictionary) + + def getLLDBLibraryEnvVal(self): + """ Returns the path that the OS-specific library search environment variable + (self.dylibPath) should be set to in order for a program to find the LLDB + library. If an environment variable named self.dylibPath is already set, + the new path is appended to it and returned. + """ + existing_library_path = os.environ[ + self.dylibPath] if self.dylibPath in os.environ else None + lib_dir = os.environ["LLDB_LIB_DIR"] + if existing_library_path: + return "%s:%s" % (existing_library_path, lib_dir) + elif sys.platform.startswith("darwin"): + return os.path.join(lib_dir, 'LLDB.framework') + else: + return lib_dir + + def getLibcPlusPlusLibs(self): + if self.getPlatform() in ('freebsd', 'linux', 'netbsd', 'openbsd'): + return ['libc++.so.1'] + else: + return ['libc++.1.dylib', 'libc++abi.'] + +# Metaclass for TestBase to change the list of test metods when a new TestCase is loaded. +# We change the test methods to create a new test method for each test for each debug info we are +# testing. The name of the new test method will be '<original-name>_<debug-info>' and with adding +# the new test method we remove the old method at the same time. This functionality can be +# supressed by at test case level setting the class attribute NO_DEBUG_INFO_TESTCASE or at test +# level by using the decorator @no_debug_info_test. + + +class LLDBTestCaseFactory(type): + + def __new__(cls, name, bases, attrs): + original_testcase = super( + LLDBTestCaseFactory, cls).__new__( + cls, name, bases, attrs) + if original_testcase.NO_DEBUG_INFO_TESTCASE: + return original_testcase + + newattrs = {} + for attrname, attrvalue in attrs.items(): + if attrname.startswith("test") and not getattr( + attrvalue, "__no_debug_info_test__", False): + + # If any debug info categories were explicitly tagged, assume that list to be + # authoritative. If none were specified, try with all debug + # info formats. + all_dbginfo_categories = set(test_categories.debug_info_categories) + categories = set( + getattr( + attrvalue, + "categories", + [])) & all_dbginfo_categories + if not categories: + categories = all_dbginfo_categories + + for cat in categories: + @decorators.add_test_categories([cat]) + @wraps(attrvalue) + def test_method(self, attrvalue=attrvalue): + return attrvalue(self) + + method_name = attrname + "_" + cat + test_method.__name__ = method_name + test_method.debug_info = cat + newattrs[method_name] = test_method + + else: + newattrs[attrname] = attrvalue + return super( + LLDBTestCaseFactory, + cls).__new__( + cls, + name, + bases, + newattrs) + +# Setup the metaclass for this class to change the list of the test +# methods when a new class is loaded + + +@add_metaclass(LLDBTestCaseFactory) +class TestBase(Base): + """ + This abstract base class is meant to be subclassed. It provides default + implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(), + among other things. + + Important things for test class writers: + + - Overwrite the mydir class attribute, otherwise your test class won't + run. It specifies the relative directory to the top level 'test' so + the test harness can change to the correct working directory before + running your test. + + - The setUp method sets up things to facilitate subsequent interactions + with the debugger as part of the test. These include: + - populate the test method name + - create/get a debugger set with synchronous mode (self.dbg) + - get the command interpreter from with the debugger (self.ci) + - create a result object for use with the command interpreter + (self.res) + - plus other stuffs + + - The tearDown method tries to perform some necessary cleanup on behalf + of the test to return the debugger to a good state for the next test. + These include: + - execute any tearDown hooks registered by the test method with + TestBase.addTearDownHook(); examples can be found in + settings/TestSettings.py + - kill the inferior process associated with each target, if any, + and, then delete the target from the debugger's target list + - perform build cleanup before running the next test method in the + same test class; examples of registering for this service can be + found in types/TestIntegerTypes.py with the call: + - self.setTearDownCleanup(dictionary=d) + + - Similarly setUpClass and tearDownClass perform classwise setup and + teardown fixtures. The tearDownClass method invokes a default build + cleanup for the entire test class; also, subclasses can implement the + classmethod classCleanup(cls) to perform special class cleanup action. + + - The instance methods runCmd and expect are used heavily by existing + test cases to send a command to the command interpreter and to perform + string/pattern matching on the output of such command execution. The + expect method also provides a mode to peform string/pattern matching + without running a command. + + - The build methods buildDefault, buildDsym, and buildDwarf are used to + build the binaries used during a particular test scenario. A plugin + should be provided for the sys.platform running the test suite. The + Mac OS X implementation is located in plugins/darwin.py. + """ + + # Subclasses can set this to true (if they don't depend on debug info) to avoid running the + # test multiple times with various debug info types. + NO_DEBUG_INFO_TESTCASE = False + + # Maximum allowed attempts when launching the inferior process. + # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable. + maxLaunchCount = 1 + + # Time to wait before the next launching attempt in second(s). + # Can be overridden by the LLDB_TIME_WAIT_NEXT_LAUNCH environment variable. + timeWaitNextLaunch = 1.0 + + def generateSource(self, source): + template = source + '.template' + temp = os.path.join(self.getSourceDir(), template) + with open(temp, 'r') as f: + content = f.read() + + public_api_dir = os.path.join( + os.environ["LLDB_SRC"], "include", "lldb", "API") + + # Look under the include/lldb/API directory and add #include statements + # for all the SB API headers. + public_headers = os.listdir(public_api_dir) + # For different platforms, the include statement can vary. + if self.hasDarwinFramework(): + include_stmt = "'#include <%s>' % os.path.join('LLDB', header)" + else: + include_stmt = "'#include <%s>' % os.path.join('" + public_api_dir + "', header)" + list = [eval(include_stmt) for header in public_headers if ( + header.startswith("SB") and header.endswith(".h"))] + includes = '\n'.join(list) + new_content = content.replace('%include_SB_APIs%', includes) + src = os.path.join(self.getBuildDir(), source) + with open(src, 'w') as f: + f.write(new_content) + + self.addTearDownHook(lambda: os.remove(src)) + + def setUp(self): + #import traceback + # traceback.print_stack() + + # Works with the test driver to conditionally skip tests via + # decorators. + Base.setUp(self) + + for s in self.setUpCommands(): + self.runCmd(s) + + if "LLDB_MAX_LAUNCH_COUNT" in os.environ: + self.maxLaunchCount = int(os.environ["LLDB_MAX_LAUNCH_COUNT"]) + + if "LLDB_TIME_WAIT_NEXT_LAUNCH" in os.environ: + self.timeWaitNextLaunch = float( + os.environ["LLDB_TIME_WAIT_NEXT_LAUNCH"]) + + # We want our debugger to be synchronous. + self.dbg.SetAsync(False) + + # Retrieve the associated command interpreter instance. + self.ci = self.dbg.GetCommandInterpreter() + if not self.ci: + raise Exception('Could not get the command interpreter') + + # And the result object. + self.res = lldb.SBCommandReturnObject() + + def registerSharedLibrariesWithTarget(self, target, shlibs): + '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing + + Any modules in the target that have their remote install file specification set will + get uploaded to the remote host. This function registers the local copies of the + shared libraries with the target and sets their remote install locations so they will + be uploaded when the target is run. + ''' + if not shlibs or not self.platformContext: + return None + + shlib_environment_var = self.platformContext.shlib_environment_var + shlib_prefix = self.platformContext.shlib_prefix + shlib_extension = '.' + self.platformContext.shlib_extension + + working_dir = self.get_process_working_directory() + environment = ['%s=%s' % (shlib_environment_var, working_dir)] + # Add any shared libraries to our target if remote so they get + # uploaded into the working directory on the remote side + for name in shlibs: + # The path can be a full path to a shared library, or a make file name like "Foo" for + # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a + # basename like "libFoo.so". So figure out which one it is and resolve the local copy + # of the shared library accordingly + if os.path.isfile(name): + local_shlib_path = name # name is the full path to the local shared library + else: + # Check relative names + local_shlib_path = os.path.join( + self.getBuildDir(), shlib_prefix + name + shlib_extension) + if not os.path.exists(local_shlib_path): + local_shlib_path = os.path.join( + self.getBuildDir(), name + shlib_extension) + if not os.path.exists(local_shlib_path): + local_shlib_path = os.path.join(self.getBuildDir(), name) + + # Make sure we found the local shared library in the above code + self.assertTrue(os.path.exists(local_shlib_path)) + + # Add the shared library to our target + shlib_module = target.AddModule(local_shlib_path, None, None, None) + if lldb.remote_platform: + # We must set the remote install location if we want the shared library + # to get uploaded to the remote target + remote_shlib_path = lldbutil.append_to_process_working_directory(self, + os.path.basename(local_shlib_path)) + shlib_module.SetRemoteInstallFileSpec( + lldb.SBFileSpec(remote_shlib_path, False)) + + return environment + + def registerSanitizerLibrariesWithTarget(self, target): + runtimes = [] + for m in target.module_iter(): + libspec = m.GetFileSpec() + if "clang_rt" in libspec.GetFilename(): + runtimes.append(os.path.join(libspec.GetDirectory(), + libspec.GetFilename())) + return self.registerSharedLibrariesWithTarget(target, runtimes) + + # utility methods that tests can use to access the current objects + def target(self): + if not self.dbg: + raise Exception('Invalid debugger instance') + return self.dbg.GetSelectedTarget() + + def process(self): + if not self.dbg: + raise Exception('Invalid debugger instance') + return self.dbg.GetSelectedTarget().GetProcess() + + def thread(self): + if not self.dbg: + raise Exception('Invalid debugger instance') + return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread() + + def frame(self): + if not self.dbg: + raise Exception('Invalid debugger instance') + return self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() + + def get_process_working_directory(self): + '''Get the working directory that should be used when launching processes for local or remote processes.''' + if lldb.remote_platform: + # Remote tests set the platform working directory up in + # TestBase.setUp() + return lldb.remote_platform.GetWorkingDirectory() + else: + # local tests change directory into each test subdirectory + return self.getBuildDir() + + def tearDown(self): + #import traceback + # traceback.print_stack() + + # Ensure all the references to SB objects have gone away so that we can + # be sure that all test-specific resources have been freed before we + # attempt to delete the targets. + gc.collect() + + # Delete the target(s) from the debugger as a general cleanup step. + # This includes terminating the process for each target, if any. + # We'd like to reuse the debugger for our next test without incurring + # the initialization overhead. + targets = [] + for target in self.dbg: + if target: + targets.append(target) + process = target.GetProcess() + if process: + rc = self.invoke(process, "Kill") + self.assertTrue(rc.Success(), PROCESS_KILLED) + for target in targets: + self.dbg.DeleteTarget(target) + + # Do this last, to make sure it's in reverse order from how we setup. + Base.tearDown(self) + + # This must be the last statement, otherwise teardown hooks or other + # lines might depend on this still being active. + del self.dbg + + def switch_to_thread_with_stop_reason(self, stop_reason): + """ + Run the 'thread list' command, and select the thread with stop reason as + 'stop_reason'. If no such thread exists, no select action is done. + """ + from .lldbutil import stop_reason_to_str + self.runCmd('thread list') + output = self.res.GetOutput() + thread_line_pattern = re.compile( + "^[ *] thread #([0-9]+):.*stop reason = %s" % + stop_reason_to_str(stop_reason)) + for line in output.splitlines(): + matched = thread_line_pattern.match(line) + if matched: + self.runCmd('thread select %s' % matched.group(1)) + + def runCmd(self, cmd, msg=None, check=True, trace=False, inHistory=False): + """ + Ask the command interpreter to handle the command and then check its + return status. + """ + # Fail fast if 'cmd' is not meaningful. + if not cmd or len(cmd) == 0: + raise Exception("Bad 'cmd' parameter encountered") + + trace = (True if traceAlways else trace) + + if cmd.startswith("target create "): + cmd = cmd.replace("target create ", "file ") + + running = (cmd.startswith("run") or cmd.startswith("process launch")) + + for i in range(self.maxLaunchCount if running else 1): + self.ci.HandleCommand(cmd, self.res, inHistory) + + with recording(self, trace) as sbuf: + print("runCmd:", cmd, file=sbuf) + if not check: + print("check of return status not required", file=sbuf) + if self.res.Succeeded(): + print("output:", self.res.GetOutput(), file=sbuf) + else: + print("runCmd failed!", file=sbuf) + print(self.res.GetError(), file=sbuf) + + if self.res.Succeeded(): + break + elif running: + # For process launch, wait some time before possible next try. + time.sleep(self.timeWaitNextLaunch) + with recording(self, trace) as sbuf: + print("Command '" + cmd + "' failed!", file=sbuf) + + if check: + output = "" + if self.res.GetOutput(): + output += "\nCommand output:\n" + self.res.GetOutput() + if self.res.GetError(): + output += "\nError output:\n" + self.res.GetError() + if msg: + msg += output + if cmd: + cmd += output + self.assertTrue(self.res.Succeeded(), + msg if (msg) else CMD_MSG(cmd)) + + def match( + self, + str, + patterns, + msg=None, + trace=False, + error=False, + matching=True, + exe=True): + """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern + + Otherwise, all the arguments have the same meanings as for the expect function""" + + trace = (True if traceAlways else trace) + + if exe: + # First run the command. If we are expecting error, set check=False. + # Pass the assert message along since it provides more semantic + # info. + self.runCmd( + str, + msg=msg, + trace=( + True if trace else False), + check=not error) + + # Then compare the output against expected strings. + output = self.res.GetError() if error else self.res.GetOutput() + + # If error is True, the API client expects the command to fail! + if error: + self.assertFalse(self.res.Succeeded(), + "Command '" + str + "' is expected to fail!") + else: + # No execution required, just compare str against the golden input. + output = str + with recording(self, trace) as sbuf: + print("looking at:", output, file=sbuf) + + # The heading says either "Expecting" or "Not expecting". + heading = "Expecting" if matching else "Not expecting" + + for pattern in patterns: + # Match Objects always have a boolean value of True. + match_object = re.search(pattern, output) + matched = bool(match_object) + with recording(self, trace) as sbuf: + print("%s pattern: %s" % (heading, pattern), file=sbuf) + print("Matched" if matched else "Not matched", file=sbuf) + if matched: + break + + self.assertTrue(matched if matching else not matched, + msg if msg else EXP_MSG(str, output, exe)) + + return match_object + + def check_completion_with_desc(self, str_input, match_desc_pairs): + interp = self.dbg.GetCommandInterpreter() + match_strings = lldb.SBStringList() + description_strings = lldb.SBStringList() + num_matches = interp.HandleCompletionWithDescriptions(str_input, len(str_input), 0, -1, match_strings, description_strings) + self.assertEqual(len(description_strings), len(match_strings)) + + missing_pairs = [] + for pair in match_desc_pairs: + found_pair = False + for i in range(num_matches + 1): + match_candidate = match_strings.GetStringAtIndex(i) + description_candidate = description_strings.GetStringAtIndex(i) + if match_candidate == pair[0] and description_candidate == pair[1]: + found_pair = True + break + if not found_pair: + missing_pairs.append(pair) + + if len(missing_pairs): + error_msg = "Missing pairs:\n" + for pair in missing_pairs: + error_msg += " [" + pair[0] + ":" + pair[1] + "]\n" + error_msg += "Got the following " + str(num_matches) + " completions back:\n" + for i in range(num_matches + 1): + match_candidate = match_strings.GetStringAtIndex(i) + description_candidate = description_strings.GetStringAtIndex(i) + error_msg += "[" + match_candidate + ":" + description_candidate + "]\n" + self.assertEqual(0, len(missing_pairs), error_msg) + + def complete_exactly(self, str_input, patterns): + self.complete_from_to(str_input, patterns, True) + + def complete_from_to(self, str_input, patterns, turn_off_re_match=False): + """Test that the completion mechanism completes str_input to patterns, + where patterns could be a pattern-string or a list of pattern-strings""" + # Patterns should not be None in order to proceed. + self.assertFalse(patterns is None) + # And should be either a string or list of strings. Check for list type + # below, if not, make a list out of the singleton string. If patterns + # is not a string or not a list of strings, there'll be runtime errors + # later on. + if not isinstance(patterns, list): + patterns = [patterns] + + interp = self.dbg.GetCommandInterpreter() + match_strings = lldb.SBStringList() + num_matches = interp.HandleCompletion(str_input, len(str_input), 0, -1, match_strings) + common_match = match_strings.GetStringAtIndex(0) + if num_matches == 0: + compare_string = str_input + else: + if common_match != None and len(common_match) > 0: + compare_string = str_input + common_match + else: + compare_string = "" + for idx in range(1, num_matches+1): + compare_string += match_strings.GetStringAtIndex(idx) + "\n" + + for p in patterns: + if turn_off_re_match: + self.expect( + compare_string, msg=COMPLETION_MSG( + str_input, p, match_strings), exe=False, substrs=[p]) + else: + self.expect( + compare_string, msg=COMPLETION_MSG( + str_input, p, match_strings), exe=False, patterns=[p]) + + def completions_match(self, command, completions): + """Checks that the completions for the given command are equal to the + given list of completions""" + interp = self.dbg.GetCommandInterpreter() + match_strings = lldb.SBStringList() + interp.HandleCompletion(command, len(command), 0, -1, match_strings) + # match_strings is a 1-indexed list, so we have to slice... + self.assertItemsEqual(completions, list(match_strings)[1:], + "List of returned completion is wrong") + + def filecheck( + self, + command, + check_file, + filecheck_options = '', + expect_cmd_failure = False): + # Run the command. + self.runCmd( + command, + check=(not expect_cmd_failure), + msg="FileCheck'ing result of `{0}`".format(command)) + + self.assertTrue((not expect_cmd_failure) == self.res.Succeeded()) + + # Get the error text if there was an error, and the regular text if not. + output = self.res.GetOutput() if self.res.Succeeded() \ + else self.res.GetError() + + # Assemble the absolute path to the check file. As a convenience for + # LLDB inline tests, assume that the check file is a relative path to + # a file within the inline test directory. + if check_file.endswith('.pyc'): + check_file = check_file[:-1] + check_file_abs = os.path.abspath(check_file) + + # Run FileCheck. + filecheck_bin = configuration.get_filecheck_path() + if not filecheck_bin: + self.assertTrue(False, "No valid FileCheck executable specified") + filecheck_args = [filecheck_bin, check_file_abs] + if filecheck_options: + filecheck_args.append(filecheck_options) + subproc = Popen(filecheck_args, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines = True) + cmd_stdout, cmd_stderr = subproc.communicate(input=output) + cmd_status = subproc.returncode + + filecheck_cmd = " ".join(filecheck_args) + filecheck_trace = """ +--- FileCheck trace (code={0}) --- +{1} + +FileCheck input: +{2} + +FileCheck output: +{3} +{4} +""".format(cmd_status, filecheck_cmd, output, cmd_stdout, cmd_stderr) + + trace = cmd_status != 0 or traceAlways + with recording(self, trace) as sbuf: + print(filecheck_trace, file=sbuf) + + self.assertTrue(cmd_status == 0) + + def expect( + self, + str, + msg=None, + patterns=None, + startstr=None, + endstr=None, + substrs=None, + trace=False, + error=False, + matching=True, + exe=True, + inHistory=False): + """ + Similar to runCmd; with additional expect style output matching ability. + + Ask the command interpreter to handle the command and then check its + return status. The 'msg' parameter specifies an informational assert + message. We expect the output from running the command to start with + 'startstr', matches the substrings contained in 'substrs', and regexp + matches the patterns contained in 'patterns'. + + If the keyword argument error is set to True, it signifies that the API + client is expecting the command to fail. In this case, the error stream + from running the command is retrieved and compared against the golden + input, instead. + + If the keyword argument matching is set to False, it signifies that the API + client is expecting the output of the command not to match the golden + input. + + Finally, the required argument 'str' represents the lldb command to be + sent to the command interpreter. In case the keyword argument 'exe' is + set to False, the 'str' is treated as a string to be matched/not-matched + against the golden input. + """ + trace = (True if traceAlways else trace) + + if exe: + # First run the command. If we are expecting error, set check=False. + # Pass the assert message along since it provides more semantic + # info. + self.runCmd( + str, + msg=msg, + trace=( + True if trace else False), + check=not error, + inHistory=inHistory) + + # Then compare the output against expected strings. + output = self.res.GetError() if error else self.res.GetOutput() + + # If error is True, the API client expects the command to fail! + if error: + self.assertFalse(self.res.Succeeded(), + "Command '" + str + "' is expected to fail!") + else: + # No execution required, just compare str against the golden input. + if isinstance(str, lldb.SBCommandReturnObject): + output = str.GetOutput() + else: + output = str + with recording(self, trace) as sbuf: + print("looking at:", output, file=sbuf) + + # The heading says either "Expecting" or "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: + with recording(self, trace) as sbuf: + print("%s start string: %s" % (heading, startstr), file=sbuf) + print("Matched" if matched else "Not matched", file=sbuf) + + # Look for endstr, if specified. + keepgoing = matched if matching else not matched + if endstr: + matched = output.endswith(endstr) + with recording(self, trace) as sbuf: + print("%s end string: %s" % (heading, endstr), file=sbuf) + print("Matched" if matched else "Not matched", file=sbuf) + + # Look for sub strings, if specified. + keepgoing = matched if matching else not matched + if substrs and keepgoing: + for substr in substrs: + matched = output.find(substr) != -1 + with recording(self, trace) as sbuf: + print("%s sub string: %s" % (heading, substr), file=sbuf) + print("Matched" if matched else "Not matched", file=sbuf) + keepgoing = matched if matching else not matched + if not keepgoing: + break + + # Search for regular expression patterns, if specified. + keepgoing = matched if matching else not matched + if patterns and keepgoing: + for pattern in patterns: + # Match Objects always have a boolean value of True. + matched = bool(re.search(pattern, output)) + with recording(self, trace) as sbuf: + print("%s pattern: %s" % (heading, pattern), file=sbuf) + print("Matched" if matched else "Not matched", file=sbuf) + keepgoing = matched if matching else not matched + if not keepgoing: + break + + self.assertTrue(matched if matching else not matched, + msg if msg else EXP_MSG(str, output, exe)) + + def expect_expr( + self, + expr, + result_summary=None, + result_value=None, + result_type=None, + error_msg=None, + ): + """ + Evaluates the given expression and verifies the result. + :param expr: The expression as a string. + :param result_summary: The summary that the expression should have. None if the summary should not be checked. + :param result_value: The value that the expression should have. None if the value should not be checked. + :param result_type: The type that the expression result should have. None if the type should not be checked. + :param error_msg: The error message the expression should return. None if the error output should not be checked. + """ + self.assertTrue(expr.strip() == expr, "Expression contains trailing/leading whitespace: '" + expr + "'") + + frame = self.frame() + eval_result = frame.EvaluateExpression(expr) + + if error_msg: + self.assertFalse(eval_result.IsValid()) + self.assertEqual(error_msg, eval_result.GetError().GetCString()) + return + + if not eval_result.GetError().Success(): + self.assertTrue(eval_result.GetError().Success(), + "Unexpected failure with msg: " + eval_result.GetError().GetCString()) + + if result_type: + self.assertEqual(result_type, eval_result.GetTypeName()) + + if result_value: + self.assertEqual(result_value, eval_result.GetValue()) + + if result_summary: + self.assertEqual(result_summary, eval_result.GetSummary()) + + def invoke(self, obj, name, trace=False): + """Use reflection to call a method dynamically with no argument.""" + trace = (True if traceAlways else trace) + + method = getattr(obj, name) + import inspect + self.assertTrue(inspect.ismethod(method), + name + "is a method name of object: " + str(obj)) + result = method() + with recording(self, trace) as sbuf: + print(str(method) + ":", result, file=sbuf) + return result + + def build( + self, + architecture=None, + compiler=None, + dictionary=None): + """Platform specific way to build the default binaries.""" + module = builder_module() + + dictionary = lldbplatformutil.finalize_build_dictionary(dictionary) + if self.getDebugInfo() is None: + return self.buildDefault(architecture, compiler, dictionary) + elif self.getDebugInfo() == "dsym": + return self.buildDsym(architecture, compiler, dictionary) + elif self.getDebugInfo() == "dwarf": + return self.buildDwarf(architecture, compiler, dictionary) + elif self.getDebugInfo() == "dwo": + return self.buildDwo(architecture, compiler, dictionary) + elif self.getDebugInfo() == "gmodules": + return self.buildGModules(architecture, compiler, dictionary) + else: + self.fail("Can't build for debug info: %s" % self.getDebugInfo()) + + def run_platform_command(self, cmd): + platform = self.dbg.GetSelectedPlatform() + shell_command = lldb.SBPlatformShellCommand(cmd) + err = platform.Run(shell_command) + return (err, shell_command.GetStatus(), shell_command.GetOutput()) + + # ================================================= + # Misc. helper methods for debugging test execution + # ================================================= + + def DebugSBValue(self, val): + """Debug print a SBValue object, if traceAlways is True.""" + from .lldbutil import value_type_to_str + + if not traceAlways: + return + + err = sys.stderr + err.write(val.GetName() + ":\n") + err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n') + err.write('\t' + "ByteSize -> " + + str(val.GetByteSize()) + '\n') + err.write('\t' + "NumChildren -> " + + str(val.GetNumChildren()) + '\n') + err.write('\t' + "Value -> " + str(val.GetValue()) + '\n') + err.write('\t' + "ValueAsUnsigned -> " + + str(val.GetValueAsUnsigned()) + '\n') + err.write( + '\t' + + "ValueType -> " + + value_type_to_str( + val.GetValueType()) + + '\n') + err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n') + err.write('\t' + "IsPointerType -> " + + str(val.TypeIsPointerType()) + '\n') + err.write('\t' + "Location -> " + val.GetLocation() + '\n') + + def DebugSBType(self, type): + """Debug print a SBType object, if traceAlways is True.""" + if not traceAlways: + return + + err = sys.stderr + err.write(type.GetName() + ":\n") + err.write('\t' + "ByteSize -> " + + str(type.GetByteSize()) + '\n') + err.write('\t' + "IsPointerType -> " + + str(type.IsPointerType()) + '\n') + err.write('\t' + "IsReferenceType -> " + + str(type.IsReferenceType()) + '\n') + + def DebugPExpect(self, child): + """Debug the spwaned pexpect object.""" + if not traceAlways: + return + + print(child) + + @classmethod + def RemoveTempFile(cls, file): + if os.path.exists(file): + remove_file(file) + +# On Windows, the first attempt to delete a recently-touched file can fail +# because of a race with antimalware scanners. This function will detect a +# failure and retry. + + +def remove_file(file, num_retries=1, sleep_duration=0.5): + for i in range(num_retries + 1): + try: + os.remove(file) + return True + except: + time.sleep(sleep_duration) + continue + return False diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbtest_config.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbtest_config.py new file mode 100644 index 00000000000..d31588ab15c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbtest_config.py @@ -0,0 +1,25 @@ +""" + Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. + See https://llvm.org/LICENSE.txt for license information. + SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +Configuration options for lldbtest.py set by dotest.py during initialization +""" + +# array of strings +# each string has the name of an lldb channel followed by +# zero or more categories in that channel +# ex. "gdb-remote packets" +channels = [] + +# leave logs/traces even for successful test runs +log_success = False + +# Indicate whether we're testing with an out-of-tree debugserver +out_of_tree_debugserver = False + +# path to the lldb command line executable tool +lldbExec = None + +# Environment variables for the inferior +inferior_env = None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbutil.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbutil.py new file mode 100644 index 00000000000..006362a4479 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lldbutil.py @@ -0,0 +1,1422 @@ +""" +This LLDB module contains miscellaneous utilities. +Some of the test suite takes advantage of the utility functions defined here. +They can also be useful for general purpose lldb scripting. +""" + +from __future__ import print_function +from __future__ import absolute_import + +# System modules +import errno +import os +import re +import sys + +# Third-party modules +from six import StringIO as SixStringIO +import six + +# LLDB modules +import lldb +from . import lldbtest_config + + +# =================================================== +# Utilities for locating/checking executable programs +# =================================================== + +def is_exe(fpath): + """Returns True if fpath is an executable.""" + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + +def which(program): + """Returns the full path to a program; None otherwise.""" + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ["PATH"].split(os.pathsep): + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + return None + +def mkdir_p(path): + try: + os.makedirs(path) + except OSError as e: + if e.errno != errno.EEXIST: + raise + if not os.path.isdir(path): + raise OSError(errno.ENOTDIR, "%s is not a directory"%path) +# =================================================== +# Disassembly for an SBFunction or an SBSymbol object +# =================================================== + + +def disassemble(target, function_or_symbol): + """Disassemble the function or symbol given a target. + + It returns the disassembly content in a string object. + """ + buf = SixStringIO() + insts = function_or_symbol.GetInstructions(target) + for i in insts: + print(i, file=buf) + return buf.getvalue() + +# ========================================================== +# Integer (byte size 1, 2, 4, and 8) to bytearray conversion +# ========================================================== + + +def int_to_bytearray(val, bytesize): + """Utility function to convert an integer into a bytearray. + + It returns the bytearray in the little endian format. It is easy to get the + big endian format, just do ba.reverse() on the returned object. + """ + import struct + + if bytesize == 1: + return bytearray([val]) + + # Little endian followed by a format character. + template = "<%c" + if bytesize == 2: + fmt = template % 'h' + elif bytesize == 4: + fmt = template % 'i' + elif bytesize == 4: + fmt = template % 'q' + else: + return None + + packed = struct.pack(fmt, val) + return bytearray(packed) + + +def bytearray_to_int(bytes, bytesize): + """Utility function to convert a bytearray into an integer. + + It interprets the bytearray in the little endian format. For a big endian + bytearray, just do ba.reverse() on the object before passing it in. + """ + import struct + + if bytesize == 1: + return bytes[0] + + # Little endian followed by a format character. + template = "<%c" + if bytesize == 2: + fmt = template % 'h' + elif bytesize == 4: + fmt = template % 'i' + elif bytesize == 4: + fmt = template % 'q' + else: + return None + + unpacked = struct.unpack_from(fmt, bytes) + return unpacked[0] + + +# ============================================================== +# Get the description of an lldb object or None if not available +# ============================================================== +def get_description(obj, option=None): + """Calls lldb_obj.GetDescription() and returns a string, or None. + + For SBTarget, SBBreakpointLocation, and SBWatchpoint lldb objects, an extra + option can be passed in to describe the detailed level of description + desired: + o lldb.eDescriptionLevelBrief + o lldb.eDescriptionLevelFull + o lldb.eDescriptionLevelVerbose + """ + method = getattr(obj, 'GetDescription') + if not method: + return None + tuple = (lldb.SBTarget, lldb.SBBreakpointLocation, lldb.SBWatchpoint) + if isinstance(obj, tuple): + if option is None: + option = lldb.eDescriptionLevelBrief + + stream = lldb.SBStream() + if option is None: + success = method(stream) + else: + success = method(stream, option) + if not success: + return None + return stream.GetData() + + +# ================================================= +# Convert some enum value to its string counterpart +# ================================================= + +def state_type_to_str(enum): + """Returns the stateType string given an enum.""" + if enum == lldb.eStateInvalid: + return "invalid" + elif enum == lldb.eStateUnloaded: + return "unloaded" + elif enum == lldb.eStateConnected: + return "connected" + elif enum == lldb.eStateAttaching: + return "attaching" + elif enum == lldb.eStateLaunching: + return "launching" + elif enum == lldb.eStateStopped: + return "stopped" + elif enum == lldb.eStateRunning: + return "running" + elif enum == lldb.eStateStepping: + return "stepping" + elif enum == lldb.eStateCrashed: + return "crashed" + elif enum == lldb.eStateDetached: + return "detached" + elif enum == lldb.eStateExited: + return "exited" + elif enum == lldb.eStateSuspended: + return "suspended" + else: + raise Exception("Unknown StateType enum") + + +def stop_reason_to_str(enum): + """Returns the stopReason string given an enum.""" + if enum == lldb.eStopReasonInvalid: + return "invalid" + elif enum == lldb.eStopReasonNone: + return "none" + elif enum == lldb.eStopReasonTrace: + return "trace" + elif enum == lldb.eStopReasonBreakpoint: + return "breakpoint" + elif enum == lldb.eStopReasonWatchpoint: + return "watchpoint" + elif enum == lldb.eStopReasonExec: + return "exec" + elif enum == lldb.eStopReasonSignal: + return "signal" + elif enum == lldb.eStopReasonException: + return "exception" + elif enum == lldb.eStopReasonPlanComplete: + return "plancomplete" + elif enum == lldb.eStopReasonThreadExiting: + return "threadexiting" + else: + raise Exception("Unknown StopReason enum") + + +def symbol_type_to_str(enum): + """Returns the symbolType string given an enum.""" + if enum == lldb.eSymbolTypeInvalid: + return "invalid" + elif enum == lldb.eSymbolTypeAbsolute: + return "absolute" + elif enum == lldb.eSymbolTypeCode: + return "code" + elif enum == lldb.eSymbolTypeData: + return "data" + elif enum == lldb.eSymbolTypeTrampoline: + return "trampoline" + elif enum == lldb.eSymbolTypeRuntime: + return "runtime" + elif enum == lldb.eSymbolTypeException: + return "exception" + elif enum == lldb.eSymbolTypeSourceFile: + return "sourcefile" + elif enum == lldb.eSymbolTypeHeaderFile: + return "headerfile" + elif enum == lldb.eSymbolTypeObjectFile: + return "objectfile" + elif enum == lldb.eSymbolTypeCommonBlock: + return "commonblock" + elif enum == lldb.eSymbolTypeBlock: + return "block" + elif enum == lldb.eSymbolTypeLocal: + return "local" + elif enum == lldb.eSymbolTypeParam: + return "param" + elif enum == lldb.eSymbolTypeVariable: + return "variable" + elif enum == lldb.eSymbolTypeVariableType: + return "variabletype" + elif enum == lldb.eSymbolTypeLineEntry: + return "lineentry" + elif enum == lldb.eSymbolTypeLineHeader: + return "lineheader" + elif enum == lldb.eSymbolTypeScopeBegin: + return "scopebegin" + elif enum == lldb.eSymbolTypeScopeEnd: + return "scopeend" + elif enum == lldb.eSymbolTypeAdditional: + return "additional" + elif enum == lldb.eSymbolTypeCompiler: + return "compiler" + elif enum == lldb.eSymbolTypeInstrumentation: + return "instrumentation" + elif enum == lldb.eSymbolTypeUndefined: + return "undefined" + + +def value_type_to_str(enum): + """Returns the valueType string given an enum.""" + if enum == lldb.eValueTypeInvalid: + return "invalid" + elif enum == lldb.eValueTypeVariableGlobal: + return "global_variable" + elif enum == lldb.eValueTypeVariableStatic: + return "static_variable" + elif enum == lldb.eValueTypeVariableArgument: + return "argument_variable" + elif enum == lldb.eValueTypeVariableLocal: + return "local_variable" + elif enum == lldb.eValueTypeRegister: + return "register" + elif enum == lldb.eValueTypeRegisterSet: + return "register_set" + elif enum == lldb.eValueTypeConstResult: + return "constant_result" + else: + raise Exception("Unknown ValueType enum") + + +# ================================================== +# Get stopped threads due to each stop reason. +# ================================================== + +def sort_stopped_threads(process, + breakpoint_threads=None, + crashed_threads=None, + watchpoint_threads=None, + signal_threads=None, + exiting_threads=None, + other_threads=None): + """ Fills array *_threads with threads stopped for the corresponding stop + reason. + """ + for lst in [breakpoint_threads, + watchpoint_threads, + signal_threads, + exiting_threads, + other_threads]: + if lst is not None: + lst[:] = [] + + for thread in process: + dispatched = False + for (reason, list) in [(lldb.eStopReasonBreakpoint, breakpoint_threads), + (lldb.eStopReasonException, crashed_threads), + (lldb.eStopReasonWatchpoint, watchpoint_threads), + (lldb.eStopReasonSignal, signal_threads), + (lldb.eStopReasonThreadExiting, exiting_threads), + (None, other_threads)]: + if not dispatched and list is not None: + if thread.GetStopReason() == reason or reason is None: + list.append(thread) + dispatched = True + +# ================================================== +# Utility functions for setting breakpoints +# ================================================== + +def run_break_set_by_script( + test, + class_name, + extra_options=None, + num_expected_locations=1): + """Set a scripted breakpoint. Check that it got the right number of locations.""" + test.assertTrue(class_name is not None, "Must pass in a class name.") + command = "breakpoint set -P " + class_name + if extra_options is not None: + command += " " + extra_options + + break_results = run_break_set_command(test, command) + check_breakpoint_result(test, break_results, num_locations=num_expected_locations) + return get_bpno_from_match(break_results) + +def run_break_set_by_file_and_line( + test, + file_name, + line_number, + extra_options=None, + num_expected_locations=1, + loc_exact=False, + module_name=None): + """Set a breakpoint by file and line, returning the breakpoint number. + + If extra_options is not None, then we append it to the breakpoint set command. + + If num_expected_locations is -1, we check that we got AT LEAST one location. If num_expected_locations is -2, we don't + check the actual number at all. Otherwise, we check that num_expected_locations equals the number of locations. + + If loc_exact is true, we check that there is one location, and that location must be at the input file and line number.""" + + if file_name is None: + command = 'breakpoint set -l %d' % (line_number) + else: + command = 'breakpoint set -f "%s" -l %d' % (file_name, line_number) + + if module_name: + command += " --shlib '%s'" % (module_name) + + if extra_options: + command += " " + extra_options + + break_results = run_break_set_command(test, command) + + if num_expected_locations == 1 and loc_exact: + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations, + file_name=file_name, + line_number=line_number, + module_name=module_name) + else: + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) + + return get_bpno_from_match(break_results) + + +def run_break_set_by_symbol( + test, + symbol, + extra_options=None, + num_expected_locations=-1, + sym_exact=False, + module_name=None): + """Set a breakpoint by symbol name. Common options are the same as run_break_set_by_file_and_line. + + If sym_exact is true, then the output symbol must match the input exactly, otherwise we do a substring match.""" + command = 'breakpoint set -n "%s"' % (symbol) + + if module_name: + command += " --shlib '%s'" % (module_name) + + if extra_options: + command += " " + extra_options + + break_results = run_break_set_command(test, command) + + if num_expected_locations == 1 and sym_exact: + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations, + symbol_name=symbol, + module_name=module_name) + else: + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) + + return get_bpno_from_match(break_results) + + +def run_break_set_by_selector( + test, + selector, + extra_options=None, + num_expected_locations=-1, + module_name=None): + """Set a breakpoint by selector. Common options are the same as run_break_set_by_file_and_line.""" + + command = 'breakpoint set -S "%s"' % (selector) + + if module_name: + command += ' --shlib "%s"' % (module_name) + + if extra_options: + command += " " + extra_options + + break_results = run_break_set_command(test, command) + + if num_expected_locations == 1: + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations, + symbol_name=selector, + symbol_match_exact=False, + module_name=module_name) + else: + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) + + return get_bpno_from_match(break_results) + + +def run_break_set_by_regexp( + test, + regexp, + extra_options=None, + num_expected_locations=-1): + """Set a breakpoint by regular expression match on symbol name. Common options are the same as run_break_set_by_file_and_line.""" + + command = 'breakpoint set -r "%s"' % (regexp) + if extra_options: + command += " " + extra_options + + break_results = run_break_set_command(test, command) + + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) + + return get_bpno_from_match(break_results) + + +def run_break_set_by_source_regexp( + test, + regexp, + extra_options=None, + num_expected_locations=-1): + """Set a breakpoint by source regular expression. Common options are the same as run_break_set_by_file_and_line.""" + command = 'breakpoint set -p "%s"' % (regexp) + if extra_options: + command += " " + extra_options + + break_results = run_break_set_command(test, command) + + check_breakpoint_result( + test, + break_results, + num_locations=num_expected_locations) + + return get_bpno_from_match(break_results) + + +def run_break_set_command(test, command): + """Run the command passed in - it must be some break set variant - and analyze the result. + Returns a dictionary of information gleaned from the command-line results. + Will assert if the breakpoint setting fails altogether. + + Dictionary will contain: + bpno - breakpoint of the newly created breakpoint, -1 on error. + num_locations - number of locations set for the breakpoint. + + If there is only one location, the dictionary MAY contain: + file - source file name + line_no - source line number + symbol - symbol name + inline_symbol - inlined symbol name + offset - offset from the original symbol + module - module + address - address at which the breakpoint was set.""" + + patterns = [ + r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>[0-9]+) locations\.$", + r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>no) locations \(pending\)\.", + r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>[+\-]{0,1}[^+]+)( \+ (?P<offset>[0-9]+)){0,1}( \[inlined\] (?P<inline_symbol>.*)){0,1} at (?P<file>[^:]+):(?P<line_no>[0-9]+)(?P<column>(:[0-9]+)?), address = (?P<address>0x[0-9a-fA-F]+)$", + r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>.*)( \+ (?P<offset>[0-9]+)){0,1}, address = (?P<address>0x[0-9a-fA-F]+)$"] + match_object = test.match(command, patterns) + break_results = match_object.groupdict() + + # We always insert the breakpoint number, setting it to -1 if we couldn't find it + # Also, make sure it gets stored as an integer. + if not 'bpno' in break_results: + break_results['bpno'] = -1 + else: + break_results['bpno'] = int(break_results['bpno']) + + # We always insert the number of locations + # If ONE location is set for the breakpoint, then the output doesn't mention locations, but it has to be 1... + # We also make sure it is an integer. + + if not 'num_locations' in break_results: + num_locations = 1 + else: + num_locations = break_results['num_locations'] + if num_locations == 'no': + num_locations = 0 + else: + num_locations = int(break_results['num_locations']) + + break_results['num_locations'] = num_locations + + if 'line_no' in break_results: + break_results['line_no'] = int(break_results['line_no']) + + return break_results + + +def get_bpno_from_match(break_results): + return int(break_results['bpno']) + + +def check_breakpoint_result( + test, + break_results, + file_name=None, + line_number=-1, + symbol_name=None, + symbol_match_exact=True, + module_name=None, + offset=-1, + num_locations=-1): + + out_num_locations = break_results['num_locations'] + + if num_locations == -1: + test.assertTrue(out_num_locations > 0, + "Expecting one or more locations, got none.") + elif num_locations != -2: + test.assertTrue( + num_locations == out_num_locations, + "Expecting %d locations, got %d." % + (num_locations, + out_num_locations)) + + if file_name: + out_file_name = "" + if 'file' in break_results: + out_file_name = break_results['file'] + test.assertTrue( + file_name.endswith(out_file_name), + "Breakpoint file name '%s' doesn't match resultant name '%s'." % + (file_name, + out_file_name)) + + if line_number != -1: + out_line_number = -1 + if 'line_no' in break_results: + out_line_number = break_results['line_no'] + + test.assertTrue( + line_number == out_line_number, + "Breakpoint line number %s doesn't match resultant line %s." % + (line_number, + out_line_number)) + + if symbol_name: + out_symbol_name = "" + # Look first for the inlined symbol name, otherwise use the symbol + # name: + if 'inline_symbol' in break_results and break_results['inline_symbol']: + out_symbol_name = break_results['inline_symbol'] + elif 'symbol' in break_results: + out_symbol_name = break_results['symbol'] + + if symbol_match_exact: + test.assertTrue( + symbol_name == out_symbol_name, + "Symbol name '%s' doesn't match resultant symbol '%s'." % + (symbol_name, + out_symbol_name)) + else: + test.assertTrue( + out_symbol_name.find(symbol_name) != - + 1, + "Symbol name '%s' isn't in resultant symbol '%s'." % + (symbol_name, + out_symbol_name)) + + if module_name: + out_module_name = None + if 'module' in break_results: + out_module_name = break_results['module'] + + test.assertTrue( + module_name.find(out_module_name) != - + 1, + "Symbol module name '%s' isn't in expected module name '%s'." % + (out_module_name, + module_name)) + +# ================================================== +# Utility functions related to Threads and Processes +# ================================================== + + +def get_stopped_threads(process, reason): + """Returns the thread(s) with the specified stop reason in a list. + + The list can be empty if no such thread exists. + """ + threads = [] + for t in process: + if t.GetStopReason() == reason: + threads.append(t) + return threads + + +def get_stopped_thread(process, reason): + """A convenience function which returns the first thread with the given stop + reason or None. + + Example usages: + + 1. Get the stopped thread due to a breakpoint condition + + ... + from lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonPlanComplete) + self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition") + ... + + 2. Get the thread stopped due to a breakpoint + + ... + from lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint") + ... + + """ + threads = get_stopped_threads(process, reason) + if len(threads) == 0: + return None + return threads[0] + + +def get_threads_stopped_at_breakpoint_id(process, bpid): + """ For a stopped process returns the thread stopped at the breakpoint passed in bkpt""" + stopped_threads = [] + threads = [] + + stopped_threads = get_stopped_threads(process, lldb.eStopReasonBreakpoint) + + if len(stopped_threads) == 0: + return threads + + for thread in stopped_threads: + # Make sure we've hit our breakpoint... + break_id = thread.GetStopReasonDataAtIndex(0) + if break_id == bpid: + threads.append(thread) + + return threads + + +def get_threads_stopped_at_breakpoint(process, bkpt): + return get_threads_stopped_at_breakpoint_id(process, bkpt.GetID()) + + +def get_one_thread_stopped_at_breakpoint_id( + process, bpid, require_exactly_one=True): + threads = get_threads_stopped_at_breakpoint_id(process, bpid) + if len(threads) == 0: + return None + if require_exactly_one and len(threads) != 1: + return None + + return threads[0] + + +def get_one_thread_stopped_at_breakpoint( + process, bkpt, require_exactly_one=True): + return get_one_thread_stopped_at_breakpoint_id( + process, bkpt.GetID(), require_exactly_one) + + +def is_thread_crashed(test, thread): + """In the test suite we dereference a null pointer to simulate a crash. The way this is + reported depends on the platform.""" + if test.platformIsDarwin(): + return thread.GetStopReason( + ) == lldb.eStopReasonException and "EXC_BAD_ACCESS" in thread.GetStopDescription(100) + elif test.getPlatform() == "linux": + return thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex( + 0) == thread.GetProcess().GetUnixSignals().GetSignalNumberFromName("SIGSEGV") + elif test.getPlatform() == "windows": + return "Exception 0xc0000005" in thread.GetStopDescription(200) + else: + return "invalid address" in thread.GetStopDescription(100) + + +def get_crashed_threads(test, process): + threads = [] + if process.GetState() != lldb.eStateStopped: + return threads + for thread in process: + if is_thread_crashed(test, thread): + threads.append(thread) + return threads + +# Helper functions for run_to_{source,name}_breakpoint: + +def run_to_breakpoint_make_target(test, exe_name = "a.out", in_cwd = True): + if in_cwd: + exe = test.getBuildArtifact(exe_name) + + # Create the target + target = test.dbg.CreateTarget(exe) + test.assertTrue(target, "Target: %s is not valid."%(exe_name)) + + # Set environment variables for the inferior. + if lldbtest_config.inferior_env: + test.runCmd('settings set target.env-vars {}'.format( + lldbtest_config.inferior_env)) + + return target + +def run_to_breakpoint_do_run(test, target, bkpt, launch_info = None, + only_one_thread = True, extra_images = None): + + # Launch the process, and do not stop at the entry point. + if not launch_info: + launch_info = target.GetLaunchInfo() + launch_info.SetWorkingDirectory(test.get_process_working_directory()) + + if extra_images and lldb.remote_platform: + environ = test.registerSharedLibrariesWithTarget(target, extra_images) + launch_info.SetEnvironmentEntries(environ, True) + + error = lldb.SBError() + process = target.Launch(launch_info, error) + + test.assertTrue(process, + "Could not create a valid process for %s: %s"%(target.GetExecutable().GetFilename(), + error.GetCString())) + test.assertFalse(error.Fail(), + "Process launch failed: %s" % (error.GetCString())) + + # Frame #0 should be at our breakpoint. + threads = get_threads_stopped_at_breakpoint( + process, bkpt) + + num_threads = len(threads) + if only_one_thread: + test.assertEqual(num_threads, 1, "Expected 1 thread to stop at breakpoint, %d did."%(num_threads)) + else: + test.assertGreater(num_threads, 0, "No threads stopped at breakpoint") + + thread = threads[0] + return (target, process, thread, bkpt) + +def run_to_name_breakpoint (test, bkpt_name, launch_info = None, + exe_name = "a.out", + bkpt_module = None, + in_cwd = True, + only_one_thread = True, + extra_images = None): + """Start up a target, using exe_name as the executable, and run it to + a breakpoint set by name on bkpt_name restricted to bkpt_module. + + If you want to pass in launch arguments or environment + variables, you can optionally pass in an SBLaunchInfo. If you + do that, remember to set the working directory as well. + + If your executable isn't called a.out, you can pass that in. + And if your executable isn't in the CWD, pass in the absolute + path to the executable in exe_name, and set in_cwd to False. + + If you need to restrict the breakpoint to a particular module, + pass the module name (a string not a FileSpec) in bkpt_module. If + nothing is passed in setting will be unrestricted. + + If the target isn't valid, the breakpoint isn't found, or hit, the + function will cause a testsuite failure. + + If successful it returns a tuple with the target process and + thread that hit the breakpoint, and the breakpoint that we set + for you. + + If only_one_thread is true, we require that there be only one + thread stopped at the breakpoint. Otherwise we only require one + or more threads stop there. If there are more than one, we return + the first thread that stopped. + """ + + target = run_to_breakpoint_make_target(test, exe_name, in_cwd) + + breakpoint = target.BreakpointCreateByName(bkpt_name, bkpt_module) + + + test.assertTrue(breakpoint.GetNumLocations() > 0, + "No locations found for name breakpoint: '%s'."%(bkpt_name)) + return run_to_breakpoint_do_run(test, target, breakpoint, launch_info, + only_one_thread, extra_images) + +def run_to_source_breakpoint(test, bkpt_pattern, source_spec, + launch_info = None, exe_name = "a.out", + bkpt_module = None, + in_cwd = True, + only_one_thread = True, + extra_images = None): + """Start up a target, using exe_name as the executable, and run it to + a breakpoint set by source regex bkpt_pattern. + + The rest of the behavior is the same as run_to_name_breakpoint. + """ + + target = run_to_breakpoint_make_target(test, exe_name, in_cwd) + # Set the breakpoints + breakpoint = target.BreakpointCreateBySourceRegex( + bkpt_pattern, source_spec, bkpt_module) + test.assertTrue(breakpoint.GetNumLocations() > 0, + 'No locations found for source breakpoint: "%s", file: "%s", dir: "%s"' + %(bkpt_pattern, source_spec.GetFilename(), source_spec.GetDirectory())) + return run_to_breakpoint_do_run(test, target, breakpoint, launch_info, + only_one_thread, extra_images) + +def run_to_line_breakpoint(test, source_spec, line_number, column = 0, + launch_info = None, exe_name = "a.out", + bkpt_module = None, + in_cwd = True, + only_one_thread = True, + extra_images = None): + """Start up a target, using exe_name as the executable, and run it to + a breakpoint set by (source_spec, line_number(, column)). + + The rest of the behavior is the same as run_to_name_breakpoint. + """ + + target = run_to_breakpoint_make_target(test, exe_name, in_cwd) + # Set the breakpoints + breakpoint = target.BreakpointCreateByLocation( + source_spec, line_number, column, 0, lldb.SBFileSpecList()) + test.assertTrue(breakpoint.GetNumLocations() > 0, + 'No locations found for line breakpoint: "%s:%d(:%d)", dir: "%s"' + %(source_spec.GetFilename(), line_number, column, + source_spec.GetDirectory())) + return run_to_breakpoint_do_run(test, target, breakpoint, launch_info, + only_one_thread, extra_images) + + +def continue_to_breakpoint(process, bkpt): + """ Continues the process, if it stops, returns the threads stopped at bkpt; otherwise, returns None""" + process.Continue() + if process.GetState() != lldb.eStateStopped: + return None + else: + return get_threads_stopped_at_breakpoint(process, bkpt) + + +def get_caller_symbol(thread): + """ + Returns the symbol name for the call site of the leaf function. + """ + depth = thread.GetNumFrames() + if depth <= 1: + return None + caller = thread.GetFrameAtIndex(1).GetSymbol() + if caller: + return caller.GetName() + else: + return None + + +def get_function_names(thread): + """ + Returns a sequence of function names from the stack frames of this thread. + """ + def GetFuncName(i): + return thread.GetFrameAtIndex(i).GetFunctionName() + + return list(map(GetFuncName, list(range(thread.GetNumFrames())))) + + +def get_symbol_names(thread): + """ + Returns a sequence of symbols for this thread. + """ + def GetSymbol(i): + return thread.GetFrameAtIndex(i).GetSymbol().GetName() + + return list(map(GetSymbol, list(range(thread.GetNumFrames())))) + + +def get_pc_addresses(thread): + """ + Returns a sequence of pc addresses for this thread. + """ + def GetPCAddress(i): + return thread.GetFrameAtIndex(i).GetPCAddress() + + return list(map(GetPCAddress, list(range(thread.GetNumFrames())))) + + +def get_filenames(thread): + """ + Returns a sequence of file names from the stack frames of this thread. + """ + def GetFilename(i): + return thread.GetFrameAtIndex( + i).GetLineEntry().GetFileSpec().GetFilename() + + return list(map(GetFilename, list(range(thread.GetNumFrames())))) + + +def get_line_numbers(thread): + """ + Returns a sequence of line numbers from the stack frames of this thread. + """ + def GetLineNumber(i): + return thread.GetFrameAtIndex(i).GetLineEntry().GetLine() + + return list(map(GetLineNumber, list(range(thread.GetNumFrames())))) + + +def get_module_names(thread): + """ + Returns a sequence of module names from the stack frames of this thread. + """ + def GetModuleName(i): + return thread.GetFrameAtIndex( + i).GetModule().GetFileSpec().GetFilename() + + return list(map(GetModuleName, list(range(thread.GetNumFrames())))) + + +def get_stack_frames(thread): + """ + Returns a sequence of stack frames for this thread. + """ + def GetStackFrame(i): + return thread.GetFrameAtIndex(i) + + return list(map(GetStackFrame, list(range(thread.GetNumFrames())))) + + +def print_stacktrace(thread, string_buffer=False): + """Prints a simple stack trace of this thread.""" + + output = SixStringIO() if string_buffer else sys.stdout + target = thread.GetProcess().GetTarget() + + depth = thread.GetNumFrames() + + mods = get_module_names(thread) + funcs = get_function_names(thread) + symbols = get_symbol_names(thread) + files = get_filenames(thread) + lines = get_line_numbers(thread) + addrs = get_pc_addresses(thread) + + if thread.GetStopReason() != lldb.eStopReasonInvalid: + desc = "stop reason=" + stop_reason_to_str(thread.GetStopReason()) + else: + desc = "" + print( + "Stack trace for thread id={0:#x} name={1} queue={2} ".format( + thread.GetThreadID(), + thread.GetName(), + thread.GetQueueName()) + desc, + file=output) + + for i in range(depth): + frame = thread.GetFrameAtIndex(i) + function = frame.GetFunction() + + load_addr = addrs[i].GetLoadAddress(target) + if not function: + file_addr = addrs[i].GetFileAddress() + start_addr = frame.GetSymbol().GetStartAddress().GetFileAddress() + symbol_offset = file_addr - start_addr + print( + " frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}".format( + num=i, + addr=load_addr, + mod=mods[i], + symbol=symbols[i], + offset=symbol_offset), + file=output) + else: + print( + " frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}".format( + num=i, + addr=load_addr, + mod=mods[i], + func='%s [inlined]' % + funcs[i] if frame.IsInlined() else funcs[i], + file=files[i], + line=lines[i], + args=get_args_as_string( + frame, + showFuncName=False) if not frame.IsInlined() else '()'), + file=output) + + if string_buffer: + return output.getvalue() + + +def print_stacktraces(process, string_buffer=False): + """Prints the stack traces of all the threads.""" + + output = SixStringIO() if string_buffer else sys.stdout + + print("Stack traces for " + str(process), file=output) + + for thread in process: + print(print_stacktrace(thread, string_buffer=True), file=output) + + if string_buffer: + return output.getvalue() + + +def expect_state_changes(test, listener, process, states, timeout=5): + """Listens for state changed events on the listener and makes sure they match what we + expect. Stop-and-restart events (where GetRestartedFromEvent() returns true) are ignored.""" + + for expected_state in states: + def get_next_event(): + event = lldb.SBEvent() + if not listener.WaitForEventForBroadcasterWithType( + timeout, + process.GetBroadcaster(), + lldb.SBProcess.eBroadcastBitStateChanged, + event): + test.fail( + "Timed out while waiting for a transition to state %s" % + lldb.SBDebugger.StateAsCString(expected_state)) + return event + + event = get_next_event() + while (lldb.SBProcess.GetStateFromEvent(event) == lldb.eStateStopped and + lldb.SBProcess.GetRestartedFromEvent(event)): + # Ignore restarted event and the subsequent running event. + event = get_next_event() + test.assertEqual( + lldb.SBProcess.GetStateFromEvent(event), + lldb.eStateRunning, + "Restarted event followed by a running event") + event = get_next_event() + + test.assertEqual( + lldb.SBProcess.GetStateFromEvent(event), + expected_state) + +# =================================== +# Utility functions related to Frames +# =================================== + + +def get_parent_frame(frame): + """ + Returns the parent frame of the input frame object; None if not available. + """ + thread = frame.GetThread() + parent_found = False + for f in thread: + if parent_found: + return f + if f.GetFrameID() == frame.GetFrameID(): + parent_found = True + + # If we reach here, no parent has been found, return None. + return None + + +def get_args_as_string(frame, showFuncName=True): + """ + Returns the args of the input frame object as a string. + """ + # arguments => True + # locals => False + # statics => False + # in_scope_only => True + vars = frame.GetVariables(True, False, False, True) # type of SBValueList + args = [] # list of strings + for var in vars: + args.append("(%s)%s=%s" % (var.GetTypeName(), + var.GetName(), + var.GetValue())) + if frame.GetFunction(): + name = frame.GetFunction().GetName() + elif frame.GetSymbol(): + name = frame.GetSymbol().GetName() + else: + name = "" + if showFuncName: + return "%s(%s)" % (name, ", ".join(args)) + else: + return "(%s)" % (", ".join(args)) + + +def print_registers(frame, string_buffer=False): + """Prints all the register sets of the frame.""" + + output = SixStringIO() if string_buffer else sys.stdout + + print("Register sets for " + str(frame), file=output) + + registerSet = frame.GetRegisters() # Return type of SBValueList. + print("Frame registers (size of register set = %d):" % + registerSet.GetSize(), file=output) + for value in registerSet: + #print(value, file=output) + print("%s (number of children = %d):" % + (value.GetName(), value.GetNumChildren()), file=output) + for child in value: + print( + "Name: %s, Value: %s" % + (child.GetName(), + child.GetValue()), + file=output) + + if string_buffer: + return output.getvalue() + + +def get_registers(frame, kind): + """Returns the registers given the frame and the kind of registers desired. + + Returns None if there's no such kind. + """ + registerSet = frame.GetRegisters() # Return type of SBValueList. + for value in registerSet: + if kind.lower() in value.GetName().lower(): + return value + + return None + + +def get_GPRs(frame): + """Returns the general purpose registers of the frame as an SBValue. + + The returned SBValue object is iterable. An example: + ... + from lldbutil import get_GPRs + regs = get_GPRs(frame) + for reg in regs: + print("%s => %s" % (reg.GetName(), reg.GetValue())) + ... + """ + return get_registers(frame, "general purpose") + + +def get_FPRs(frame): + """Returns the floating point registers of the frame as an SBValue. + + The returned SBValue object is iterable. An example: + ... + from lldbutil import get_FPRs + regs = get_FPRs(frame) + for reg in regs: + print("%s => %s" % (reg.GetName(), reg.GetValue())) + ... + """ + return get_registers(frame, "floating point") + + +def get_ESRs(frame): + """Returns the exception state registers of the frame as an SBValue. + + The returned SBValue object is iterable. An example: + ... + from lldbutil import get_ESRs + regs = get_ESRs(frame) + for reg in regs: + print("%s => %s" % (reg.GetName(), reg.GetValue())) + ... + """ + return get_registers(frame, "exception state") + +# ====================================== +# Utility classes/functions for SBValues +# ====================================== + + +class BasicFormatter(object): + """The basic formatter inspects the value object and prints the value.""" + + def format(self, value, buffer=None, indent=0): + if not buffer: + output = SixStringIO() + else: + output = buffer + # If there is a summary, it suffices. + val = value.GetSummary() + # Otherwise, get the value. + if val is None: + val = value.GetValue() + if val is None and value.GetNumChildren() > 0: + val = "%s (location)" % value.GetLocation() + print("{indentation}({type}) {name} = {value}".format( + indentation=' ' * indent, + type=value.GetTypeName(), + name=value.GetName(), + value=val), file=output) + return output.getvalue() + + +class ChildVisitingFormatter(BasicFormatter): + """The child visiting formatter prints the value and its immediate children. + + The constructor takes a keyword arg: indent_child, which defaults to 2. + """ + + def __init__(self, indent_child=2): + """Default indentation of 2 SPC's for the children.""" + self.cindent = indent_child + + def format(self, value, buffer=None): + if not buffer: + output = SixStringIO() + else: + output = buffer + + BasicFormatter.format(self, value, buffer=output) + for child in value: + BasicFormatter.format( + self, child, buffer=output, indent=self.cindent) + + return output.getvalue() + + +class RecursiveDecentFormatter(BasicFormatter): + """The recursive decent formatter prints the value and the decendents. + + The constructor takes two keyword args: indent_level, which defaults to 0, + and indent_child, which defaults to 2. The current indentation level is + determined by indent_level, while the immediate children has an additional + indentation by inden_child. + """ + + def __init__(self, indent_level=0, indent_child=2): + self.lindent = indent_level + self.cindent = indent_child + + def format(self, value, buffer=None): + if not buffer: + output = SixStringIO() + else: + output = buffer + + BasicFormatter.format(self, value, buffer=output, indent=self.lindent) + new_indent = self.lindent + self.cindent + for child in value: + if child.GetSummary() is not None: + BasicFormatter.format( + self, child, buffer=output, indent=new_indent) + else: + if child.GetNumChildren() > 0: + rdf = RecursiveDecentFormatter(indent_level=new_indent) + rdf.format(child, buffer=output) + else: + BasicFormatter.format( + self, child, buffer=output, indent=new_indent) + + return output.getvalue() + +# =========================================================== +# Utility functions for path manipulation on remote platforms +# =========================================================== + + +def join_remote_paths(*paths): + # TODO: update with actual platform name for remote windows once it exists + if lldb.remote_platform.GetName() == 'remote-windows': + return os.path.join(*paths).replace(os.path.sep, '\\') + return os.path.join(*paths).replace(os.path.sep, '/') + + +def append_to_process_working_directory(test, *paths): + remote = lldb.remote_platform + if remote: + return join_remote_paths(remote.GetWorkingDirectory(), *paths) + return os.path.join(test.getBuildDir(), *paths) + +# ================================================== +# Utility functions to get the correct signal number +# ================================================== + +import signal + + +def get_signal_number(signal_name): + platform = lldb.remote_platform + if platform and platform.IsValid(): + signals = platform.GetUnixSignals() + if signals.IsValid(): + signal_number = signals.GetSignalNumberFromName(signal_name) + if signal_number > 0: + return signal_number + # No remote platform; fall back to using local python signals. + return getattr(signal, signal_name) + + +class PrintableRegex(object): + + def __init__(self, text): + self.regex = re.compile(text) + self.text = text + + def match(self, str): + return self.regex.match(str) + + def __str__(self): + return "%s" % (self.text) + + def __repr__(self): + return "re.compile(%s) -> %s" % (self.text, self.regex) + + +def skip_if_callable(test, mycallable, reason): + if six.callable(mycallable): + if mycallable(test): + test.skipTest(reason) + return True + return False + + +def skip_if_library_missing(test, target, library): + def find_library(target, library): + for module in target.modules: + filename = module.file.GetFilename() + if isinstance(library, str): + if library == filename: + return False + elif hasattr(library, 'match'): + if library.match(filename): + return False + return True + + def find_library_callable(test): + return find_library(target, library) + return skip_if_callable( + test, + find_library_callable, + "could not find library matching '%s' in target %s" % + (library, + target)) + + +def read_file_on_target(test, remote): + if lldb.remote_platform: + local = test.getBuildArtifact("file_from_target") + error = lldb.remote_platform.Get(lldb.SBFileSpec(remote, False), + lldb.SBFileSpec(local, True)) + test.assertTrue(error.Success(), "Reading file {0} failed: {1}".format(remote, error)) + else: + local = remote + with open(local, 'r') as f: + return f.read() + +def read_file_from_process_wd(test, name): + path = append_to_process_working_directory(test, name) + return read_file_on_target(test, path) + +def wait_for_file_on_target(testcase, file_path, max_attempts=6): + for i in range(max_attempts): + err, retcode, msg = testcase.run_platform_command("ls %s" % file_path) + if err.Success() and retcode == 0: + break + if i < max_attempts: + # Exponential backoff! + import time + time.sleep(pow(2, i) * 0.25) + else: + testcase.fail( + "File %s not found even after %d attempts." % + (file_path, max_attempts)) + + return read_file_on_target(testcase, file_path) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/lock.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lock.py new file mode 100644 index 00000000000..e9970e135f9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/lock.py @@ -0,0 +1,27 @@ +""" +Interprocess mutex based on file locks +""" + +import fcntl + + +class Lock: + + def __init__(self, filename): + self.filename = filename + # This will create it if it does not exist already + unbuffered = 0 + self.handle = open(filename, 'a+', unbuffered) + + def acquire(self): + fcntl.flock(self.handle, fcntl.LOCK_EX) + + # will throw IOError if unavailable + def try_acquire(self): + fcntl.flock(self.handle, fcntl.LOCK_NB | fcntl.LOCK_EX) + + def release(self): + fcntl.flock(self.handle, fcntl.LOCK_UN) + + def __del__(self): + self.handle.close() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/Inputs/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/Inputs/main.c new file mode 100644 index 00000000000..41a6a46c926 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/Inputs/main.c @@ -0,0 +1,8 @@ +void relative(); + +int main() +{ + relative(); + // Hello Absolute! + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/Inputs/relative.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/Inputs/relative.c new file mode 100644 index 00000000000..02331834cf2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/Inputs/relative.c @@ -0,0 +1,5 @@ +void stop() {} +void relative() { + stop(); + // Hello Relative! +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/Makefile new file mode 100644 index 00000000000..8c82c73b13f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/Makefile @@ -0,0 +1,10 @@ +BOTDIR = $(BUILDDIR)/buildbot +USERDIR = $(BUILDDIR)/user +C_SOURCES = $(BOTDIR)/main.c +LD_EXTRAS = $(BOTDIR)/relative.o + +include Makefile.rules + +$(EXE): relative.o +relative.o: $(BOTDIR)/relative.c + cd $(BOTDIR) && $(CC) -c $(CFLAGS) -o $@ relative.c diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/TestDSYMSourcePathRemapping.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/TestDSYMSourcePathRemapping.py new file mode 100644 index 00000000000..0f5daf51e97 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/DBGSourcePathRemapping/TestDSYMSourcePathRemapping.py @@ -0,0 +1,61 @@ +import lldb +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbtest as lldbtest +import lldbsuite.test.lldbutil as lldbutil +import os +import unittest2 + + +class TestDSYMSourcePathRemapping(lldbtest.TestBase): + + mydir = lldbtest.TestBase.compute_mydir(__file__) + + def build(self): + botdir = self.getBuildArtifact('buildbot') + userdir = self.getBuildArtifact('user') + inputs = self.getSourcePath('Inputs') + lldbutil.mkdir_p(botdir) + lldbutil.mkdir_p(userdir) + import shutil + for f in ['main.c', 'relative.c']: + shutil.copyfile(os.path.join(inputs, f), os.path.join(botdir, f)) + shutil.copyfile(os.path.join(inputs, f), os.path.join(userdir, f)) + + super(TestDSYMSourcePathRemapping, self).build() + + # Remove the build sources. + self.assertTrue(os.path.isdir(botdir)) + shutil.rmtree(botdir) + + # Create a plist. + import subprocess + dsym = self.getBuildArtifact('a.out.dSYM') + uuid = subprocess.check_output(["/usr/bin/dwarfdump", "--uuid", dsym] + ).decode("utf-8").split(" ")[1] + import re + self.assertTrue(re.match(r'[0-9a-fA-F-]+', uuid)) + plist = os.path.join(dsym, 'Contents', 'Resources', uuid + '.plist') + with open(plist, 'w') as f: + f.write('<?xml version="1.0" encoding="UTF-8"?>\n') + f.write('<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n') + f.write('<plist version="1.0">\n') + f.write('<dict>\n') + f.write(' <key>DBGSourcePathRemapping</key>\n') + f.write(' <dict>\n') + f.write(' <key>' + botdir + '</key>\n') + f.write(' <string>' + userdir + '</string>\n') + f.write(' </dict>\n') + f.write('</dict>\n') + f.write('</plist>\n') + + + @skipIf(debug_info=no_match("dsym")) + def test(self): + self.build() + + target, process, _, _ = lldbutil.run_to_name_breakpoint( + self, 'main') + self.expect("source list -n main", substrs=["Hello Absolute"]) + bkpt = target.BreakpointCreateByName('relative') + lldbutil.continue_to_breakpoint(process, bkpt) + self.expect("source list -n relative", substrs=["Hello Relative"]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/Makefile new file mode 100644 index 00000000000..4e1ec2202d0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/Makefile @@ -0,0 +1,14 @@ +C_SOURCES = main.c + +include Makefile.rules + +all: a.out.dSYM hide.app/Contents/a.out.dSYM + +hide.app/Contents/a.out.dSYM: + mkdir hide.app + mkdir hide.app/Contents + mv a.out.dSYM hide.app/Contents + strip -x a.out +ifneq "$(CODESIGN)" "" + $(CODESIGN) -fs - a.out +endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py new file mode 100644 index 00000000000..df9716ff513 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py @@ -0,0 +1,46 @@ +"""Test that the 'add-dsym', aka 'target symbols add', succeeds in the middle of debug session.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipUnlessDarwin +class AddDsymMidExecutionCommandCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.source = 'main.c' + + @no_debug_info_test # Prevent the genaration of the dwarf version of this test + def test_add_dsym_mid_execution(self): + """Test that add-dsym mid-execution loads the symbols at the right place for a slid binary.""" + self.buildDefault(dictionary={'MAKE_DSYM':'YES'}) + exe = self.getBuildArtifact("a.out") + + self.target = self.dbg.CreateTarget(exe) + self.assertTrue(self.target, VALID_TARGET) + + main_bp = self.target.BreakpointCreateByName("main", "a.out") + self.assertTrue(main_bp, VALID_BREAKPOINT) + + self.runCmd("settings set target.disable-aslr false") + self.process = self.target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(self.process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + self.assertTrue(self.process.GetState() == lldb.eStateStopped, + STOPPED_DUE_TO_BREAKPOINT) + + self.runCmd("add-dsym " + + self.getBuildArtifact("hide.app/Contents/a.out.dSYM")) + + self.expect("frame select", + substrs=['a.out`main at main.c']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/main.c new file mode 100644 index 00000000000..da9e09f0738 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/add-dsym/main.c @@ -0,0 +1,7 @@ +#include <stdio.h> +static int var = 5; +int main () +{ + printf ("%p is %d\n", &var, var); // break on this line + return ++var; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/Makefile new file mode 100644 index 00000000000..b880d9e722b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/Makefile @@ -0,0 +1,20 @@ +C_SOURCES := main.c + +# Make an archive that has two object files with the same name, but +# different timestamps. Do it all in one rule so that the timestamps +# can be controlled without confusing Make. +libfoo.a: a.c sub1/a.c + $(CC) $(CFLAGS) -c $(<D)/a.c -o a.o + mkdir -p sub1 + $(CC) $(CFLAGS) -c $(<D)/sub1/a.c -o sub1/a.o + touch -t '198001010000.00' a.o + touch -t '198001010000.01' sub1/a.o + $(AR) $(ARFLAGS) $@ a.o sub1/a.o + rm a.o sub1/a.o + +include Makefile.rules + +# Needs to come after include +OBJECTS += libfoo.a +$(EXE) : libfoo.a +.DEFAULT_GOAL := $(EXE) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/TestDuplicateMembers.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/TestDuplicateMembers.py new file mode 100644 index 00000000000..3fecb3beae5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/TestDuplicateMembers.py @@ -0,0 +1,52 @@ +"""Test breaking inside functions defined within a BSD archive file libfoo.a.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BSDArchivesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @expectedFailureAll( + oslist=["windows"], + bugnumber="llvm.org/pr24527. Makefile.rules doesn't know how to build static libs on Windows") + def test(self): + """Break inside a() and b() defined within libfoo.a.""" + self.build() + + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Break on a() and b() symbols + lldbutil.run_break_set_by_symbol( + self, "a", sym_exact=True) + lldbutil.run_break_set_by_symbol( + self, "b", sym_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # Break at a(int) first. + self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int) arg = 1']) + self.expect("frame variable __a_global", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int) __a_global = 1']) + + # Continue the program, we should break at b(int) next. + self.runCmd("continue") + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int) arg = 2']) + self.expect("frame variable __b_global", VARIABLES_DISPLAYED_CORRECTLY, + substrs=['(int) __b_global = 2']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/a.c new file mode 100644 index 00000000000..4d57868c320 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/a.c @@ -0,0 +1,13 @@ +//===-- a.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +int __a_global = 1; + +int a(int arg) { + int result = arg + __a_global; + return result; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/main.c new file mode 100644 index 00000000000..1525a1a5e38 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/main.c @@ -0,0 +1,16 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +extern int a(int); +extern int b(int); +int main (int argc, char const *argv[]) +{ + printf ("a(1) returns %d\n", a(1)); + printf ("b(2) returns %d\n", b(2)); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/sub1/a.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/sub1/a.c new file mode 100644 index 00000000000..e90218c9676 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/duplicate-archive-members/sub1/a.c @@ -0,0 +1,13 @@ +//===-- a.c -----------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +static int __b_global = 2; + +int b(int arg) { + int result = arg + __b_global; + return result; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/Makefile new file mode 100644 index 00000000000..68012d22f5b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/Makefile @@ -0,0 +1,20 @@ +SRCDIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))/ +CC ?= clang + +ifeq "$(ARCH)" "" + ARCH = x86_64 +endif + +CFLAGS ?= -g -O0 -arch $(ARCH) + +all: TestApp.app/Contents/MacOS/TestApp + +TestApp.app/Contents/MacOS/TestApp: $(SRCDIR)/main.c + $(CC) $(CFLAGS) -o TestApp $< + rm -rf TestApp.app + cp -r $(SRCDIR)/TestApp.app . + mv TestApp TestApp.app/Contents/MacOS/TestApp + mv TestApp.dSYM TestApp.app.dSYM + +clean: + rm -rf TestApp.app/Contents/MacOS/TestApp TestApp.app.dSYM diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestApp.app/Contents/Info.plist b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestApp.app/Contents/Info.plist new file mode 100644 index 00000000000..a47f72bb14d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestApp.app/Contents/Info.plist @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>en</string> + <key>CFBundleExecutable</key> + <string>TestApp</string> + <key>CFBundleIdentifier</key> + <string>com.lldb.TestApp</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>TestApp</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleShortVersionString</key> + <string>1.0</string> + <key>CFBundleSupportedPlatforms</key> + <array> + <string>MacOSX</string> + </array> + <key>CFBundleVersion</key> + <string>1</string> + <key>LSMinimumSystemVersion</key> + <string>10.8</string> + <key>NSHumanReadableCopyright</key> + <string>Copyright © 2018 Jim Ingham. All rights reserved.</string> +</dict> +</plist> diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestApp.app/Contents/MacOS/.empty b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestApp.app/Contents/MacOS/.empty new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestApp.app/Contents/MacOS/.empty diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestApp.app/Contents/Resources/.empty b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestApp.app/Contents/Resources/.empty new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestApp.app/Contents/Resources/.empty diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestFindAppInBundle.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestFindAppInBundle.py new file mode 100644 index 00000000000..99d21f02208 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/TestFindAppInBundle.py @@ -0,0 +1,58 @@ +""" +Make sure we can find the binary inside an app bundle. +""" + + + +import lldb +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import lldbsuite.test.lldbplatformutil as lldbplatformutil +from lldbsuite.test.lldbtest import * + +@decorators.skipUnlessDarwin +class FindAppInMacOSAppBundle(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test_find_app_in_bundle(self): + """There can be many tests in a test case - describe this test here.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.c") + self.find_app_in_bundle_test() + + def find_app_in_bundle_test(self): + """This reads in the .app, makes sure we get the right binary and can run it.""" + + # This function starts a process, "a.out" by default, sets a source + # breakpoint, runs to it, and returns the thread, process & target. + # It optionally takes an SBLaunchOption argument if you want to pass + # arguments or environment variables. + exe = self.getBuildArtifact("TestApp.app") + error = lldb.SBError() + target = self.dbg.CreateTarget(exe, None, None, False, error) + self.assertTrue(error.Success(), "Could not create target: %s"%(error.GetCString())) + self.assertTrue(target.IsValid(), "Target: TestApp.app is not valid.") + exe_module_spec = target.GetExecutable() + self.assertTrue(exe_module_spec.GetFilename(), "TestApp") + + bkpt = target.BreakpointCreateBySourceRegex("Set a breakpoint here", self.main_source_file) + self.assertTrue(bkpt.GetNumLocations() == 1, "Couldn't set a breakpoint in the main app") + + if lldbplatformutil.getPlatform() == "macosx": + launch_info = lldb.SBLaunchInfo(None) + launch_info.SetWorkingDirectory(self.get_process_working_directory()) + + error = lldb.SBError() + process = target.Launch(launch_info, error) + + self.assertTrue(process.IsValid(), "Could not create a valid process for TestApp: %s"%(error.GetCString())) + + # Frame #0 should be at our breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint(process, bkpt) + + self.assertTrue(len(threads) == 1, "Expected 1 thread to stop at breakpoint, %d did."%(len(threads))) + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/main.c new file mode 100644 index 00000000000..27a0cdc01a9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-app-in-bundle/main.c @@ -0,0 +1,9 @@ +#include <stdio.h> + +int +main() +{ + printf("Set a breakpoint here.\n"); + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/Makefile new file mode 100644 index 00000000000..658c9a93870 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/Makefile @@ -0,0 +1,22 @@ +SRCDIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))/ +CC ?= clang + +ifeq "$(ARCH)" "" + ARCH = x86_64 +endif + +CFLAGS ?= -g -O0 -arch $(ARCH) + +all: clean + $(CC) $(CFLAGS) -dynamiclib -o com.apple.sbd $(SRCDIR)/bundle.c + mkdir com.apple.sbd.xpc + mv com.apple.sbd com.apple.sbd.xpc/ + mkdir -p com.apple.sbd.xpc.dSYM/Contents/Resources/DWARF + mv com.apple.sbd.dSYM/Contents/Resources/DWARF/com.apple.sbd com.apple.sbd.xpc.dSYM/Contents/Resources/DWARF/ + rm -rf com.apple.sbd.dSYM + mkdir hide.app + tar cf - com.apple.sbd.xpc com.apple.sbd.xpc.dSYM | ( cd hide.app;tar xBpf -) + $(CC) $(CFLAGS) -o find-bundle-with-dots-in-fn $(SRCDIR)/main.c + +clean: + rm -rf a.out a.out.dSYM hide.app com.apple.sbd com.apple.sbd.dSYM com.apple.sbd.xpc com.apple.sbd.xpc.dSYM find-bundle-with-dots-in-fn find-bundle-with-dots-in-fn.dSYM diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py new file mode 100644 index 00000000000..6b38d3c3aa7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/TestBundleWithDotInFilename.py @@ -0,0 +1,72 @@ +"""Test that a dSYM can be found when a binary is in a bundle hnd has dots in the filename.""" + + +#import unittest2 +import os.path +from time import sleep + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +exe_name = 'find-bundle-with-dots-in-fn' # must match Makefile + +class BundleWithDotInFilenameTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfRemote + @skipUnlessDarwin + # This test is explicitly a dSYM test, it doesn't need to run for any other config, but + # the following doesn't work, fixme. + # @skipIf(debug_info=no_match(["dsym"]), bugnumber="This test is looking explicitly for a dSYM") + + def setUp(self): + TestBase.setUp(self) + self.source = 'main.c' + + def tearDown(self): + # Destroy process before TestBase.tearDown() + self.dbg.GetSelectedTarget().GetProcess().Destroy() + + # Call super's tearDown(). + TestBase.tearDown(self) + + def test_attach_and_check_dsyms(self): + """Test attach to binary, see if the bundle dSYM is found""" + exe = self.getBuildArtifact(exe_name) + self.build() + os.chdir(self.getBuildDir()); + popen = self.spawnSubprocess(exe) + self.addTearDownHook(self.cleanupSubprocesses) + + # Give the inferior time to start up, dlopen a bundle, remove the bundle it linked in + sleep(5) + + # Since the library that was dlopen()'ed is now removed, lldb will need to find the + # binary & dSYM via target.exec-search-paths + settings_str = "settings set target.exec-search-paths " + self.get_process_working_directory() + "/hide.app" + self.runCmd(settings_str) + + self.runCmd("process attach -p " + str(popen.pid)) + + target = self.dbg.GetSelectedTarget() + self.assertTrue(target.IsValid(), 'Should have a valid Target after attaching to process') + + setup_complete = target.FindFirstGlobalVariable("setup_is_complete") + self.assertTrue(setup_complete.GetValueAsUnsigned() == 1, 'Check that inferior process has completed setup') + + # Find the bundle module, see if we found the dSYM too (they're both in "hide.app") + i = 0 + while i < target.GetNumModules(): + mod = target.GetModuleAtIndex(i) + if mod.GetFileSpec().GetFilename() == 'com.apple.sbd': + dsym_name = mod.GetSymbolFileSpec().GetFilename() + self.assertTrue (dsym_name == 'com.apple.sbd', "Check that we found the dSYM for the bundle that was loaded") + i=i+1 + os.chdir(self.getSourceDir()); + +if __name__ == '__main__': + unittest.main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/bundle.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/bundle.c new file mode 100644 index 00000000000..c100f9a2c07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/bundle.c @@ -0,0 +1,4 @@ +int foo () +{ + return 5; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/main.c new file mode 100644 index 00000000000..30761eb1b40 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/bundle-with-dot-in-filename/main.c @@ -0,0 +1,28 @@ +#include <dlfcn.h> +#include <unistd.h> +#include <stdlib.h> + +int setup_is_complete = 0; + +int main() +{ + + void *handle = dlopen ("com.apple.sbd.xpc/com.apple.sbd", RTLD_NOW); + if (handle) + { + if (dlsym(handle, "foo")) + { + system ("/bin/rm -rf com.apple.sbd.xpc com.apple.sbd.xpc.dSYM"); + setup_is_complete = 1; + + // At this point we want lldb to attach to the process. If lldb attaches + // before we've removed the dlopen'ed bundle, lldb will find the bundle + // at its actual filepath and not have to do any tricky work, invalidating + // the test. + + for (int loop_limiter = 0; loop_limiter < 100; loop_limiter++) + sleep (1); + } + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/Info.plist b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/Info.plist new file mode 100644 index 00000000000..82e17116e35 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/Info.plist @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>BuildMachineOSBuild</key> + <string>16B2657</string> + <key>CFBundleDevelopmentRegion</key> + <string>en</string> + <key>CFBundleExecutable</key> + <string>MyFramework</string> + <key>CFBundleIdentifier</key> + <string>com.apple.test.framework</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>MyFramework</string> + <key>CFBundlePackageType</key> + <string>FMWK</string> + <key>CFBundleShortVersionString</key> + <string>113</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleSupportedPlatforms</key> + <array> + <string>MacOSX</string> + </array> + <key>CFBundleVersion</key> + <string>113</string> + <key>DTCompiler</key> + <string>com.apple.compilers.llvm.clang.1_0</string> + <key>DTPlatformBuild</key> + <string>9L120i</string> + <key>DTPlatformVersion</key> + <string>GM</string> + <key>DTSDKBuild</key> + <string>17A261x</string> + <key>DTSDKName</key> + <string>macosx10.13</string> + <key>DTXcode</key> + <string>0900</string> + <key>DTXcodeBuild</key> + <string>9L120i</string> +</dict> +</plist> diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/Makefile new file mode 100644 index 00000000000..b2a66c2ad41 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/Makefile @@ -0,0 +1,29 @@ +SRCDIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))/ +CC ?= clang + +ifeq "$(ARCH)" "" + ARCH = x86_64 +endif + +CFLAGS ?= -g -O0 -arch $(ARCH) + +all: clean + $(CC) $(CFLAGS) -install_name $(shell pwd)/MyFramework.framework/Versions/A/MyFramework -dynamiclib -o MyFramework $(SRCDIR)/myframework.c + mkdir -p MyFramework.framework/Versions/A/Headers + mkdir -p MyFramework.framework/Versions/A/Resources + cp MyFramework MyFramework.framework/Versions/A + cp $(SRCDIR)/MyFramework.h MyFramework.framework/Versions/A/Headers + cp $(SRCDIR)/Info.plist MyFramework.framework/Versions/A/Resources + ( cd MyFramework.framework/Versions ; ln -s A Current ) + ( cd MyFramework.framework/ ; ln -s Versions/Current/Headers . ) + ( cd MyFramework.framework/ ; ln -s Versions/Current/MyFramework . ) + ( cd MyFramework.framework/ ; ln -s Versions/Current/Resources . ) + mv MyFramework.dSYM MyFramework.framework.dSYM + mkdir hide.app + rm -f MyFramework + tar cf - MyFramework.framework MyFramework.framework.dSYM | ( cd hide.app;tar xBpf -) + $(CC) $(CFLAGS) -o deep-bundle $(SRCDIR)/main.c -F. -framework MyFramework + + +clean: + rm -rf a.out a.out.dSYM deep-bundle deep-bundle.dSYM MyFramework.framework MyFramework.framework.dSYM MyFramework MyFramework.dSYM hide.app diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/MyFramework.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/MyFramework.h new file mode 100644 index 00000000000..a4536647cfc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/MyFramework.h @@ -0,0 +1 @@ +int foo (); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/TestDeepBundle.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/TestDeepBundle.py new file mode 100644 index 00000000000..ecab53587a7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/TestDeepBundle.py @@ -0,0 +1,72 @@ +"""Test that a dSYM can be found when a binary is in a deep bundle with multiple pathname components.""" + + +#import unittest2 +from time import sleep + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +exe_name = 'deep-bundle' # must match Makefile + +class DeepBundleTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfRemote + @skipUnlessDarwin + # This test is explicitly a dSYM test, it doesn't need to run for any other config, but + # the following doesn't work, fixme. + # @skipIf(debug_info=no_match(["dsym"]), bugnumber="This test is looking explicitly for a dSYM") + + def setUp(self): + TestBase.setUp(self) + self.source = 'main.c' + + def tearDown(self): + # Destroy process before TestBase.tearDown() + self.dbg.GetSelectedTarget().GetProcess().Destroy() + + # Call super's tearDown(). + TestBase.tearDown(self) + + def test_attach_and_check_dsyms(self): + """Test attach to binary, see if the framework dSYM is found""" + exe = self.getBuildArtifact(exe_name) + self.build() + popen = self.spawnSubprocess(exe, [self.getBuildDir()]) + self.addTearDownHook(self.cleanupSubprocesses) + + # Give the inferior time to start up, dlopen a bundle, remove the bundle it linked in + sleep(5) + + # Since the library that was dlopen()'ed is now removed, lldb will need to find the + # binary & dSYM via target.exec-search-paths + settings_str = "settings set target.exec-search-paths " + self.get_process_working_directory() + "/hide.app" + self.runCmd(settings_str) + self.runCmd("process attach -p " + str(popen.pid)) + + target = self.dbg.GetSelectedTarget() + self.assertTrue(target.IsValid(), 'Should have a valid Target after attaching to process') + + setup_complete = target.FindFirstGlobalVariable("setup_is_complete") + self.assertTrue(setup_complete.GetValueAsUnsigned() == 1, 'Check that inferior process has completed setup') + + # Find the bundle module, see if we found the dSYM too (they're both in "hide.app") + i = 0 + found_module = False + while i < target.GetNumModules(): + mod = target.GetModuleAtIndex(i) + if mod.GetFileSpec().GetFilename() == 'MyFramework': + found_module = True + dsym_name = mod.GetSymbolFileSpec().GetFilename() + self.assertTrue (dsym_name == 'MyFramework', "Check that we found the dSYM for the bundle that was loaded") + i=i+1 + + self.assertTrue(found_module, "Check that we found the framework loaded in lldb's image list") + +if __name__ == '__main__': + unittest.main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/main.c new file mode 100644 index 00000000000..b5ef5cff74a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/main.c @@ -0,0 +1,27 @@ +#include <MyFramework/MyFramework.h> +#include <unistd.h> +#include <stdio.h> +#include <stdlib.h> + +int setup_is_complete = 0; + +int main(int argc, const char **argv) +{ + char command[8192]; + sprintf (command, + "/bin/rm -rf %s/MyFramework %s/MyFramework.framework %s/MyFramework.framework.dSYM", + argv[1], argv[1], argv[1]); + system (command); + + setup_is_complete = 1; + + // At this point we want lldb to attach to the process. If lldb attaches + // before we've removed the framework we're running against, it will be + // easy for lldb to find the binary & dSYM without using target.exec-search-paths, + // which is the point of this test. + + for (int loop_limiter = 0; loop_limiter < 100; loop_limiter++) + sleep (1); + + return foo(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/myframework.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/myframework.c new file mode 100644 index 00000000000..c100f9a2c07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/find-dsym/deep-bundle/myframework.c @@ -0,0 +1,4 @@ +int foo () +{ + return 5; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/function-starts/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/function-starts/Makefile new file mode 100644 index 00000000000..0d6f5172939 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/function-starts/Makefile @@ -0,0 +1,8 @@ +CXX_SOURCES := main.cpp +EXE := StripMe +MAKE_DSYM := NO + +include Makefile.rules + +main.o: main.cpp + $(CC) $(CFLAGS_NO_DEBUG) -c $< -o $@ diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/function-starts/TestFunctionStarts.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/function-starts/TestFunctionStarts.py new file mode 100644 index 00000000000..e876cdf8b5d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/function-starts/TestFunctionStarts.py @@ -0,0 +1,86 @@ +""" +Test that we read the function starts section. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +exe_name = "StripMe" # Must match Makefile + +class FunctionStartsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + @skipIfRemote + @skipUnlessDarwin + def test_function_starts_binary(self): + """Test that we make synthetic symbols when we have the binary.""" + self.build() + self.do_function_starts(False) + + @skipIfRemote + @skipUnlessDarwin + def test_function_starts_no_binary(self): + """Test that we make synthetic symbols when we don't have the binary""" + self.build() + self.do_function_starts(True) + + def do_function_starts(self, in_memory): + """Run the binary, stop at our unstripped function, + make sure the caller has synthetic symbols""" + + exe = self.getBuildArtifact(exe_name) + # Now strip the binary, but leave externals so we can break on dont_strip_me. + try: + fail_str = system([["strip", "-u", "-x", "-S", exe]]) + except CalledProcessError as cmd_error: + self.fail("Strip failed: %d"%(cmd_error.returncode)) + + # Use a file as a synchronization point between test and inferior. + pid_file_path = lldbutil.append_to_process_working_directory(self, + "token_pid_%d" % (int(os.getpid()))) + self.addTearDownHook( + lambda: self.run_platform_command( + "rm %s" % + (pid_file_path))) + + popen = self.spawnSubprocess(exe, [pid_file_path]) + self.addTearDownHook(self.cleanupSubprocesses) + + # Wait until process has fully started up. + pid = lldbutil.wait_for_file_on_target(self, pid_file_path) + + if in_memory: + remove_file(exe) + + target = self.dbg.CreateTarget(None) + self.assertTrue(target.IsValid(), "Got a vaid empty target.") + error = lldb.SBError() + attach_info = lldb.SBAttachInfo() + attach_info.SetProcessID(popen.pid) + attach_info.SetIgnoreExisting(False) + process = target.Attach(attach_info, error) + self.assertTrue(error.Success(), "Didn't attach successfully to %d: %s"%(popen.pid, error.GetCString())) + + bkpt = target.BreakpointCreateByName("dont_strip_me", exe) + self.assertTrue(bkpt.GetNumLocations() > 0, "Didn't set the dont_strip_me bkpt.") + + threads = lldbutil.continue_to_breakpoint(process, bkpt) + self.assertEqual(len(threads), 1, "Didn't hit my breakpoint.") + + # Our caller frame should have been stripped. Make sure we made a synthetic symbol + # for it: + thread = threads[0] + self.assertTrue(thread.num_frames > 1, "Couldn't backtrace.") + name = thread.frame[1].GetFunctionName() + self.assertTrue(name.startswith("___lldb_unnamed_symbol")) + self.assertTrue(name.endswith("$$StripMe")) + + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/function-starts/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/function-starts/main.cpp new file mode 100644 index 00000000000..188078a22ed --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/function-starts/main.cpp @@ -0,0 +1,32 @@ +#include <stdio.h> +#include <fcntl.h> + +#include <chrono> +#include <fstream> +#include <thread> + +extern void dont_strip_me() +{ + printf("I wasn't stripped\n"); +} + +static void *a_function() +{ + while (1) + { + std::this_thread::sleep_for(std::chrono::microseconds(100)); + dont_strip_me(); + } + return 0; +} + +int main(int argc, char const *argv[]) +{ + { + // Create file to signal that this process has started up. + std::ofstream f; + f.open(argv[1]); + } + a_function(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/Makefile new file mode 100644 index 00000000000..929ed58f757 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/Makefile @@ -0,0 +1,16 @@ +C_SOURCES := main.c +LD_EXTRAS := -L. -lindirect -lreexport + +.PHONY: build-libindirect build-libreepxoprt +all: build-libindirect build-libreepxoprt a.out + +include Makefile.rules + +build-libindirect: indirect.c + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_C_SOURCES=indirect.c DYLIB_NAME=indirect DYLIB_ONLY=YES + +build-libreepxoprt: reexport.c + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_C_SOURCES=reexport.c DYLIB_NAME=reexport DYLIB_ONLY=YES \ + LD_EXTRAS="-L. -lindirect -Wl,-alias_list,$(SRCDIR)/alias.list" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py new file mode 100644 index 00000000000..2718bd746a0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py @@ -0,0 +1,115 @@ +"""Test stepping and setting breakpoints in indirect and re-exported symbols.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestIndirectFunctions(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers that we will step to in main: + self.main_source = "main.c" + + @skipUnlessDarwin + @expectedFailureAll(oslist=no_match(["macosx"]), bugnumber="rdar://55952764") + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test stepping and setting breakpoints in indirect and re-exported symbols.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + if self.platformIsDarwin(): + lib1 = self.getBuildArtifact('libindirect.dylib') + lib2 = self.getBuildArtifact('libreexport.dylib') + self.registerSharedLibrariesWithTarget(target, [lib1, lib2]) + + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + break1 = target.BreakpointCreateBySourceRegex( + "Set breakpoint here to step in indirect.", self.main_source_spec) + self.assertTrue(break1, VALID_BREAKPOINT) + + break2 = target.BreakpointCreateBySourceRegex( + "Set breakpoint here to step in reexported.", self.main_source_spec) + self.assertTrue(break2, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) + if len(threads) != 1: + self.fail("Failed to stop at breakpoint 1.") + + thread = threads[0] + + # Now do a step-into, and we should end up in the hidden target of this + # indirect function. + thread.StepInto() + curr_function = thread.GetFrameAtIndex(0).GetFunctionName() + self.assertEqual(curr_function, "call_through_indirect_hidden", + "Stepped into indirect symbols.") + + # Now set a breakpoint using the indirect symbol name, and make sure we + # get to that: + break_indirect = target.BreakpointCreateByName("call_through_indirect") + self.assertTrue(break_indirect, VALID_BREAKPOINT) + + # Now continue should take us to the second call through the indirect + # symbol: + + threads = lldbutil.continue_to_breakpoint(process, break_indirect) + self.assertTrue( + len(threads) == 1, + "Stopped at breakpoint in indirect function.") + curr_function = thread.GetFrameAtIndex(0).GetFunctionName() + self.assertTrue( + curr_function == "call_through_indirect_hidden", + "Stepped into indirect symbols.") + + # Delete this breakpoint so it won't get in the way: + target.BreakpointDelete(break_indirect.GetID()) + + # Now continue to the site of the first re-exported function call in + # main: + threads = lldbutil.continue_to_breakpoint(process, break2) + + # This is stepping Into through a re-exported symbol to an indirect + # symbol: + thread.StepInto() + curr_function = thread.GetFrameAtIndex(0).GetFunctionName() + self.assertTrue( + curr_function == "call_through_indirect_hidden", + "Stepped into indirect symbols.") + + # And the last bit is to set a breakpoint on the re-exported symbol and + # make sure we are again in out target function. + break_reexported = target.BreakpointCreateByName( + "reexport_to_indirect") + self.assertTrue(break_reexported, VALID_BREAKPOINT) + + # Now continue should take us to the second call through the indirect + # symbol: + + threads = lldbutil.continue_to_breakpoint(process, break_reexported) + self.assertTrue( + len(threads) == 1, + "Stopped at breakpoint in reexported function target.") + curr_function = thread.GetFrameAtIndex(0).GetFunctionName() + self.assertTrue( + curr_function == "call_through_indirect_hidden", + "Stepped into indirect symbols.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/alias.list b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/alias.list new file mode 100644 index 00000000000..3232c588837 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/alias.list @@ -0,0 +1 @@ +_call_through_indirect _reexport_to_indirect
\ No newline at end of file diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/indirect.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/indirect.c new file mode 100644 index 00000000000..48e1459bb59 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/indirect.c @@ -0,0 +1,14 @@ +#define MakeResolver(name) \ + void * name ## Resolver(void) __asm__("_" #name); \ + void * name ## Resolver(void) { \ + __asm__(".symbol_resolver _" #name); \ + return name ## _hidden; \ + } + +int +call_through_indirect_hidden(int arg) +{ + return arg + 5; +} + +MakeResolver(call_through_indirect) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/main.c new file mode 100644 index 00000000000..b5af058d00b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/main.c @@ -0,0 +1,14 @@ +extern int call_through_indirect(int); +extern int reexport_to_indirect(int); + +int +main () +{ + int indirect_result = call_through_indirect(20); // Set breakpoint here to step in indirect. + indirect_result = call_through_indirect(30); + + int reexport_result = reexport_to_indirect (20); // Set breakpoint here to step in reexported. + reexport_result = reexport_to_indirect (30); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/reexport.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/reexport.c new file mode 100644 index 00000000000..096a463b3a4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/indirect_symbol/reexport.c @@ -0,0 +1,7 @@ +extern int call_through_indirect(int); + +int +fake_call_through_reexport(int value) +{ + return value + 10; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/Makefile new file mode 100644 index 00000000000..ad37346bbeb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/Makefile @@ -0,0 +1,11 @@ +MAKE_DSYM := NO + +C_SOURCES := main.c + +all: a.out create-empty-corefile + +create-empty-corefile: + $(MAKE) -f $(MAKEFILE_RULES) EXE=create-empty-corefile \ + C_SOURCES=create-empty-corefile.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/TestKernVerStrLCNOTE.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/TestKernVerStrLCNOTE.py new file mode 100644 index 00000000000..80007438add --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/TestKernVerStrLCNOTE.py @@ -0,0 +1,99 @@ +"""Test that corefiles with an LC_NOTE "kern ver str" load command is used.""" + + + +import os +import re +import subprocess + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestKernVerStrLCNOTE(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(debug_info=no_match(["dsym"]), bugnumber="This test is looking explicitly for a dSYM") + @skipIfDarwinEmbedded + @skipUnlessDarwin + def test_lc_note(self): + self.build() + self.test_exe = self.getBuildArtifact("a.out") + self.create_corefile = self.getBuildArtifact("create-empty-corefile") + self.dsym_for_uuid = self.getBuildArtifact("dsym-for-uuid.sh") + self.corefile = self.getBuildArtifact("core") + + ## We can hook in our dsym-for-uuid shell script to lldb with this env + ## var instead of requiring a defaults write. + os.environ['LLDB_APPLE_DSYMFORUUID_EXECUTABLE'] = self.dsym_for_uuid + self.addTearDownHook(lambda: os.environ.pop('LLDB_APPLE_DSYMFORUUID_EXECUTABLE', None)) + + dwarfdump_uuid_regex = re.compile( + 'UUID: ([-0-9a-fA-F]+) \(([^\(]+)\) .*') + dwarfdump_cmd_output = subprocess.check_output( + ('/usr/bin/dwarfdump --uuid "%s"' % self.test_exe), shell=True).decode("utf-8") + aout_uuid = None + for line in dwarfdump_cmd_output.splitlines(): + match = dwarfdump_uuid_regex.search(line) + if match: + aout_uuid = match.group(1) + self.assertNotEqual(aout_uuid, None, "Could not get uuid of built a.out") + + ### Create our dsym-for-uuid shell script which returns self.test_exe + ### and its dSYM when given self.test_exe's UUID. + shell_cmds = [ + '#! /bin/sh', + 'ret=0', + 'echo "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>"', + 'echo "<!DOCTYPE plist PUBLIC \\"-//Apple//DTD PLIST 1.0//EN\\" \\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\\">"', + 'echo "<plist version=\\"1.0\\">"', + '', + '# the last arugment is probably the uuid', + 'while [ $# -gt 1 ]', + 'do', + ' shift', + 'done', + 'echo "<dict><key>$1</key><dict>"', + '', + 'if [ "$1" = "%s" ]' % aout_uuid, + 'then', + ' echo "<key>DBGArchitecture</key><string>x86_64</string>"', + ' echo "<key>DBGDSYMPath</key><string>%s.dSYM/Contents/Resources/DWARF/%s</string>"' % (self.test_exe, os.path.basename(self.test_exe)), + ' echo "<key>DBGSymbolRichExecutable</key><string>%s</string>"' % self.test_exe, + 'else', + ' echo "<key>DBGError</key><string>not found</string>"', + ' ret=1', + 'fi', + 'echo "</dict></dict></plist>"', + 'exit $ret' + ] + + with open(self.dsym_for_uuid, "w") as writer: + for l in shell_cmds: + writer.write(l + '\n') + + os.chmod(self.dsym_for_uuid, 0o755) + + ### Create our corefile + retcode = call(self.create_corefile + " " + self.corefile + " " + self.test_exe, shell=True) + + ### Now run lldb on the corefile + ### which will give us a UUID + ### which we call dsym-for-uuid.sh with + ### which gives us a binary and dSYM + ### which lldb should load! + + + self.target = self.dbg.CreateTarget('') + err = lldb.SBError() + self.process = self.target.LoadCore(self.corefile) + self.assertEqual(self.process.IsValid(), True) + if self.TraceOn(): + self.runCmd("image list") + self.assertEqual(self.target.GetNumModules(), 1) + fspec = self.target.GetModuleAtIndex(0).GetFileSpec() + filepath = fspec.GetDirectory() + "/" + fspec.GetFilename() + self.assertEqual(filepath, self.test_exe) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/create-empty-corefile.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/create-empty-corefile.cpp new file mode 100644 index 00000000000..8a8115af967 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/create-empty-corefile.cpp @@ -0,0 +1,315 @@ +#include <stdio.h> +#include <stdlib.h> +#include <mach-o/loader.h> +#include <vector> +#include <string> +#include <mach/thread_status.h> +#include <string.h> +#include <uuid/uuid.h> + +// Create an empty corefile with a "kern ver str" LC_NOTE. +// If an existing binary is given as an optional 2nd argument on the cmd line, +// the UUID from that binary will be encoded in the corefile. +// Otherwise a pre-set UUID will be put in the corefile that +// is created. + + +union uint32_buf { + uint8_t bytebuf[4]; + uint32_t val; +}; + +union uint64_buf { + uint8_t bytebuf[8]; + uint64_t val; +}; + +void +add_uint64(std::vector<uint8_t> &buf, uint64_t val) +{ + uint64_buf conv; + conv.val = val; + for (int i = 0; i < 8; i++) + buf.push_back(conv.bytebuf[i]); +} + +void +add_uint32(std::vector<uint8_t> &buf, uint32_t val) +{ + uint32_buf conv; + conv.val = val; + for (int i = 0; i < 4; i++) + buf.push_back(conv.bytebuf[i]); +} + +std::vector<uint8_t> +x86_lc_thread_load_command () +{ + std::vector<uint8_t> data; + add_uint32 (data, LC_THREAD); // thread_command.cmd + add_uint32 (data, 184); // thread_command.cmdsize + add_uint32 (data, x86_THREAD_STATE64); // thread_command.flavor + add_uint32 (data, x86_THREAD_STATE64_COUNT); // thread_command.count + add_uint64 (data, 0x0000000000000000); // rax + add_uint64 (data, 0x0000000000000400); // rbx + add_uint64 (data, 0x0000000000000000); // rcx + add_uint64 (data, 0x0000000000000000); // rdx + add_uint64 (data, 0x0000000000000000); // rdi + add_uint64 (data, 0x0000000000000000); // rsi + add_uint64 (data, 0xffffff9246e2ba20); // rbp + add_uint64 (data, 0xffffff9246e2ba10); // rsp + add_uint64 (data, 0x0000000000000000); // r8 + add_uint64 (data, 0x0000000000000000); // r9 + add_uint64 (data, 0x0000000000000000); // r10 + add_uint64 (data, 0x0000000000000000); // r11 + add_uint64 (data, 0xffffff7f96ce5fe1); // r12 + add_uint64 (data, 0x0000000000000000); // r13 + add_uint64 (data, 0x0000000000000000); // r14 + add_uint64 (data, 0xffffff9246e2bac0); // r15 + add_uint64 (data, 0xffffff8015a8f6d0); // rip + add_uint64 (data, 0x0000000000011111); // rflags + add_uint64 (data, 0x0000000000022222); // cs + add_uint64 (data, 0x0000000000033333); // fs + add_uint64 (data, 0x0000000000044444); // gs + return data; +} + +void +add_lc_note_kern_ver_str_load_command (std::vector<std::vector<uint8_t> > &loadcmds, + std::vector<uint8_t> &payload, + int payload_file_offset, + std::string ident) +{ + std::vector<uint8_t> loadcmd_data; + + add_uint32 (loadcmd_data, LC_NOTE); // note_command.cmd + add_uint32 (loadcmd_data, 40); // note_command.cmdsize + char lc_note_name[16]; + memset (lc_note_name, 0, 16); + strcpy (lc_note_name, "kern ver str"); + + // lc_note.data_owner + for (int i = 0; i < 16; i++) + loadcmd_data.push_back (lc_note_name[i]); + + // we start writing the payload at payload_file_offset to leave + // room at the start for the header & the load commands. + uint64_t current_payload_offset = payload.size() + payload_file_offset; + + add_uint64 (loadcmd_data, current_payload_offset); // note_command.offset + add_uint64 (loadcmd_data, 4 + ident.size() + 1); // note_command.size + + loadcmds.push_back (loadcmd_data); + + add_uint32 (payload, 1); // kerneL_version_string.version + for (int i = 0; i < ident.size() + 1; i++) + { + payload.push_back (ident[i]); + } +} + +void +add_lc_segment (std::vector<std::vector<uint8_t> > &loadcmds, + std::vector<uint8_t> &payload, + int payload_file_offset) +{ + std::vector<uint8_t> loadcmd_data; + struct segment_command_64 seg; + seg.cmd = LC_SEGMENT_64; + seg.cmdsize = sizeof (struct segment_command_64); // no sections + memset (seg.segname, 0, 16); + seg.vmaddr = 0xffffff7f96400000; + seg.vmsize = 4096; + seg.fileoff = payload.size() + payload_file_offset; + seg.filesize = 0; + seg.maxprot = 1; + seg.initprot = 1; + seg.nsects = 0; + seg.flags = 0; + + uint8_t *p = (uint8_t*) &seg; + for (int i = 0; i < sizeof (struct segment_command_64); i++) + { + loadcmd_data.push_back (*(p + i)); + } + loadcmds.push_back (loadcmd_data); +} + +std::string +get_uuid_from_binary (const char *fn) +{ + FILE *f = fopen(fn, "r"); + if (f == nullptr) + { + fprintf (stderr, "Unable to open binary '%s' to get uuid\n", fn); + exit(1); + } + uint32_t num_of_load_cmds = 0; + uint32_t size_of_load_cmds = 0; + std::string uuid; + off_t file_offset = 0; + + uint8_t magic[4]; + if (::fread (magic, 1, 4, f) != 4) + { + fprintf (stderr, "Failed to read magic number from input file %s\n", fn); + exit (1); + } + uint8_t magic_32_be[] = {0xfe, 0xed, 0xfa, 0xce}; + uint8_t magic_32_le[] = {0xce, 0xfa, 0xed, 0xfe}; + uint8_t magic_64_be[] = {0xfe, 0xed, 0xfa, 0xcf}; + uint8_t magic_64_le[] = {0xcf, 0xfa, 0xed, 0xfe}; + + if (memcmp (magic, magic_32_be, 4) == 0 || memcmp (magic, magic_64_be, 4) == 0) + { + fprintf (stderr, "big endian corefiles not supported\n"); + exit (1); + } + + ::fseeko (f, 0, SEEK_SET); + if (memcmp (magic, magic_32_le, 4) == 0) + { + struct mach_header mh; + if (::fread (&mh, 1, sizeof (mh), f) != sizeof (mh)) + { + fprintf (stderr, "error reading mach header from input file\n"); + exit (1); + } + if (mh.cputype != CPU_TYPE_X86_64) + { + fprintf (stderr, "This tool creates an x86_64 corefile but " + "the supplied binary '%s' is cputype 0x%x\n", + fn, (uint32_t) mh.cputype); + exit (1); + } + num_of_load_cmds = mh.ncmds; + size_of_load_cmds = mh.sizeofcmds; + file_offset += sizeof (struct mach_header); + } + else + { + struct mach_header_64 mh; + if (::fread (&mh, 1, sizeof (mh), f) != sizeof (mh)) + { + fprintf (stderr, "error reading mach header from input file\n"); + exit (1); + } + if (mh.cputype != CPU_TYPE_X86_64) + { + fprintf (stderr, "This tool creates an x86_64 corefile but " + "the supplied binary '%s' is cputype 0x%x\n", + fn, (uint32_t) mh.cputype); + exit (1); + } + num_of_load_cmds = mh.ncmds; + size_of_load_cmds = mh.sizeofcmds; + file_offset += sizeof (struct mach_header_64); + } + + off_t load_cmds_offset = file_offset; + + for (int i = 0; i < num_of_load_cmds && (file_offset - load_cmds_offset) < size_of_load_cmds; i++) + { + ::fseeko (f, file_offset, SEEK_SET); + uint32_t cmd; + uint32_t cmdsize; + ::fread (&cmd, sizeof (uint32_t), 1, f); + ::fread (&cmdsize, sizeof (uint32_t), 1, f); + if (cmd == LC_UUID) + { + struct uuid_command uuidcmd; + ::fseeko (f, file_offset, SEEK_SET); + if (::fread (&uuidcmd, 1, sizeof (uuidcmd), f) != sizeof (uuidcmd)) + { + fprintf (stderr, "Unable to read LC_UUID load command.\n"); + exit (1); + } + uuid_string_t uuidstr; + uuid_unparse (uuidcmd.uuid, uuidstr); + uuid = uuidstr; + break; + } + file_offset += cmdsize; + } + return uuid; +} + +int main (int argc, char **argv) +{ + if (argc != 2 && argc != 3) + { + fprintf (stderr, "usage: create-empty-corefile <output-core-name> [binary-to-copy-uuid-from]\n"); + fprintf (stderr, "Create a Mach-O corefile with an LC_NOTE 'kern ver str' load command/payload\n"); + fprintf (stderr, "If a binary is given as a second argument, the Mach-O UUID of that file will\n"); + fprintf (stderr, "be read and used in the corefile's LC_NOTE payload.\n"); + exit (1); + } + + std::string ident = "EFI UUID=3F9BA21F-55EA-356A-A349-BBA6F51FE8B1"; + if (argc == 3) + { + std::string uuid_from_file = get_uuid_from_binary (argv[2]); + if (!uuid_from_file.empty()) + { + ident = "EFI UUID="; + ident += uuid_from_file; + } + } + + // An array of load commands (in the form of byte arrays) + std::vector<std::vector<uint8_t> > load_commands; + + // An array of corefile contents (page data, lc_note data, etc) + std::vector<uint8_t> payload; + + // First add all the load commands / payload so we can figure out how large + // the load commands will actually be. + load_commands.push_back (x86_lc_thread_load_command()); + add_lc_note_kern_ver_str_load_command (load_commands, payload, 0, ident); + add_lc_segment (load_commands, payload, 0); + + int size_of_load_commands = 0; + for (const auto &lc : load_commands) + size_of_load_commands += lc.size(); + + int header_and_load_cmd_room = sizeof (struct mach_header_64) + size_of_load_commands; + + // Erease the load commands / payload now that we know how much space is needed, + // redo it. + load_commands.clear(); + payload.clear(); + + load_commands.push_back (x86_lc_thread_load_command()); + add_lc_note_kern_ver_str_load_command (load_commands, payload, header_and_load_cmd_room, ident); + add_lc_segment (load_commands, payload, header_and_load_cmd_room); + + struct mach_header_64 mh; + mh.magic = MH_MAGIC_64; + mh.cputype = CPU_TYPE_X86_64; + mh.cpusubtype = CPU_SUBTYPE_X86_64_ALL; + mh.filetype = MH_CORE; + mh.ncmds = load_commands.size(); + mh.sizeofcmds = size_of_load_commands; + mh.flags = 0; + mh.reserved = 0; + + + FILE *f = fopen (argv[1], "w"); + + if (f == nullptr) + { + fprintf (stderr, "Unable to open file %s for writing\n", argv[1]); + exit (1); + } + + fwrite (&mh, sizeof (struct mach_header_64), 1, f); + + for (const auto &lc : load_commands) + fwrite (lc.data(), lc.size(), 1, f); + + fseek (f, header_and_load_cmd_room, SEEK_SET); + + fwrite (payload.data(), payload.size(), 1, f); + + fclose (f); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/main.c new file mode 100644 index 00000000000..70a72e0b80b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/lc-note/kern-ver-str/main.c @@ -0,0 +1,2 @@ +#include <stdio.h> +int main () { puts ("this is the lc-note test program."); } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/load-kext/TestLoadKext.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/load-kext/TestLoadKext.py new file mode 100644 index 00000000000..ec35ce854d8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/load-kext/TestLoadKext.py @@ -0,0 +1,35 @@ +""" +Test loading of a kext binary. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LoadKextTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + #super(LoadKextTestCase, self).setUp() + #self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def test_load_kext(self): + """Test that lldb can load a kext binary.""" + + # Create kext from YAML. + self.yaml2obj("mykext.yaml", self.getBuildArtifact("mykext")) + + target = self.dbg.CreateTarget(self.getBuildArtifact("mykext")) + + self.assertTrue(target.IsValid()) + + self.assertEqual(target.GetNumModules(), 1) + mod = target.GetModuleAtIndex(0) + self.assertEqual(mod.GetFileSpec().GetFilename(), "mykext") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/load-kext/mykext.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/load-kext/mykext.yaml new file mode 100644 index 00000000000..ccf016304c8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/load-kext/mykext.yaml @@ -0,0 +1,222 @@ +--- !mach-o +FileHeader: + magic: 0xFEEDFACF + cputype: 0x01000007 + cpusubtype: 0x00000003 + filetype: 0x0000000B + ncmds: 7 + sizeofcmds: 520 + flags: 0x00000085 + reserved: 0x00000000 +LoadCommands: + - cmd: LC_SEGMENT_64 + cmdsize: 152 + segname: __TEXT + vmaddr: 0 + vmsize: 4096 + fileoff: 0 + filesize: 4096 + maxprot: 7 + initprot: 5 + nsects: 1 + flags: 0 + Sections: + - sectname: __text + segname: __TEXT + addr: 0x0000000000000F60 + size: 158 + offset: 0x00000F60 + align: 4 + reloff: 0x00000000 + nreloc: 0 + flags: 0x80000400 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - cmd: LC_SEGMENT_64 + cmdsize: 152 + segname: __DATA + vmaddr: 4096 + vmsize: 4096 + fileoff: 4096 + filesize: 4096 + maxprot: 7 + initprot: 3 + nsects: 1 + flags: 0 + Sections: + - sectname: __data + segname: __DATA + addr: 0x0000000000001000 + size: 220 + offset: 0x00001000 + align: 3 + reloff: 0x00000000 + nreloc: 0 + flags: 0x00000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: __LINKEDIT + vmaddr: 8192 + vmsize: 4096 + fileoff: 8192 + filesize: 800 + maxprot: 7 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_SYMTAB + cmdsize: 24 + symoff: 8224 + nsyms: 19 + stroff: 8528 + strsize: 464 + - cmd: LC_DYSYMTAB + cmdsize: 80 + ilocalsym: 0 + nlocalsym: 16 + iextdefsym: 16 + nextdefsym: 3 + iundefsym: 19 + nundefsym: 0 + tocoff: 0 + ntoc: 0 + modtaboff: 0 + nmodtab: 0 + extrefsymoff: 0 + nextrefsyms: 0 + indirectsymoff: 0 + nindirectsyms: 0 + extreloff: 0 + nextrel: 0 + locreloff: 8192 + nlocrel: 4 + - cmd: LC_UUID + cmdsize: 24 + uuid: 17A97B33-09B7-3195-9408-DBD965D578A5 + - cmd: LC_SOURCE_VERSION + cmdsize: 16 + version: 0 +LinkEditData: + NameList: + - n_strx: 40 + n_type: 0x64 + n_sect: 0 + n_desc: 0 + n_value: 0 + - n_strx: 141 + n_type: 0x64 + n_sect: 0 + n_desc: 0 + n_value: 0 + - n_strx: 155 + n_type: 0x66 + n_sect: 3 + n_desc: 1 + n_value: 1543540349 + - n_strx: 276 + n_type: 0x20 + n_sect: 0 + n_desc: 0 + n_value: 0 + - n_strx: 287 + n_type: 0x20 + n_sect: 0 + n_desc: 0 + n_value: 0 + - n_strx: 298 + n_type: 0x20 + n_sect: 0 + n_desc: 0 + n_value: 0 + - n_strx: 309 + n_type: 0x20 + n_sect: 0 + n_desc: 0 + n_value: 0 + - n_strx: 1 + n_type: 0x64 + n_sect: 1 + n_desc: 0 + n_value: 0 + - n_strx: 325 + n_type: 0x1E + n_sect: 1 + n_desc: 0 + n_value: 3992 + - n_strx: 333 + n_type: 0x1E + n_sect: 1 + n_desc: 0 + n_value: 4018 + - n_strx: 361 + n_type: 0x1E + n_sect: 1 + n_desc: 0 + n_value: 4035 + - n_strx: 392 + n_type: 0x1E + n_sect: 1 + n_desc: 0 + n_value: 4052 + - n_strx: 417 + n_type: 0x1E + n_sect: 1 + n_desc: 0 + n_value: 4068 + - n_strx: 424 + n_type: 0x1E + n_sect: 2 + n_desc: 0 + n_value: 4296 + - n_strx: 435 + n_type: 0x1E + n_sect: 2 + n_desc: 0 + n_value: 4304 + - n_strx: 446 + n_type: 0x1E + n_sect: 2 + n_desc: 0 + n_value: 4312 + - n_strx: 2 + n_type: 0x0F + n_sect: 2 + n_desc: 0 + n_value: 4096 + - n_strx: 13 + n_type: 0x0F + n_sect: 1 + n_desc: 0 + n_value: 3936 + - n_strx: 27 + n_type: 0x0F + n_sect: 1 + n_desc: 0 + n_value: 3968 + StringTable: + - ' ' + - _kmod_info + - _mykext_start + - _mykext_stop + - /tmp/mykext/build/mykext/Build/Intermediates.noindex/mykext.build/Debug/mykext.build/DerivedSources/ + - mykext_info.c + - /tmp/mykext/build/mykext/Build/Intermediates.noindex/mykext.build/Debug/mykext.build/Objects-normal/x86_64/mykext_info.o + - _kmod_info + - __realmain + - __antimain + - __kext_apple_cc + - __start + - _OSKextGetCurrentIdentifier + - _OSKextGetCurrentVersionString + - _OSKextGetCurrentLoadTag + - __stop + - __realmain + - __antimain + - __kext_apple_cc + - '' + - '' +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/Makefile new file mode 100644 index 00000000000..2123af1dd70 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/Makefile @@ -0,0 +1,13 @@ +C_SOURCES := main.c +LD_EXTRAS := -L. -lfoo + +TRIPLE := x86_64-apple-ios13.0-macabi +CFLAGS_EXTRAS := -target $(TRIPLE) + +all: libfoo.dylib a.out + +libfoo.dylib: foo.c + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_ONLY=YES DYLIB_NAME=foo DYLIB_C_SOURCES=foo.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/TestMacABImacOSFramework.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/TestMacABImacOSFramework.py new file mode 100644 index 00000000000..23b26772554 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/TestMacABImacOSFramework.py @@ -0,0 +1,28 @@ +# TestMacABImacOSFramework.py +import lldb +from lldbsuite.test.lldbtest import * +from lldbsuite.test.decorators import * +import lldbsuite.test.lldbutil as lldbutil +import os +import unittest2 + + +class TestMacABImacOSFramework(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIf(macos_version=["<", "10.15"]) + @skipUnlessDarwin + @skipIfDarwinEmbedded + # There is a Clang driver change missing on llvm.org. + @expectedFailureAll(bugnumber="rdar://problem/54986190>") + def test_macabi(self): + """Test the x86_64-apple-ios-macabi target linked against a macos dylib""" + self.build() + lldbutil.run_to_source_breakpoint(self, "break here", + lldb.SBFileSpec('main.c')) + self.expect("image list -t -b", + patterns=["x86_64.*-apple-ios.*-macabi a\.out", + "x86_64.*-apple-macosx.* libfoo.dylib[^(]"]) + self.expect("fr v s", "Hello MacABI") + self.expect("p s", "Hello MacABI") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/foo.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/foo.c new file mode 100644 index 00000000000..9c29d590f26 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/foo.c @@ -0,0 +1,8 @@ +#include "foo.h" + +void stop() {} + +int foo() { + stop(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/foo.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/foo.h new file mode 100644 index 00000000000..5d5f8f0c9e7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/foo.h @@ -0,0 +1 @@ +int foo(); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/main.c new file mode 100644 index 00000000000..92069d902fd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/macabi/main.c @@ -0,0 +1,5 @@ +#include "foo.h" +int main() { + const char *s = "Hello MacABI!"; + return foo(); // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/nslog/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/nslog/Makefile new file mode 100644 index 00000000000..a68dad547ec --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/nslog/Makefile @@ -0,0 +1,4 @@ +OBJC_SOURCES := main.m +LD_EXTRAS = -framework Foundation + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/nslog/TestDarwinNSLogOutput.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/nslog/TestDarwinNSLogOutput.py new file mode 100644 index 00000000000..2ab217d600b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/nslog/TestDarwinNSLogOutput.py @@ -0,0 +1,155 @@ +""" +Test DarwinLog "source include debug-level" functionality provided by the +StructuredDataDarwinLog plugin. + +These tests are currently only supported when running against Darwin +targets. +""" + + +import lldb +import platform +import re + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbtest_config + + +class DarwinNSLogOutputTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @skipIfRemote # this test is currently written using lldb commands & assumes running on local system + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.child = None + self.child_prompt = '(lldb) ' + self.strict_sources = False + + # Source filename. + self.source = 'main.m' + + # Output filename. + self.exe_name = self.getBuildArtifact("a.out") + self.d = {'OBJC_SOURCES': self.source, 'EXE': self.exe_name} + + # Locate breakpoint. + self.line = line_number(self.source, '// break here') + + def tearDown(self): + # Shut down the process if it's still running. + if self.child: + self.runCmd('process kill') + self.expect_prompt() + self.runCmd('quit') + + # Let parent clean up + super(DarwinNSLogOutputTestCase, self).tearDown() + + def run_lldb_to_breakpoint(self, exe, source_file, line, + settings_commands=None): + # Set self.child_prompt, which is "(lldb) ". + prompt = self.child_prompt + + # So that the child gets torn down after the test. + import pexpect + import sys + if sys.version_info.major == 3: + self.child = pexpect.spawnu('%s %s %s' % (lldbtest_config.lldbExec, + self.lldbOption, exe)) + else: + self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, + self.lldbOption, exe)) + child = self.child + + # Turn on logging for what the child sends back. + if self.TraceOn(): + child.logfile_read = sys.stdout + + # Disable showing of source lines at our breakpoint. + # This is necessary for the logging tests, because the very + # text we want to match for output from the running inferior + # will show up in the source as well. We don't want the source + # output to erroneously make a match with our expected output. + self.runCmd("settings set stop-line-count-before 0") + self.expect_prompt() + self.runCmd("settings set stop-line-count-after 0") + self.expect_prompt() + + # Run any test-specific settings commands now. + if settings_commands is not None: + for setting_command in settings_commands: + self.runCmd(setting_command) + self.expect_prompt() + + # Set the breakpoint, and run to it. + child.sendline('breakpoint set -f %s -l %d' % (source_file, line)) + child.expect_exact(prompt) + child.sendline('run') + child.expect_exact(prompt) + + # Ensure we stopped at a breakpoint. + self.runCmd("thread list") + self.expect(re.compile(r"stop reason = .*breakpoint")) + + def runCmd(self, cmd): + if self.child: + self.child.sendline(cmd) + + def expect_prompt(self, exactly=True): + self.expect(self.child_prompt, exactly=exactly) + + def expect(self, pattern, exactly=False, *args, **kwargs): + if exactly: + return self.child.expect_exact(pattern, *args, **kwargs) + return self.child.expect(pattern, *args, **kwargs) + + def do_test(self, expect_regexes=None, settings_commands=None): + """ Run a test. """ + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + + exe = self.getBuildArtifact(self.exe_name) + self.run_lldb_to_breakpoint(exe, self.source, self.line, + settings_commands=settings_commands) + self.expect_prompt() + + # Now go. + self.runCmd("process continue") + self.expect(expect_regexes) + + def test_nslog_output_is_displayed(self): + """Test that NSLog() output shows up in the command-line debugger.""" + self.do_test(expect_regexes=[ + re.compile(r"(This is a message from NSLog)"), + re.compile(r"Process \d+ exited with status") + ]) + self.assertIsNotNone(self.child.match) + self.assertGreater(len(self.child.match.groups()), 0) + self.assertEqual( + "This is a message from NSLog", + self.child.match.group(1)) + + def test_nslog_output_is_suppressed_with_env_var(self): + """Test that NSLog() output does not show up with the ignore env var.""" + # This test will only work properly on macOS 10.12+. Skip it on earlier versions. + # This will require some tweaking on iOS. + match = re.match(r"^\d+\.(\d+)", platform.mac_ver()[0]) + if match is None or int(match.group(1)) < 12: + self.skipTest("requires macOS 10.12 or higher") + + self.do_test( + expect_regexes=[ + re.compile(r"(This is a message from NSLog)"), + re.compile(r"Process \d+ exited with status") + ], + settings_commands=[ + "settings set target.env-vars " + "\"IDE_DISABLED_OS_ACTIVITY_DT_MODE=1\"" + ]) + self.assertIsNotNone(self.child.match) + self.assertEqual(len(self.child.match.groups()), 0) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/nslog/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/nslog/main.m new file mode 100644 index 00000000000..d48536496b8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/nslog/main.m @@ -0,0 +1,17 @@ +//===-- main.m --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <Foundation/Foundation.h> + +int main(int argc, char** argv) +{ + printf("About to log\n"); // break here + NSLog(@"This is a message from NSLog"); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/Makefile new file mode 100644 index 00000000000..ee67988d065 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/Makefile @@ -0,0 +1,5 @@ +C_SOURCES := main.c +LD_EXTRAS = -Xlinker -order_file -Xlinker $(SRCDIR)/order-file +MAKE_DSYM := NO + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py new file mode 100644 index 00000000000..778d06ddaca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py @@ -0,0 +1,36 @@ +""" +Test that debug symbols have the correct order as specified by the order file. +""" + + + +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class OrderFileTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + def test(self): + """Test debug symbols follow the correct order by the order file.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Test that the debug symbols have Function f3 before Function f1. + # Use "-s address" option to sort by address. + self.runCmd("image dump symtab -s address %s" % exe) + output = self.res.GetOutput() + mo_f3 = re.search("Code +.+f3", output) + mo_f1 = re.search("Code +.+f1", output) + + # Match objects for f3 and f1 must exist and f3 must come before f1. + self.assertTrue(mo_f3 and mo_f1 and mo_f3.start() < mo_f1.start(), + "Symbols have correct order by the order file") + + self.runCmd("run", RUN_COMPLETED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/cmds.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/cmds.txt new file mode 100644 index 00000000000..8c51dd763bf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/cmds.txt @@ -0,0 +1,3 @@ +b main.c:41 +c +lines -shlib a.out main.c diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/main.c new file mode 100644 index 00000000000..18ee77685c9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/main.c @@ -0,0 +1,53 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + + +int f1 (char *s); +int f2 (char *s); +int f3 (char *s); + + +// We want f1 to start on line 20 +int f1 (char *s) +{ + return printf("f1: %s\n", s); +} + + + + + +// We want f2 to start on line 30 +int f2 (char *s) +{ + return printf("f2: %s\n", s); +} + + + + + +// We want f3 to start on line 40 +int f3 (char *s) +{ + return printf("f3: %s\n", s); +} + + + + + +// We want main to start on line 50 +int main (int argc, const char * argv[]) +{ + f1("carp"); + f2("ding"); + f3("dong"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/order-file b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/order-file new file mode 100644 index 00000000000..0cf8ecd2a63 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/order/order-file @@ -0,0 +1,4 @@ +main.o:_f3 +main.o:_main +main.o:_f2 +main.o:_f1 diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/queues/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/queues/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/queues/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py new file mode 100644 index 00000000000..805ad21a413 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py @@ -0,0 +1,391 @@ +"""Test queues inspection SB APIs.""" + +from __future__ import print_function + + +import unittest2 +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestQueues(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_with_python_api_queues(self): + """Test queues inspection SB APIs.""" + self.build() + self.queues() + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_with_python_api_queues_with_backtrace(self): + """Test queues inspection SB APIs.""" + self.build() + self.queues_with_libBacktraceRecording() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers that we will step to in main: + self.main_source = "main.c" + + def check_queue_for_valid_queue_id(self, queue): + self.assertTrue( + queue.GetQueueID() != 0, "Check queue %s for valid QueueID (got 0x%x)" % + (queue.GetName(), queue.GetQueueID())) + + def check_running_and_pending_items_on_queue( + self, queue, expected_running, expected_pending): + self.assertTrue( + queue.GetNumPendingItems() == expected_pending, + "queue %s should have %d pending items, instead has %d pending items" % + (queue.GetName(), + expected_pending, + (queue.GetNumPendingItems()))) + self.assertTrue( + queue.GetNumRunningItems() == expected_running, + "queue %s should have %d running items, instead has %d running items" % + (queue.GetName(), + expected_running, + (queue.GetNumRunningItems()))) + + def describe_threads(self): + desc = [] + for x in self.inferior_process: + id = x.GetIndexID() + reason_str = lldbutil.stop_reason_to_str(x.GetStopReason()) + + location = "\t".join([lldbutil.get_description( + x.GetFrameAtIndex(i)) for i in range(x.GetNumFrames())]) + desc.append( + "thread %d: %s (queue id: %s) at\n\t%s" % + (id, reason_str, x.GetQueueID(), location)) + print('\n'.join(desc)) + + def check_number_of_threads_owned_by_queue(self, queue, number_threads): + if (queue.GetNumThreads() != number_threads): + self.describe_threads() + + self.assertTrue( + queue.GetNumThreads() == number_threads, + "queue %s should have %d thread executing, but has %d" % + (queue.GetName(), + number_threads, + queue.GetNumThreads())) + + def check_queue_kind(self, queue, kind): + expected_kind_string = "Unknown" + if kind == lldb.eQueueKindSerial: + expected_kind_string = "Serial queue" + if kind == lldb.eQueueKindConcurrent: + expected_kind_string = "Concurrent queue" + actual_kind_string = "Unknown" + if queue.GetKind() == lldb.eQueueKindSerial: + actual_kind_string = "Serial queue" + if queue.GetKind() == lldb.eQueueKindConcurrent: + actual_kind_string = "Concurrent queue" + self.assertTrue( + queue.GetKind() == kind, + "queue %s is expected to be a %s but it is actually a %s" % + (queue.GetName(), + expected_kind_string, + actual_kind_string)) + + def check_queues_threads_match_queue(self, queue): + for idx in range(0, queue.GetNumThreads()): + t = queue.GetThreadAtIndex(idx) + self.assertTrue( + t.IsValid(), "Queue %s's thread #%d must be valid" % + (queue.GetName(), idx)) + self.assertTrue( + t.GetQueueID() == queue.GetQueueID(), + "Queue %s has a QueueID of %d but its thread #%d has a QueueID of %d" % + (queue.GetName(), + queue.GetQueueID(), + idx, + t.GetQueueID())) + self.assertTrue( + t.GetQueueName() == queue.GetName(), + "Queue %s has a QueueName of %s but its thread #%d has a QueueName of %s" % + (queue.GetName(), + queue.GetName(), + idx, + t.GetQueueName())) + self.assertTrue( + t.GetQueue().GetQueueID() == queue.GetQueueID(), + "Thread #%d's Queue's QueueID of %d is not the same as the QueueID of its owning queue %d" % + (idx, + t.GetQueue().GetQueueID(), + queue.GetQueueID())) + + def queues(self): + """Test queues inspection SB APIs without libBacktraceRecording.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + self.main_source_spec = lldb.SBFileSpec(self.main_source) + break1 = target.BreakpointCreateByName("stopper", 'a.out') + self.assertTrue(break1, VALID_BREAKPOINT) + process = target.LaunchSimple( + [], None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) + if len(threads) != 1: + self.fail("Failed to stop at breakpoint 1.") + + self.inferior_process = process + + queue_submittor_1 = lldb.SBQueue() + queue_performer_1 = lldb.SBQueue() + queue_performer_2 = lldb.SBQueue() + queue_performer_3 = lldb.SBQueue() + for idx in range(0, process.GetNumQueues()): + q = process.GetQueueAtIndex(idx) + if q.GetName() == "com.apple.work_submittor_1": + queue_submittor_1 = q + if q.GetName() == "com.apple.work_performer_1": + queue_performer_1 = q + if q.GetName() == "com.apple.work_performer_2": + queue_performer_2 = q + if q.GetName() == "com.apple.work_performer_3": + queue_performer_3 = q + + self.assertTrue( + queue_submittor_1.IsValid() and queue_performer_1.IsValid() and queue_performer_2.IsValid() and queue_performer_3.IsValid(), + "Got all four expected queues: %s %s %s %s" % + (queue_submittor_1.IsValid(), + queue_performer_1.IsValid(), + queue_performer_2.IsValid(), + queue_performer_3.IsValid())) + + self.check_queue_for_valid_queue_id(queue_submittor_1) + self.check_queue_for_valid_queue_id(queue_performer_1) + self.check_queue_for_valid_queue_id(queue_performer_2) + self.check_queue_for_valid_queue_id(queue_performer_3) + + self.check_number_of_threads_owned_by_queue(queue_submittor_1, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_1, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_2, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_3, 4) + + self.check_queue_kind(queue_submittor_1, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_1, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_2, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_3, lldb.eQueueKindConcurrent) + + self.check_queues_threads_match_queue(queue_submittor_1) + self.check_queues_threads_match_queue(queue_performer_1) + self.check_queues_threads_match_queue(queue_performer_2) + self.check_queues_threads_match_queue(queue_performer_3) + + # We have threads running with all the different dispatch QoS service + # levels - find those threads and check that we can get the correct + # QoS name for each of them. + + user_initiated_thread = lldb.SBThread() + user_interactive_thread = lldb.SBThread() + utility_thread = lldb.SBThread() + unspecified_thread = lldb.SBThread() + background_thread = lldb.SBThread() + for th in process.threads: + if th.GetName() == "user initiated QoS": + user_initiated_thread = th + if th.GetName() == "user interactive QoS": + user_interactive_thread = th + if th.GetName() == "utility QoS": + utility_thread = th + if th.GetName() == "unspecified QoS": + unspecified_thread = th + if th.GetName() == "background QoS": + background_thread = th + + self.assertTrue( + user_initiated_thread.IsValid(), + "Found user initiated QoS thread") + self.assertTrue( + user_interactive_thread.IsValid(), + "Found user interactive QoS thread") + self.assertTrue(utility_thread.IsValid(), "Found utility QoS thread") + self.assertTrue( + unspecified_thread.IsValid(), + "Found unspecified QoS thread") + self.assertTrue( + background_thread.IsValid(), + "Found background QoS thread") + + stream = lldb.SBStream() + self.assertTrue( + user_initiated_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for user initiated QoS thread") + self.assertTrue( + stream.GetData() == "User Initiated", + "user initiated QoS thread name is valid") + stream.Clear() + self.assertTrue( + user_interactive_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for user interactive QoS thread") + self.assertTrue( + stream.GetData() == "User Interactive", + "user interactive QoS thread name is valid") + stream.Clear() + self.assertTrue( + utility_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for utility QoS thread") + self.assertTrue( + stream.GetData() == "Utility", + "utility QoS thread name is valid") + stream.Clear() + self.assertTrue( + unspecified_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for unspecified QoS thread") + qosName = stream.GetData() + self.assertTrue( + qosName == "User Initiated" or qosName == "Default", + "unspecified QoS thread name is valid") + stream.Clear() + self.assertTrue( + background_thread.GetInfoItemByPathAsString( + "requested_qos.printable_name", + stream), + "Get QoS printable string for background QoS thread") + self.assertTrue( + stream.GetData() == "Background", + "background QoS thread name is valid") + + @skipIfDarwin # rdar://50379398 + def queues_with_libBacktraceRecording(self): + """Test queues inspection SB APIs with libBacktraceRecording present.""" + exe = self.getBuildArtifact("a.out") + + if not os.path.isfile( + '/Applications/Xcode.app/Contents/Developer/usr/lib/libBacktraceRecording.dylib'): + self.skipTest( + "Skipped because libBacktraceRecording.dylib was present on the system.") + + if not os.path.isfile( + '/usr/lib/system/introspection/libdispatch.dylib'): + self.skipTest( + "Skipped because introspection libdispatch dylib is not present.") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + self.main_source_spec = lldb.SBFileSpec(self.main_source) + + break1 = target.BreakpointCreateByName("stopper", 'a.out') + self.assertTrue(break1, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + libbtr_path = "/Applications/Xcode.app/Contents/Developer/usr/lib/libBacktraceRecording.dylib" + if self.getArchitecture() in ['arm', 'arm64', 'arm64e', 'arm64_32', 'armv7', 'armv7k']: + libbtr_path = "/Developer/usr/lib/libBacktraceRecording.dylib" + + process = target.LaunchSimple( + [], + [ + 'DYLD_INSERT_LIBRARIES=%s' % (libbtr_path), + 'DYLD_LIBRARY_PATH=/usr/lib/system/introspection'], + self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # The stop reason of the thread should be breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) + if len(threads) != 1: + self.fail("Failed to stop at breakpoint 1.") + + self.inferior_process = process + + libbtr_module_filespec = lldb.SBFileSpec("libBacktraceRecording.dylib") + libbtr_module = target.FindModule(libbtr_module_filespec) + if not libbtr_module.IsValid(): + self.skipTest( + "Skipped because libBacktraceRecording.dylib was not loaded into the process.") + + self.assertTrue( + process.GetNumQueues() >= 4, + "Found the correct number of queues.") + + queue_submittor_1 = lldb.SBQueue() + queue_performer_1 = lldb.SBQueue() + queue_performer_2 = lldb.SBQueue() + queue_performer_3 = lldb.SBQueue() + for idx in range(0, process.GetNumQueues()): + q = process.GetQueueAtIndex(idx) + if "LLDB_COMMAND_TRACE" in os.environ: + print("Queue with id %s has name %s" % (q.GetQueueID(), q.GetName())) + if q.GetName() == "com.apple.work_submittor_1": + queue_submittor_1 = q + if q.GetName() == "com.apple.work_performer_1": + queue_performer_1 = q + if q.GetName() == "com.apple.work_performer_2": + queue_performer_2 = q + if q.GetName() == "com.apple.work_performer_3": + queue_performer_3 = q + if q.GetName() == "com.apple.main-thread": + if q.GetNumThreads() == 0: + print("Cannot get thread <=> queue associations") + return + + self.assertTrue( + queue_submittor_1.IsValid() and queue_performer_1.IsValid() and queue_performer_2.IsValid() and queue_performer_3.IsValid(), + "Got all four expected queues: %s %s %s %s" % + (queue_submittor_1.IsValid(), + queue_performer_1.IsValid(), + queue_performer_2.IsValid(), + queue_performer_3.IsValid())) + + self.check_queue_for_valid_queue_id(queue_submittor_1) + self.check_queue_for_valid_queue_id(queue_performer_1) + self.check_queue_for_valid_queue_id(queue_performer_2) + self.check_queue_for_valid_queue_id(queue_performer_3) + + self.check_running_and_pending_items_on_queue(queue_submittor_1, 1, 0) + self.check_running_and_pending_items_on_queue(queue_performer_1, 1, 3) + self.check_running_and_pending_items_on_queue( + queue_performer_2, 1, 9999) + self.check_running_and_pending_items_on_queue(queue_performer_3, 4, 0) + + self.check_number_of_threads_owned_by_queue(queue_submittor_1, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_1, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_2, 1) + self.check_number_of_threads_owned_by_queue(queue_performer_3, 4) + + self.check_queue_kind(queue_submittor_1, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_1, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_2, lldb.eQueueKindSerial) + self.check_queue_kind(queue_performer_3, lldb.eQueueKindConcurrent) + + self.check_queues_threads_match_queue(queue_submittor_1) + self.check_queues_threads_match_queue(queue_performer_1) + self.check_queues_threads_match_queue(queue_performer_2) + self.check_queues_threads_match_queue(queue_performer_3) + + self.assertTrue(queue_performer_2.GetPendingItemAtIndex( + 0).IsValid(), "queue 2's pending item #0 is valid") + self.assertTrue(queue_performer_2.GetPendingItemAtIndex(0).GetAddress().GetSymbol( + ).GetName() == "doing_the_work_2", "queue 2's pending item #0 should be doing_the_work_2") + self.assertTrue( + queue_performer_2.GetNumPendingItems() == 9999, + "verify that queue 2 still has 9999 pending items") + self.assertTrue(queue_performer_2.GetPendingItemAtIndex( + 9998).IsValid(), "queue 2's pending item #9998 is valid") + self.assertTrue(queue_performer_2.GetPendingItemAtIndex(9998).GetAddress().GetSymbol( + ).GetName() == "doing_the_work_2", "queue 2's pending item #0 should be doing_the_work_2") + self.assertTrue(queue_performer_2.GetPendingItemAtIndex( + 9999).IsValid() == False, "queue 2's pending item #9999 is invalid") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/queues/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/queues/main.c new file mode 100644 index 00000000000..3978b92bff1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/queues/main.c @@ -0,0 +1,151 @@ +#include <stdatomic.h> +#include <string.h> +#include <unistd.h> +#include <dispatch/dispatch.h> +#include <pthread.h> + +atomic_int finished_enqueueing_work = 0; +atomic_int thread_count = 0; + +void +doing_the_work_1(void *in) +{ + // This is only counted once because the first job in the queue + // starves all the others. + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (1); +} + +void +submit_work_1a(void *in) +{ + dispatch_queue_t *work_performer_1 = (dispatch_queue_t*) in; + dispatch_async_f (*work_performer_1, NULL, doing_the_work_1); + dispatch_async_f (*work_performer_1, NULL, doing_the_work_1); +} + +void +submit_work_1b(void *in) +{ + dispatch_queue_t *work_performer_1 = (dispatch_queue_t*) in; + dispatch_async_f (*work_performer_1, NULL, doing_the_work_1); + dispatch_async_f (*work_performer_1, NULL, doing_the_work_1); + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (1); +} + +void +doing_the_work_2(void *in) +{ + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (1); +} + +void +submit_work_2(void *in) +{ + dispatch_queue_t *work_performer_2 = (dispatch_queue_t*) in; + int i = 0; + while (i++ < 5000) + { + dispatch_async_f (*work_performer_2, NULL, doing_the_work_2); + dispatch_async_f (*work_performer_2, NULL, doing_the_work_2); + } + atomic_fetch_add(&finished_enqueueing_work, 1); +} + + +void +doing_the_work_3(void *in) +{ + // This counts four times, since the queue is marked as CONCURRENT. + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (1); +} + +void +submit_work_3(void *in) +{ + dispatch_queue_t *work_performer_3 = (dispatch_queue_t*) in; + dispatch_async_f (*work_performer_3, NULL, doing_the_work_3); + dispatch_async_f (*work_performer_3, NULL, doing_the_work_3); + dispatch_async_f (*work_performer_3, NULL, doing_the_work_3); + dispatch_async_f (*work_performer_3, NULL, doing_the_work_3); +} + + +void +stopper () +{ + while (1) + sleep (1); +} + + +int main (int argc, const char **argv) +{ + dispatch_queue_t work_submittor_1 = dispatch_queue_create ("com.apple.work_submittor_1", DISPATCH_QUEUE_SERIAL); + dispatch_queue_t work_submittor_2 = dispatch_queue_create ("com.apple.work_submittor_and_quit_2", DISPATCH_QUEUE_SERIAL); + dispatch_queue_t work_submittor_3 = dispatch_queue_create ("com.apple.work_submittor_3", DISPATCH_QUEUE_SERIAL); + + dispatch_queue_t work_performer_1 = dispatch_queue_create ("com.apple.work_performer_1", DISPATCH_QUEUE_SERIAL); + dispatch_queue_t work_performer_2 = dispatch_queue_create ("com.apple.work_performer_2", DISPATCH_QUEUE_SERIAL); + + dispatch_queue_t work_performer_3 = dispatch_queue_create ("com.apple.work_performer_3", DISPATCH_QUEUE_CONCURRENT); + + dispatch_async_f (work_submittor_1, (void*) &work_performer_1, submit_work_1a); + dispatch_async_f (work_submittor_1, (void*) &work_performer_1, submit_work_1b); + + dispatch_async_f (work_submittor_2, (void*) &work_performer_2, submit_work_2); + + dispatch_async_f (work_submittor_3, (void*) &work_performer_3, submit_work_3); + + + // Spin up threads with each of the different libdispatch QoS values. + dispatch_async (dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + pthread_setname_np ("user initiated QoS"); + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (10); + }); + dispatch_async (dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{ + pthread_setname_np ("user interactive QoS"); + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (10); + }); + dispatch_async (dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{ + pthread_setname_np ("default QoS"); + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (10); + }); + dispatch_async (dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ + pthread_setname_np ("utility QoS"); + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (10); + }); + dispatch_async (dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{ + pthread_setname_np ("background QoS"); + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (10); + }); + dispatch_async (dispatch_get_global_queue(QOS_CLASS_UNSPECIFIED, 0), ^{ + pthread_setname_np ("unspecified QoS"); + atomic_fetch_add(&thread_count, 1); + while (1) + sleep (10); + }); + + // Unfortunately there is no pthread_barrier on darwin. + while ((atomic_load(&thread_count) < 13) || (finished_enqueueing_work == 0)) + sleep (1); + + stopper (); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py new file mode 100644 index 00000000000..fe6d748e58e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py @@ -0,0 +1,70 @@ +"""Test function call thread safety.""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestSafeFuncCalls(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers that we will step to in main: + self.main_source = "main.c" + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test function call thread safety.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + self.main_source_spec = lldb.SBFileSpec(self.main_source) + break1 = target.BreakpointCreateByName("stopper", 'a.out') + self.assertTrue(break1, VALID_BREAKPOINT) + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + threads = lldbutil.get_threads_stopped_at_breakpoint(process, break1) + if len(threads) != 1: + self.fail("Failed to stop at breakpoint 1.") + + self.check_number_of_threads(process) + + main_thread = lldb.SBThread() + select_thread = lldb.SBThread() + for idx in range(0, process.GetNumThreads()): + t = process.GetThreadAtIndex(idx) + if t.GetName() == "main thread": + main_thread = t + if t.GetName() == "select thread": + select_thread = t + + self.assertTrue( + main_thread.IsValid() and select_thread.IsValid(), + "Got both expected threads") + + self.safe_to_call_func_on_main_thread(main_thread) + self.safe_to_call_func_on_select_thread(select_thread) + + def check_number_of_threads(self, process): + self.assertTrue( + process.GetNumThreads() == 2, + "Check that the process has two threads when sitting at the stopper() breakpoint") + + def safe_to_call_func_on_main_thread(self, main_thread): + self.assertTrue(main_thread.SafeToCallFunctions(), + "It is safe to call functions on the main thread") + + def safe_to_call_func_on_select_thread(self, select_thread): + self.assertTrue( + select_thread.SafeToCallFunctions() == False, + "It is not safe to call functions on the select thread") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/main.c new file mode 100644 index 00000000000..58650087628 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/safe-to-func-call/main.c @@ -0,0 +1,31 @@ +#include <sys/time.h> // work around module map issue with iOS sdk, <rdar://problem/35159346> +#include <sys/select.h> +#include <stdio.h> +#include <pthread.h> +#include <unistd.h> + +void * +select_thread (void *in) +{ + pthread_setname_np ("select thread"); + fd_set fdset; + FD_SET (STDIN_FILENO, &fdset); + while (1) + select (2, &fdset, NULL, NULL, NULL); + return NULL; +} + +void stopper () +{ + while (1) + sleep(1); // break here +} + +int main () +{ + pthread_setname_np ("main thread"); + pthread_t other_thread; + pthread_create (&other_thread, NULL, select_thread, NULL); + sleep (1); + stopper(); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/thread-names/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/thread-names/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/thread-names/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/thread-names/TestInterruptThreadNames.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/thread-names/TestInterruptThreadNames.py new file mode 100644 index 00000000000..2a2768195d4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/thread-names/TestInterruptThreadNames.py @@ -0,0 +1,133 @@ +"""Test that we get thread names when interrupting a process.""" + + +import time +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestInterruptThreadNames(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test_with_python_api(self): + """Test that we get thread names when interrupting a process.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + launch_info = lldb.SBLaunchInfo(None) + error = lldb.SBError() + self.dbg.SetAsync(True) + process = target.Launch(launch_info, error) + self.assertTrue(process, PROCESS_IS_VALID) + + listener = self.dbg.GetListener() + broadcaster = process.GetBroadcaster() + rc = broadcaster.AddListener(listener, lldb.SBProcess.eBroadcastBitStateChanged) + self.assertTrue(rc != 0, "Unable to add listener to process") + self.assertTrue(self.wait_for_running(process, listener), "Check that process is up and running") + + inferior_set_up = self.wait_until_program_setup_complete(process, listener) + + self.assertTrue(inferior_set_up.IsValid() and inferior_set_up.GetValueAsSigned() == 1, "Check that the program was able to create its threads within the allotted time") + + self.check_number_of_threads(process) + + main_thread = lldb.SBThread() + second_thread = lldb.SBThread() + third_thread = lldb.SBThread() + for idx in range(0, process.GetNumThreads()): + t = process.GetThreadAtIndex(idx) + if t.GetName() == "main thread": + main_thread = t + if t.GetName() == "second thread": + second_thread = t + if t.GetName() == "third thread": + third_thread = t + + self.check_expected_threads_present(main_thread, second_thread, third_thread) + + process.Kill() + + + # The process will set a global variable 'threads_up_and_running' to 1 when + # it has has completed its setup. Sleep for one second, pause the program, + # check to see if the global has that value, and continue if it does not. + def wait_until_program_setup_complete(self, process, listener): + inferior_set_up = lldb.SBValue() + retry = 5 + while retry > 0: + arch = self.getArchitecture() + # when running the testsuite against a remote arm device, it may take + # a little longer for the process to start up. Use a "can't possibly take + # longer than this" value. + if arch == 'arm64' or arch == 'armv7': + time.sleep(10) + else: + time.sleep(1) + process.SendAsyncInterrupt() + self.assertTrue(self.wait_for_stop(process, listener), "Check that process is paused") + inferior_set_up = process.GetTarget().CreateValueFromExpression("threads_up_and_running", "threads_up_and_running") + if inferior_set_up.IsValid() and inferior_set_up.GetValueAsSigned() == 1: + retry = 0 + else: + process.Continue() + retry = retry - 1 + return inferior_set_up + + # Listen to the process events until we get an event saying that the process is + # running. Retry up to five times in case we get other events that are not + # what we're looking for. + def wait_for_running(self, process, listener): + retry_count = 5 + if process.GetState() == lldb.eStateRunning: + return True + + while retry_count > 0: + event = lldb.SBEvent() + listener.WaitForEvent(2, event) + if event.GetType() == lldb.SBProcess.eBroadcastBitStateChanged: + if process.GetState() == lldb.eStateRunning: + return True + retry_count = retry_count - 1 + + return False + + # Listen to the process events until we get an event saying the process is + # stopped. Retry up to five times in case we get other events that we are + # not looking for. + def wait_for_stop(self, process, listener): + retry_count = 5 + if process.GetState() == lldb.eStateStopped or process.GetState() == lldb.eStateCrashed or process.GetState() == lldb.eStateDetached or process.GetState() == lldb.eStateExited: + return True + + while retry_count > 0: + event = lldb.SBEvent() + listener.WaitForEvent(2, event) + if event.GetType() == lldb.SBProcess.eBroadcastBitStateChanged: + if process.GetState() == lldb.eStateStopped or process.GetState() == lldb.eStateCrashed or process.GetState() == lldb.eStateDetached or process.GetState() == lldb.eStateExited: + return True + if process.GetState() == lldb.eStateCrashed or process.GetState() == lldb.eStateDetached or process.GetState() == lldb.eStateExited: + return False + retry_count = retry_count - 1 + + return False + + + + def check_number_of_threads(self, process): + self.assertTrue( + process.GetNumThreads() == 3, + "Check that the process has three threads when sitting at the stopper() breakpoint") + + def check_expected_threads_present(self, main_thread, second_thread, third_thread): + self.assertTrue( + main_thread.IsValid() and second_thread.IsValid() and third_thread.IsValid(), + "Got all three expected threads") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/thread-names/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/thread-names/main.c new file mode 100644 index 00000000000..6834f064151 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/thread-names/main.c @@ -0,0 +1,36 @@ +#include <stdio.h> +#include <pthread.h> +#include <unistd.h> + +int threads_up_and_running = 0; + +void * +second_thread (void *in) +{ + pthread_setname_np ("second thread"); + while (1) + sleep (1); + return NULL; +} + +void * +third_thread (void *in) +{ + pthread_setname_np ("third thread"); + while (1) + sleep (1); + return NULL; +} + +int main () +{ + pthread_setname_np ("main thread"); + pthread_t other_thread; + pthread_create (&other_thread, NULL, second_thread, NULL); + pthread_create (&other_thread, NULL, third_thread, NULL); + + threads_up_and_running = 1; + + while (1) + sleep (1); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/universal/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/universal/Makefile new file mode 100644 index 00000000000..efdeb1fd131 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/universal/Makefile @@ -0,0 +1,23 @@ +EXE := testit + +include Makefile.rules + +all: testit + +testit: testit.x86_64h testit.x86_64 + lipo -create -o testit $^ + +testit.x86_64h: testit.x86_64h.o + $(CC) -arch x86_64h -o testit.x86_64h $< + +testit.x86_64: testit.x86_64.o + $(CC) -arch x86_64 -o testit.x86_64 $< + +testit.x86_64h.o: main.c + $(CC) -g -O0 -arch x86_64h -c -o testit.x86_64h.o $< + +testit.x86_64.o: main.c + $(CC) -g -O0 -arch x86_64 -c -o testit.x86_64.o $< + +clean:: + rm -rf $(wildcard testit* *~) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py new file mode 100644 index 00000000000..ebcdee84f64 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py @@ -0,0 +1,162 @@ +"""Test aspects of lldb commands on universal binaries.""" + + + +import unittest2 +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +def haswellOrLater(): + features = subprocess.check_output(["sysctl", "machdep.cpu"]) + return "AVX2" in features.split() + +class UniversalTestCase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # 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.') + + @add_test_categories(['pyapi']) + @skipUnlessDarwin + @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in + ['x86_64'], "requires x86_64") + @skipIfDarwinEmbedded # this test file assumes we're targetting an x86 system + def test_sbdebugger_create_target_with_file_and_target_triple(self): + """Test the SBDebugger.CreateTargetWithFileAndTargetTriple() API.""" + # Invoke the default build rule. + self.build() + + # Note that "testit" is a universal binary. + exe = self.getBuildArtifact("testit") + + # Create a target by the debugger. + target = self.dbg.CreateTargetWithFileAndTargetTriple( + exe, "x86_64-apple-macosx") + self.assertTrue(target, VALID_TARGET) + self.expect("image list -A -b", substrs=["x86_64 testit"]) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + @skipUnlessDarwin + @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in + ['x86_64'], "requires x86_64") + @skipIfDarwinEmbedded # this test file assumes we're targetting an x86 system + def test_process_launch_for_universal(self): + """Test process launch of a universal binary.""" + from lldbsuite.test.lldbutil import print_registers + + if not haswellOrLater(): + return + + # Invoke the default build rule. + self.build() + + # Note that "testit" is a universal binary. + exe = self.getBuildArtifact("testit") + + # By default, x86_64 is assumed if no architecture is specified. + self.expect("file " + exe, CURRENT_EXECUTABLE_SET, + startstr="Current executable set to ", + substrs=["testit' (x86_64h)."]) + + # Break inside the main. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + + # We should be able to launch the x86_64h executable. + self.runCmd("run", RUN_SUCCEEDED) + + # Check whether we have a x86_64h process launched. + target = self.dbg.GetSelectedTarget() + process = target.GetProcess() + self.expect("image list -A -b", substrs=["x86_64h testit"]) + self.runCmd("continue") + + # Now specify x86_64 as the architecture for "testit". + self.expect("file -a x86_64 " + exe, CURRENT_EXECUTABLE_SET, + startstr="Current executable set to ", + substrs=["testit' (x86_64)."]) + + # Break inside the main. + lldbutil.run_break_set_by_file_and_line( + self, "main.c", self.line, num_expected_locations=1, loc_exact=True) + + # We should be able to launch the x86_64 executable as well. + self.runCmd("run", RUN_SUCCEEDED) + + # Check whether we have a x86_64 process launched. + + # FIXME: This wrong. We are expecting x86_64, but spawning a + # new process currently doesn't allow specifying a *sub*-architecture. + # <rdar://problem/46101466> + self.expect("image list -A -b", substrs=["x86_64h testit"]) + self.runCmd("continue") + + @skipUnlessDarwin + @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in + ['x86_64'], "requires x86_64") + @skipIfDarwinEmbedded # this test file assumes we're targetting an x86 system + def test_process_attach_with_wrong_arch(self): + """Test that when we attach to a binary from the wrong fork of + a universal binary, we fix up the ABI correctly.""" + if not haswellOrLater(): + return + + # Now keep the architecture at x86_64, but switch the binary + # we launch to x86_64h, and make sure on attach we switch to + # the correct architecture. + + # Invoke the default build rule. + self.build() + + # Note that "testit" is a universal binary. + exe = self.getBuildArtifact("testit") + + # Create a target by the debugger. + target = self.dbg.CreateTargetWithFileAndTargetTriple( + exe, "x86_64-apple-macosx") + self.assertTrue(target, VALID_TARGET) + self.expect("image list -A -b", substrs=["x86_64 testit"]) + + bkpt = target.BreakpointCreateBySourceRegex( + "sleep", lldb.SBFileSpec("main.c")) + self.assertTrue(bkpt.IsValid(), "Valid breakpoint") + self.assertTrue( + bkpt.GetNumLocations() >= 1, + "Our main breakpoint has locations.") + + popen = self.spawnSubprocess(exe, ["keep_waiting"]) + self.addTearDownHook(self.cleanupSubprocesses) + + error = lldb.SBError() + empty_listener = lldb.SBListener() + process = target.AttachToProcessWithID( + empty_listener, popen.pid, error) + self.assertTrue(error.Success(), "Attached to process.") + + self.expect("image list -A -b", substrs=["x86_64h testit"]) + + # It may seem odd to check the number of frames, but the bug + # that motivated this test was that we eventually fixed the + # architecture, but we left the ABI set to the original value. + # In that case, if you asked the process for its architecture, + # it would look right, but since the ABI was wrong, + # backtracing failed. + + threads = lldbutil.continue_to_breakpoint(process, bkpt) + self.assertTrue(len(threads) == 1) + thread = threads[0] + self.assertTrue( + thread.GetNumFrames() > 1, + "We were able to backtrace.") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/universal/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/universal/main.c new file mode 100644 index 00000000000..3edab51b1f6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/universal/main.c @@ -0,0 +1,21 @@ +#include <stdio.h> +#include <unistd.h> +#include <string.h> + +void +call_me() +{ + sleep(1); +} + +int +main (int argc, char **argv) +{ + printf ("Hello there!\n"); // Set break point at this line. + if (argc == 2 && strcmp(argv[1], "keep_waiting") == 0) + while (1) + { + call_me(); + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/version_zero/TestGetVersionZeroVersion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/version_zero/TestGetVersionZeroVersion.py new file mode 100644 index 00000000000..f7e4da73dda --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/version_zero/TestGetVersionZeroVersion.py @@ -0,0 +1,39 @@ +""" +Read in a library with a version number of 0.0.0, make sure we produce a good version. +""" + + + +import lldb +from lldbsuite.test import decorators +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class TestGetVersionForZero(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def test_get_version_zero(self): + """Read in a library with a version of 0.0.0. Test SBModule::GetVersion""" + self.yaml2obj("libDylib.dylib.yaml", self.getBuildArtifact("libDylib.dylib")) + self.do_test() + + def do_test(self): + lib_name = "libDylib.dylib" + target = lldbutil.run_to_breakpoint_make_target(self, exe_name=lib_name) + module = target.FindModule(lldb.SBFileSpec(lib_name)) + self.assertTrue(module.IsValid(), "Didn't find the libDylib.dylib module") + # For now the actual version numbers are wrong for a library of 0.0.0 + # but the previous code would crash iterating over the resultant + # list. So we are testing that that doesn't happen. + did_iterate = False + for elem in module.GetVersion(): + did_iterate = True + self.assertTrue(did_iterate, "Didn't get into the GetVersion loop") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/version_zero/libDylib.dylib.yaml b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/version_zero/libDylib.dylib.yaml new file mode 100644 index 00000000000..a672f49fb4a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/macosx/version_zero/libDylib.dylib.yaml @@ -0,0 +1,220 @@ +--- !mach-o +FileHeader: + magic: 0xFEEDFACF + cputype: 0x01000007 + cpusubtype: 0x00000003 + filetype: 0x00000006 + ncmds: 12 + sizeofcmds: 672 + flags: 0x00100085 + reserved: 0x00000000 +LoadCommands: + - cmd: LC_SEGMENT_64 + cmdsize: 232 + segname: __TEXT + vmaddr: 0 + vmsize: 4096 + fileoff: 0 + filesize: 4096 + maxprot: 5 + initprot: 5 + nsects: 2 + flags: 0 + Sections: + - sectname: __text + segname: __TEXT + addr: 0x0000000000000FA0 + size: 11 + offset: 0x00000FA0 + align: 4 + reloff: 0x00000000 + nreloc: 0 + flags: 0x80000400 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - sectname: __unwind_info + segname: __TEXT + addr: 0x0000000000000FAC + size: 72 + offset: 0x00000FAC + align: 2 + reloff: 0x00000000 + nreloc: 0 + flags: 0x00000000 + reserved1: 0x00000000 + reserved2: 0x00000000 + reserved3: 0x00000000 + - cmd: LC_SEGMENT_64 + cmdsize: 72 + segname: __LINKEDIT + vmaddr: 4096 + vmsize: 4096 + fileoff: 4096 + filesize: 528 + maxprot: 1 + initprot: 1 + nsects: 0 + flags: 0 + - cmd: LC_ID_DYLIB + cmdsize: 56 + dylib: + name: 24 + timestamp: 1 + current_version: 0 + compatibility_version: 0 + PayloadString: '@executable_path/libDylib.dylib' + ZeroPadBytes: 1 + - cmd: LC_DYLD_INFO_ONLY + cmdsize: 48 + rebase_off: 0 + rebase_size: 0 + bind_off: 0 + bind_size: 0 + weak_bind_off: 0 + weak_bind_size: 0 + lazy_bind_off: 0 + lazy_bind_size: 0 + export_off: 4096 + export_size: 16 + - cmd: LC_SYMTAB + cmdsize: 24 + symoff: 4120 + nsyms: 10 + stroff: 4280 + strsize: 344 + - cmd: LC_DYSYMTAB + cmdsize: 80 + ilocalsym: 0 + nlocalsym: 8 + iextdefsym: 8 + nextdefsym: 1 + iundefsym: 9 + nundefsym: 1 + tocoff: 0 + ntoc: 0 + modtaboff: 0 + nmodtab: 0 + extrefsymoff: 0 + nextrefsyms: 0 + indirectsymoff: 0 + nindirectsyms: 0 + extreloff: 0 + nextrel: 0 + locreloff: 0 + nlocrel: 0 + - cmd: LC_UUID + cmdsize: 24 + uuid: 5F76D8E3-7EA5-3092-8A9D-0D0E36429550 + - cmd: LC_BUILD_VERSION + cmdsize: 32 + platform: 1 + minos: 659200 + sdk: 659200 + ntools: 1 + Tools: + - tool: 3 + version: 33227776 + - cmd: LC_SOURCE_VERSION + cmdsize: 16 + version: 0 + - cmd: LC_LOAD_DYLIB + cmdsize: 56 + dylib: + name: 24 + timestamp: 2 + current_version: 83427328 + compatibility_version: 65536 + PayloadString: '/usr/lib/libSystem.B.dylib' + ZeroPadBytes: 6 + - cmd: LC_FUNCTION_STARTS + cmdsize: 16 + dataoff: 4112 + datasize: 8 + - cmd: LC_DATA_IN_CODE + cmdsize: 16 + dataoff: 4120 + datasize: 0 +LinkEditData: + ExportTrie: + TerminalSize: 0 + NodeOffset: 0 + Name: '' + Flags: 0x0000000000000000 + Address: 0x0000000000000000 + Other: 0x0000000000000000 + ImportName: '' + Children: + - TerminalSize: 3 + NodeOffset: 9 + Name: _func + Flags: 0x0000000000000000 + Address: 0x0000000000000FA0 + Other: 0x0000000000000000 + ImportName: '' + NameList: + - n_strx: 25 + n_type: 0x64 + n_sect: 0 + n_desc: 0 + n_value: 0 + - n_strx: 148 + n_type: 0x64 + n_sect: 0 + n_desc: 0 + n_value: 0 + - n_strx: 156 + n_type: 0x66 + n_sect: 3 + n_desc: 1 + n_value: 1553735575 + - n_strx: 1 + n_type: 0x2E + n_sect: 1 + n_desc: 0 + n_value: 4000 + - n_strx: 332 + n_type: 0x24 + n_sect: 1 + n_desc: 0 + n_value: 4000 + - n_strx: 1 + n_type: 0x24 + n_sect: 0 + n_desc: 0 + n_value: 11 + - n_strx: 1 + n_type: 0x4E + n_sect: 1 + n_desc: 0 + n_value: 11 + - n_strx: 1 + n_type: 0x64 + n_sect: 1 + n_desc: 0 + n_value: 0 + - n_strx: 2 + n_type: 0x0F + n_sect: 1 + n_desc: 0 + n_value: 4000 + - n_strx: 8 + n_type: 0x01 + n_sect: 0 + n_desc: 256 + n_value: 0 + StringTable: + - ' ' + - _func + - dyld_stub_binder + - '/Volumes/ThePlayground/Users/jingham/Work/LLDB/llvm-dot-org/lldb-clean/packages/Python/lldbsuite/test/macosx/version_zero/' + - dylib.c + - '/Volumes/ThePlayground/Users/jingham/Work/LLDB/llvm-dot-org/lldb-clean/test/lldb-test-build.noindex/macosx/version_zero/TestGetVersionZeroVersion.test_get_version_zero/dylib.o' + - _func + - '' + - '' + - '' + - '' + - '' + - '' +... diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/Android.rules b/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/Android.rules new file mode 100644 index 00000000000..7339c22d2e4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/Android.rules @@ -0,0 +1,89 @@ +NDK_ROOT := $(shell dirname $(CC))/../../../../.. + +ifeq "$(findstring 64, $(ARCH))" "64" + # lowest 64-bit API level + API_LEVEL := 21 +else ifeq "$(ARCH)" "i386" + # clone(2) declaration is present only since this api level + API_LEVEL := 17 +else + # lowest supported 32-bit API level + API_LEVEL := 16 +endif + +ifeq "$(ARCH)" "arm" + SYSROOT_ARCH := arm + STL_ARCH := armeabi-v7a + TRIPLE := armv7-none-linux-androideabi + ARCH_CFLAGS += -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -marm +else ifeq "$(ARCH)" "aarch64" + SYSROOT_ARCH := arm64 + STL_ARCH := arm64-v8a + TRIPLE := aarch64-none-linux-android +else ifeq "$(ARCH)" "i386" + SYSROOT_ARCH := x86 + STL_ARCH := x86 + TRIPLE := i686-none-linux-android +else ifeq "$(ARCH)" "mips64r6" + SYSROOT_ARCH := mips64 + STL_ARCH := mips64 + TRIPLE := mips64el-none-linux-android +else ifeq "$(ARCH)" "mips32" + SYSROOT_ARCH := mips + STL_ARCH := mips + TRIPLE := mipsel-none-linux-android +else + SYSROOT_ARCH := $(ARCH) + STL_ARCH := $(ARCH) + TRIPLE := $(ARCH)-none-linux-android +endif + +ifeq "$(findstring 86,$(ARCH))" "86" + TOOLCHAIN_DIR := $(STL_ARCH)-4.9 +else ifeq "$(ARCH)" "arm" + TOOLCHAIN_DIR := arm-linux-androideabi-4.9 +else + TOOLCHAIN_DIR := $(subst -none,,$(TRIPLE))-4.9 +endif + +ifeq "$(ARCH)" "arm" + TOOL_PREFIX := arm-linux-androideabi +else + TOOL_PREFIX := $(subst -none,,$(TRIPLE)) +endif + +ifeq "$(HOST_OS)" "Linux" + HOST_TAG := linux-x86_64 +else ifeq "$(HOST_OS)" "Darwin" + HOST_TAG := darwin-x86_64 +else + HOST_TAG := windows-x86_64 +endif + +GCC_TOOLCHAIN = $(NDK_ROOT)/toolchains/$(TOOLCHAIN_DIR)/prebuilt/$(HOST_TAG) + +OBJCOPY ?= $(GCC_TOOLCHAIN)/bin/$(TOOL_PREFIX)-objcopy +ARCHIVER ?= $(GCC_TOOLCHAIN)/bin/$(TOOL_PREFIX)-ar + +ifeq "$(findstring clang,$(CC))" "clang" + ARCH_CFLAGS += -target $(TRIPLE) -gcc-toolchain $(GCC_TOOLCHAIN) + ARCH_LDFLAGS += -target $(TRIPLE) -gcc-toolchain $(GCC_TOOLCHAIN) +endif + +ARCH_CFLAGS += --sysroot=$(NDK_ROOT)/sysroot \ + -isystem $(NDK_ROOT)/sysroot/usr/include/$(TOOL_PREFIX) \ + -D__ANDROID_API__=$(API_LEVEL) \ + -isystem $(NDK_ROOT)/platforms/android-$(API_LEVEL)/arch-$(SYSROOT_ARCH)/usr/include + +ARCH_LDFLAGS += --sysroot=$(NDK_ROOT)/platforms/android-$(API_LEVEL)/arch-$(SYSROOT_ARCH) -lm + +ARCH_CXXFLAGS += \ + -isystem $(NDK_ROOT)/sources/cxx-stl/llvm-libc++/include \ + -isystem $(NDK_ROOT)/sources/android/support/include \ + -isystem $(NDK_ROOT)/sources/cxx-stl/llvm-libc++abi/include + +ARCH_LDFLAGS += \ + -L$(NDK_ROOT)/sources/cxx-stl/llvm-libc++/libs/$(STL_ARCH) \ + $(NDK_ROOT)/sources/cxx-stl/llvm-libc++/libs/$(STL_ARCH)/libc++_static.a \ + -lc++abi \ + -nostdlib++ diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/Makefile.rules b/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/Makefile.rules new file mode 100644 index 00000000000..f25d062ca43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/Makefile.rules @@ -0,0 +1,782 @@ +#---------------------------------------------------------------------- +# Clients fill in the source files to build +#---------------------------------------------------------------------- +# C_SOURCES := main.c +# CXX_SOURCES := +# OBJC_SOURCES := +# OBJCXX_SOURCES := +# DYLIB_C_SOURCES := +# DYLIB_OBJC_SOURCES := +# DYLIB_CXX_SOURCES := +# +# Specifying DYLIB_ONLY has the effect of building dylib only, skipping +# the building of the a.out executable program. For example, +# DYLIB_ONLY := YES +# +# Specifying FRAMEWORK and its variants has the effect of building a NeXT-style +# framework. +# FRAMEWORK := "Foo" +# FRAMEWORK_HEADERS := "Foo.h" +# FRAMEWORK_MODULES := "module.modulemap" +# +# Also might be of interest: +# FRAMEWORK_INCLUDES (Darwin only) := +# CFLAGS_EXTRAS := +# LD_EXTRAS := +# SPLIT_DEBUG_SYMBOLS := YES +# CROSS_COMPILE := +# USE_PRIVATE_MODULE_CACHE := YES +# +# And test/functionalities/archives/Makefile: +# MAKE_DSYM := NO +# ARCHIVE_NAME := libfoo.a +# ARCHIVE_C_SOURCES := a.c b.c + +# Uncomment line below for debugging shell commands +# SHELL = /bin/sh -x + +SRCDIR := $(shell dirname $(firstword $(MAKEFILE_LIST))) +BUILDDIR := $(shell pwd) +MAKEFILE_RULES := $(lastword $(MAKEFILE_LIST)) +THIS_FILE_DIR := $(shell dirname $(MAKEFILE_RULES)) +LLDB_BASE_DIR := $(THIS_FILE_DIR)/../../../../../ + +#---------------------------------------------------------------------- +# If OS is not defined, use 'uname -s' to determine the OS name. +# +# uname on Windows gives "windows32" or "server version windows32", but most +# environments standardize on "Windows_NT", so we'll make it consistent here. +# When running tests from Visual Studio, the environment variable isn't +# inherited all the way down to the process spawned for make. +#---------------------------------------------------------------------- +HOST_OS = $(shell uname -s) +ifneq (,$(findstring windows32,$(HOST_OS))) + HOST_OS = Windows_NT +endif +ifeq "$(OS)" "" + OS = $(HOST_OS) +endif + +#---------------------------------------------------------------------- +# If OS is Windows, force SHELL to be cmd +# +# Some versions of make on Windows will search for other shells such as +# C:\cygwin\bin\sh.exe. This shell fails for numerous different reasons +# so default to using cmd.exe. +#---------------------------------------------------------------------- +ifeq "$(OS)" "Windows_NT" + SHELL = $(WINDIR)\system32\cmd.exe +endif + +#---------------------------------------------------------------------- +# If the OS is Windows use double-quotes in commands +# +# For other operating systems, single-quotes work fine, but on Windows +# we strictly required double-quotes +#---------------------------------------------------------------------- +ifeq "$(HOST_OS)" "Windows_NT" + JOIN_CMD = & + QUOTE = " + FIXUP_SYNTAX_HIGHLIGHTING_IN_MY_EDITOR = " +else + JOIN_CMD = ; + QUOTE = ' + FIXUP_SYNTAX_HIGHLIGHTING_IN_MY_EDITOR = ' +endif + +#---------------------------------------------------------------------- +# If TRIPLE is not defined try to set the ARCH, CC, CFLAGS, and more +# from the triple alone +#---------------------------------------------------------------------- +ARCH_CFLAGS := +ifneq "$(TRIPLE)" "" + triple_space = $(subst -, ,$(TRIPLE)) + ARCH =$(word 1, $(triple_space)) + TRIPLE_VENDOR =$(word 2, $(triple_space)) + triple_os_and_version =$(shell echo $(word 3, $(triple_space)) | sed 's/\([a-z]*\)\(.*\)/\1 \2/') + TRIPLE_OS =$(word 1, $(triple_os_and_version)) + TRIPLE_VERSION =$(word 2, $(triple_os_and_version)) + TRIPLE_ENV =$(word 4, $(triple_space)) + ifeq "$(TRIPLE_VENDOR)" "apple" + ifeq "$(TRIPLE_OS)" "ios" + CODESIGN := codesign + ifeq "$(SDKROOT)" "" + # Set SDKROOT if it wasn't set + ifneq (,$(findstring arm,$(ARCH))) + SDKROOT = $(shell xcrun --sdk iphoneos --show-sdk-path) + ifeq "$(TRIPLE_VERSION)" "" + TRIPLE_VERSION =$(shell echo $(notdir $(SDKROOT)) | sed -e 's/.*\([0-9]\.[0-9]\).*/\1/') + endif + ARCH_CFLAGS :=-mios-version-min=$(TRIPLE_VERSION) -isysroot "$(SDKROOT)" + else + ifeq "$(TRIPLE_ENV)" "macabi" + SDKROOT = $(shell xcrun --sdk macosx --show-sdk-path) + else + SDKROOT = $(shell xcrun --sdk iphonesimulator --show-sdk-path) + endif + ifeq "$(TRIPLE_VERSION)" "" + TRIPLE_VERSION =$(shell echo $(notdir $(SDKROOT)) | sed -e 's/.*\([0-9]\.[0-9]\).*/\1/') + endif + ifeq "$(TRIPLE_ENV)" "macabi" + ARCH_CFLAGS :=-mios-version-min=$(TRIPLE_VERSION) -isysroot "$(SDKROOT)" + else + ARCH_CFLAGS :=-mios-simulator-version-min=$(TRIPLE_VERSION) -isysroot "$(SDKROOT)" + endif + endif + endif + endif + ifeq "$(TRIPLE_OS)" "watchos" + CODESIGN := codesign + ifeq "$(SDKROOT)" "" + # Set SDKROOT if it wasn't set + ifneq (,$(findstring arm,$(ARCH))) + SDKROOT = $(shell xcrun --sdk watchos --show-sdk-path) + ifeq "$(TRIPLE_VERSION)" "" + TRIPLE_VERSION =$(shell echo $(notdir $(SDKROOT)) | sed -e 's/.*\([0-9]\.[0-9]\).*/\1/') + endif + ARCH_CFLAGS :=-mwatchos-version-min=$(TRIPLE_VERSION) -isysroot "$(SDKROOT)" + else + SDKROOT = $(shell xcrun --sdk watchsimulator --show-sdk-path) + ifeq "$(TRIPLE_VERSION)" "" + TRIPLE_VERSION =$(shell echo $(notdir $(SDKROOT)) | sed -e 's/.*\([0-9]\.[0-9]\).*/\1/') + endif + ARCH_CFLAGS :=-mwatchos-simulator-version-min=$(TRIPLE_VERSION) -isysroot "$(SDKROOT)" + endif + endif + endif + endif +endif +ifeq "$(OS)" "Android" + include $(THIS_FILE_DIR)/Android.rules +endif + +#---------------------------------------------------------------------- +# If ARCH is not defined, default to x86_64. +#---------------------------------------------------------------------- +ifeq "$(ARCH)" "" +ifeq "$(OS)" "Windows_NT" + ARCH = x86 +else + ARCH = x86_64 +endif +endif + +#---------------------------------------------------------------------- +# CC defaults to clang. +# +# If you change the defaults of CC, be sure to also change it in the file +# test/plugins/builder_base.py, which provides a Python way to return the +# value of the make variable CC -- getCompiler(). +# +# See also these functions: +# o cxx_compiler +# o cxx_linker +#---------------------------------------------------------------------- +ifeq "$(CC)" "" +$(error "C compiler is not specified. Please run tests through lldb-dotest or lit") +endif + +#---------------------------------------------------------------------- +# Handle SDKROOT on Darwin +#---------------------------------------------------------------------- + +ifeq "$(OS)" "Darwin" + ifeq "$(SDKROOT)" "" + # We haven't otherwise set the SDKROOT, so set it now to macosx + SDKROOT := $(shell xcrun --sdk macosx --show-sdk-path) + endif +endif + +#---------------------------------------------------------------------- +# ARCHFLAG is the flag used to tell the compiler which architecture +# to compile for. The default is the flag that clang accepts. +#---------------------------------------------------------------------- +ARCHFLAG ?= -arch + +#---------------------------------------------------------------------- +# Change any build/tool options needed +#---------------------------------------------------------------------- +ifeq "$(OS)" "Darwin" + DS := $(DSYMUTIL) + DSFLAGS = + DSYM = $(EXE).dSYM + AR := $(CROSS_COMPILE)libtool + ARFLAGS := -static -o +else + AR := $(CROSS_COMPILE)ar + # On non-Apple platforms, -arch becomes -m + ARCHFLAG := -m + + # i386, i686, x86 -> 32 + # amd64, x86_64, x64 -> 64 + ifeq "$(ARCH)" "amd64" + override ARCH := $(subst amd64,64,$(ARCH)) + endif + ifeq "$(ARCH)" "x86_64" + override ARCH := $(subst x86_64,64,$(ARCH)) + endif + ifeq "$(ARCH)" "x64" + override ARCH := $(subst x64,64,$(ARCH)) + endif + ifeq "$(ARCH)" "x86" + override ARCH := $(subst x86,32,$(ARCH)) + endif + ifeq "$(ARCH)" "i386" + override ARCH := $(subst i386,32,$(ARCH)) + endif + ifeq "$(ARCH)" "i686" + override ARCH := $(subst i686,32,$(ARCH)) + endif + ifeq "$(ARCH)" "powerpc" + override ARCH := $(subst powerpc,32,$(ARCH)) + endif + ifeq "$(ARCH)" "powerpc64" + override ARCH := $(subst powerpc64,64,$(ARCH)) + endif + ifeq "$(ARCH)" "powerpc64le" + override ARCH := $(subst powerpc64le,64,$(ARCH)) + endif + ifeq "$(ARCH)" "aarch64" + override ARCH := + override ARCHFLAG := + endif + ifeq "$(findstring arm,$(ARCH))" "arm" + override ARCH := + override ARCHFLAG := + endif + ifeq "$(ARCH)" "s390x" + override ARCH := + override ARCHFLAG := + endif + ifeq "$(findstring mips,$(ARCH))" "mips" + override ARCHFLAG := - + endif + + ifeq "$(SPLIT_DEBUG_SYMBOLS)" "YES" + DSYM = $(EXE).debug + endif +endif + +LIMIT_DEBUG_INFO_FLAGS = +NO_LIMIT_DEBUG_INFO_FLAGS = +MODULE_DEBUG_INFO_FLAGS = +ifneq (,$(findstring clang,$(CC))) + LIMIT_DEBUG_INFO_FLAGS += -flimit-debug-info + NO_LIMIT_DEBUG_INFO_FLAGS += -fno-limit-debug-info + MODULE_DEBUG_INFO_FLAGS += -gmodules +endif + +DEBUG_INFO_FLAG ?= -g + +CFLAGS ?= $(DEBUG_INFO_FLAG) -O0 -fno-builtin + +ifeq "$(OS)" "Darwin" + ifneq "$(SDKROOT)" "" + CFLAGS += -isysroot "$(SDKROOT)" + endif +endif + +ifeq "$(OS)" "Darwin" + CFLAGS += $(ARCHFLAG) $(ARCH) $(FRAMEWORK_INCLUDES) -I$(LLDB_BASE_DIR)include +else + CFLAGS += $(ARCHFLAG)$(ARCH) $(FRAMEWORK_INCLUDES) -I$(LLDB_BASE_DIR)include +endif + +CFLAGS += -I$(SRCDIR) -I$(THIS_FILE_DIR) + +ifndef NO_TEST_COMMON_H + CFLAGS += -include $(THIS_FILE_DIR)/test_common.h +endif + +CFLAGS += $(NO_LIMIT_DEBUG_INFO_FLAGS) $(ARCH_CFLAGS) $(CFLAGS_EXTRAS) + +# If the OS is Windows, we need to pass -gdwarf to clang, otherwise it will build +# with codeview by default but all the tests rely on dwarf. +ifeq "$(OS)" "Windows_NT" + CFLAGS += -gdwarf +endif + +# Use this one if you want to build one part of the result without debug information: +ifeq "$(OS)" "Darwin" + CFLAGS_NO_DEBUG = -O0 $(ARCHFLAG) $(ARCH) $(FRAMEWORK_INCLUDES) $(ARCH_CFLAGS) $(CFLAGS_EXTRAS) +else + CFLAGS_NO_DEBUG = -O0 $(ARCHFLAG)$(ARCH) $(FRAMEWORK_INCLUDES) $(ARCH_CFLAGS) $(CFLAGS_EXTRAS) +endif + +ifeq "$(MAKE_DWO)" "YES" + CFLAGS += -gsplit-dwarf +endif + +ifeq "$(USE_PRIVATE_MODULE_CACHE)" "YES" +THE_CLANG_MODULE_CACHE_DIR := $(BUILDDIR)/private-module-cache +else +THE_CLANG_MODULE_CACHE_DIR := $(CLANG_MODULE_CACHE_DIR) +endif + +MODULE_BASE_FLAGS := -fmodules -gmodules -fmodules-cache-path=$(THE_CLANG_MODULE_CACHE_DIR) +MANDATORY_MODULE_BUILD_CFLAGS := $(MODULE_BASE_FLAGS) -gmodules +# Build flags for building with C++ modules. +# -glldb is necessary for emitting information about what modules were imported. +MANDATORY_CXXMODULE_BUILD_CFLAGS := $(MODULE_BASE_FLAGS) -fcxx-modules -glldb + +ifeq "$(OS)" "Darwin" + MANDATORY_MODULE_BUILD_CFLAGS += -fcxx-modules +endif + +ifeq "$(MAKE_GMODULES)" "YES" + CFLAGS += $(MANDATORY_MODULE_BUILD_CFLAGS) + CXXFLAGS += $(MANDATORY_MODULE_BUILD_CFLAGS) +endif + +CXXFLAGS += -std=c++11 $(CFLAGS) $(ARCH_CXXFLAGS) $(CXXFLAGS_EXTRAS) +LD = $(CC) +LDFLAGS ?= $(CFLAGS) +LDFLAGS += $(LD_EXTRAS) $(ARCH_LDFLAGS) +ifneq (,$(LLVM_LIBS_DIR)) + ifeq ($(OS),NetBSD) + LDFLAGS += -L$(LLVM_LIBS_DIR) -Wl,-rpath,$(LLVM_LIBS_DIR) + endif +endif +ifeq (,$(filter $(OS), Windows_NT Android Darwin)) + ifneq (,$(filter YES,$(ENABLE_THREADS))) + LDFLAGS += -pthread + endif +endif +OBJECTS = +EXE ?= a.out + +ifneq "$(FRAMEWORK)" "" + DYLIB_NAME ?= $(FRAMEWORK).framework/Versions/A/$(FRAMEWORK) + DYLIB_FILENAME ?= $(FRAMEWORK).framework/Versions/A/$(FRAMEWORK) +endif + +ifneq "$(DYLIB_NAME)" "" + ifeq "$(OS)" "Darwin" + ifneq "$(FRAMEWORK)" "" + DYLIB_INSTALL_NAME ?= @executable_path/$(FRAMEWORK).framework/Versions/A/$(FRAMEWORK) + else + DYLIB_FILENAME = lib$(DYLIB_NAME).dylib + DYLIB_INSTALL_NAME ?= @executable_path/$(DYLIB_FILENAME) + endif + else ifeq "$(OS)" "Windows_NT" + DYLIB_FILENAME = $(DYLIB_NAME).dll + else + DYLIB_FILENAME = lib$(DYLIB_NAME).so + endif +endif + +# Function that returns the counterpart C++ compiler, given $(CC) as arg. +cxx_compiler_notdir = $(if $(findstring icc,$(1)), \ + $(subst icc,icpc,$(1)), \ + $(if $(findstring llvm-gcc,$(1)), \ + $(subst llvm-gcc,llvm-g++,$(1)), \ + $(if $(findstring gcc,$(1)), \ + $(subst gcc,g++,$(1)), \ + $(subst cc,c++,$(1))))) +cxx_compiler = $(if $(findstring /,$(1)),$(join $(dir $(1)), $(call cxx_compiler_notdir,$(notdir $(1)))),$(call cxx_compiler_notdir,$(1))) + +# Function that returns the C++ linker, given $(CC) as arg. +cxx_linker_notdir = $(if $(findstring icc,$(1)), \ + $(subst icc,icpc,$(1)), \ + $(if $(findstring llvm-gcc,$(1)), \ + $(subst llvm-gcc,llvm-g++,$(1)), \ + $(if $(findstring gcc,$(1)), \ + $(subst gcc,g++,$(1)), \ + $(subst cc,c++,$(1))))) +cxx_linker = $(if $(findstring /,$(1)),$(join $(dir $(1)), $(call cxx_linker_notdir,$(notdir $(1)))),$(call cxx_linker_notdir,$(1))) + +ifneq "$(OS)" "Darwin" + CLANG_OR_GCC := $(strip $(if $(findstring clang,$(CC)), \ + $(findstring clang,$(CC)), \ + $(if $(findstring gcc,$(CC)), \ + $(findstring gcc,$(CC)), \ + cc))) + + CC_LASTWORD := $(strip $(lastword $(subst -, ,$(CC)))) + + replace_with = $(strip $(if $(findstring $(3),$(CC_LASTWORD)), \ + $(subst $(3),$(1),$(2)), \ + $(subst $(3),$(1),$(subst -$(CC_LASTWORD),,$(2))))) + + ifeq "$(notdir $(CC))" "$(CC)" + replace_cc_with = $(call replace_with,$(1),$(CC),$(CLANG_OR_GCC)) + else + replace_cc_with = $(join $(dir $(CC)),$(call replace_with,$(1),$(notdir $(CC)),$(CLANG_OR_GCC))) + endif + + OBJCOPY ?= $(call replace_cc_with,objcopy) + ARCHIVER ?= $(call replace_cc_with,ar) + override AR = $(ARCHIVER) +endif + +ifdef PIE + LDFLAGS += -pie +endif + +#---------------------------------------------------------------------- +# Windows specific options +#---------------------------------------------------------------------- +ifeq "$(OS)" "Windows_NT" + ifneq (,$(findstring clang,$(CC))) + # Clang for Windows doesn't support C++ Exceptions + CXXFLAGS += -fno-exceptions + CXXFLAGS += -D_HAS_EXCEPTIONS=0 + + # MSVC 2015 or higher is required, which depends on c++14, so + # append these values unconditionally. + CXXFLAGS += -fms-compatibility-version=19.0 + override CXXFLAGS := $(subst -std=c++11,-std=c++14,$(CXXFLAGS)) + + # The MSVC linker doesn't understand long section names + # generated by the clang compiler. + LDFLAGS += -fuse-ld=lld + endif +endif + +#---------------------------------------------------------------------- +# C++ standard library options +#---------------------------------------------------------------------- +ifeq (1,$(USE_LIBSTDCPP)) + # Clang requires an extra flag: -stdlib=libstdc++ + ifneq (,$(findstring clang,$(CC))) + CXXFLAGS += -stdlib=libstdc++ -DLLDB_USING_LIBSTDCPP + LDFLAGS += -stdlib=libstdc++ + endif +endif + +ifeq (1,$(USE_LIBCPP)) + CXXFLAGS += -DLLDB_USING_LIBCPP + ifeq "$(OS)" "Linux" + ifneq (,$(findstring clang,$(CC))) + CXXFLAGS += -stdlib=libc++ + LDFLAGS += -stdlib=libc++ + else + CXXFLAGS += -isystem /usr/include/c++/v1 + LDFLAGS += -lc++ + endif + else ifeq "$(OS)" "Android" + # Nothing to do, this is already handled in + # Android.rules. + else + CXXFLAGS += -stdlib=libc++ + LDFLAGS += -stdlib=libc++ + endif +endif + +#---------------------------------------------------------------------- +# Additional system libraries +#---------------------------------------------------------------------- +ifeq (1,$(USE_LIBDL)) + ifneq ($(OS),NetBSD) + LDFLAGS += -ldl + endif +endif + +#---------------------------------------------------------------------- +# dylib settings +#---------------------------------------------------------------------- + +DYLIB_OBJECTS +=$(strip $(DYLIB_C_SOURCES:.c=.o)) +DYLIB_OBJECTS +=$(strip $(DYLIB_OBJC_SOURCES:.m=.o)) +ifneq "$(strip $(DYLIB_CXX_SOURCES))" "" + DYLIB_OBJECTS +=$(strip $(patsubst %.mm, %.o, $(DYLIB_CXX_SOURCES:.cpp=.o))) + CXX = $(call cxx_compiler,$(CC)) + LD = $(call cxx_linker,$(CC)) +endif + +#---------------------------------------------------------------------- +# Check if we have a precompiled header +#---------------------------------------------------------------------- +ifneq "$(strip $(PCH_CXX_SOURCE))" "" + PCH_OUTPUT = $(PCH_CXX_SOURCE:.h=.h.pch) + PCHFLAGS = -include $(PCH_CXX_SOURCE) +endif + +#---------------------------------------------------------------------- +# Check if we have any C source files +#---------------------------------------------------------------------- +ifneq "$(strip $(C_SOURCES))" "" + OBJECTS +=$(strip $(C_SOURCES:.c=.o)) +endif + +#---------------------------------------------------------------------- +# Check if we have any C++ source files +#---------------------------------------------------------------------- +ifneq "$(strip $(CXX_SOURCES))" "" + OBJECTS +=$(strip $(CXX_SOURCES:.cpp=.o)) + CXX = $(call cxx_compiler,$(CC)) + LD = $(call cxx_linker,$(CC)) +endif + +#---------------------------------------------------------------------- +# Check if we have any ObjC source files +#---------------------------------------------------------------------- +ifneq "$(strip $(OBJC_SOURCES))" "" + OBJECTS +=$(strip $(OBJC_SOURCES:.m=.o)) + LDFLAGS +=-lobjc +endif + +#---------------------------------------------------------------------- +# Check if we have any ObjC++ source files +#---------------------------------------------------------------------- +ifneq "$(strip $(OBJCXX_SOURCES))" "" + OBJECTS +=$(strip $(OBJCXX_SOURCES:.mm=.o)) + CXX = $(call cxx_compiler,$(CC)) + LD = $(call cxx_linker,$(CC)) + ifeq "$(findstring lobjc,$(LDFLAGS))" "" + LDFLAGS +=-lobjc + endif +endif + +#---------------------------------------------------------------------- +# Check if we have any C source files for archive +#---------------------------------------------------------------------- +ifneq "$(strip $(ARCHIVE_C_SOURCES))" "" + ARCHIVE_OBJECTS +=$(strip $(ARCHIVE_C_SOURCES:.c=.o)) +endif + +#---------------------------------------------------------------------- +# Check if we have any C++ source files for archive +#---------------------------------------------------------------------- +ifneq "$(strip $(ARCHIVE_CXX_SOURCES))" "" + ARCHIVE_OBJECTS +=$(strip $(ARCHIVE_CXX_SOURCES:.cpp=.o)) + CXX = $(call cxx_compiler,$(CC)) + LD = $(call cxx_linker,$(CC)) +endif + +#---------------------------------------------------------------------- +# Check if we have any ObjC source files for archive +#---------------------------------------------------------------------- +ifneq "$(strip $(ARCHIVE_OBJC_SOURCES))" "" + ARCHIVE_OBJECTS +=$(strip $(ARCHIVE_OBJC_SOURCES:.m=.o)) + LDFLAGS +=-lobjc +endif + +#---------------------------------------------------------------------- +# Check if we have any ObjC++ source files for archive +#---------------------------------------------------------------------- +ifneq "$(strip $(ARCHIVE_OBJCXX_SOURCES))" "" + ARCHIVE_OBJECTS +=$(strip $(ARCHIVE_OBJCXX_SOURCES:.mm=.o)) + CXX = $(call cxx_compiler,$(CC)) + LD = $(call cxx_linker,$(CC)) + ifeq "$(findstring lobjc,$(LDFLAGS))" "" + LDFLAGS +=-lobjc + endif +endif + +#---------------------------------------------------------------------- +# Check if we are compiling with gcc 4.6 +#---------------------------------------------------------------------- +ifneq "$(strip $(CXX_SOURCES) $(OBJCXX_SOURCES))" "" +ifneq "$(filter g++,$(CXX))" "" + CXXVERSION = $(shell $(CXX) -dumpversion | cut -b 1-3) + ifeq "$(CXXVERSION)" "4.6" + # GCC 4.6 cannot handle -std=c++11, so replace it with -std=c++0x + # instead. FIXME: remove once GCC version is upgraded. + override CXXFLAGS := $(subst -std=c++11,-std=c++0x,$(CXXFLAGS)) + endif +endif +endif + +ifeq ($(findstring clang, $(CXX)), clang) + CXXFLAGS += --driver-mode=g++ +endif + +ifneq "$(CXX)" "" + ifeq ($(findstring clang, $(LD)), clang) + LDFLAGS += --driver-mode=g++ + endif +endif + +#---------------------------------------------------------------------- +# DYLIB_ONLY variable can be used to skip the building of a.out. +# See the sections below regarding dSYM file as well as the building of +# EXE from all the objects. +#---------------------------------------------------------------------- + +#---------------------------------------------------------------------- +# Compile the executable from all the objects. +#---------------------------------------------------------------------- +ifneq "$(DYLIB_NAME)" "" +ifeq "$(DYLIB_ONLY)" "" +$(EXE) : $(OBJECTS) $(ARCHIVE_NAME) $(DYLIB_FILENAME) + $(LD) $(OBJECTS) $(ARCHIVE_NAME) -L. -l$(DYLIB_NAME) $(LDFLAGS) -o "$(EXE)" +ifneq "$(CODESIGN)" "" + $(CODESIGN) -s - "$(EXE)" +endif +else +EXE = $(DYLIB_FILENAME) +endif +else +$(EXE) : $(OBJECTS) $(ARCHIVE_NAME) + $(LD) $(OBJECTS) $(LDFLAGS) $(ARCHIVE_NAME) -o "$(EXE)" +ifneq "$(CODESIGN)" "" + $(CODESIGN) -s - "$(EXE)" +endif +endif + +#---------------------------------------------------------------------- +# Make the dSYM file from the executable if $(MAKE_DSYM) != "NO" +#---------------------------------------------------------------------- +$(DSYM) : $(EXE) +ifeq "$(OS)" "Darwin" +ifneq "$(MAKE_DSYM)" "NO" + "$(DS)" $(DSFLAGS) -o "$(DSYM)" "$(EXE)" +else +endif +else +ifeq "$(SPLIT_DEBUG_SYMBOLS)" "YES" + $(OBJCOPY) --only-keep-debug "$(EXE)" "$(DSYM)" + $(OBJCOPY) --strip-debug --add-gnu-debuglink="$(DSYM)" "$(EXE)" "$(EXE)" +endif +endif + +#---------------------------------------------------------------------- +# Make the archive +#---------------------------------------------------------------------- +ifneq "$(ARCHIVE_NAME)" "" +ifeq "$(OS)" "Darwin" +$(ARCHIVE_NAME) : $(ARCHIVE_OBJECTS) + $(AR) $(ARFLAGS) $(ARCHIVE_NAME) $(ARCHIVE_OBJECTS) + $(RM) $(ARCHIVE_OBJECTS) +else +$(ARCHIVE_NAME) : $(foreach ar_obj,$(ARCHIVE_OBJECTS),$(ARCHIVE_NAME)($(ar_obj))) +endif +endif + +#---------------------------------------------------------------------- +# Make the dylib +#---------------------------------------------------------------------- +$(DYLIB_OBJECTS) : CFLAGS += -DCOMPILING_LLDB_TEST_DLL + +ifneq "$(OS)" "Windows_NT" +$(DYLIB_OBJECTS) : CFLAGS += -fPIC +$(DYLIB_OBJECTS) : CXXFLAGS += -fPIC +endif + +$(DYLIB_FILENAME) : $(DYLIB_OBJECTS) +ifeq "$(OS)" "Darwin" +ifneq "$(FRAMEWORK)" "" + mkdir -p $(FRAMEWORK).framework/Versions/A/Headers + mkdir -p $(FRAMEWORK).framework/Versions/A/Modules + mkdir -p $(FRAMEWORK).framework/Versions/A/Resources +ifneq "$(FRAMEWORK_MODULES)" "" + cp -r $(FRAMEWORK_MODULES) $(FRAMEWORK).framework/Versions/A/Modules +endif +ifneq "$(FRAMEWORK_HEADERS)" "" + cp -r $(FRAMEWORK_HEADERS) $(FRAMEWORK).framework/Versions/A/Headers +endif + (cd $(FRAMEWORK).framework/Versions; ln -sf A Current) + (cd $(FRAMEWORK).framework/; ln -sf Versions/A/Headers Headers) + (cd $(FRAMEWORK).framework/; ln -sf Versions/A/Modules Modules) + (cd $(FRAMEWORK).framework/; ln -sf Versions/A/Resources Resources) + (cd $(FRAMEWORK).framework/; ln -sf Versions/A/$(FRAMEWORK) $(FRAMEWORK)) +endif + $(LD) $(DYLIB_OBJECTS) $(LDFLAGS) -install_name "$(DYLIB_INSTALL_NAME)" -dynamiclib -o "$(DYLIB_FILENAME)" +ifneq "$(CODESIGN)" "" + $(CODESIGN) -s - "$(DYLIB_FILENAME)" +endif +ifneq "$(MAKE_DSYM)" "NO" +ifneq "$(DS)" "" + "$(DS)" $(DSFLAGS) "$(DYLIB_FILENAME)" +endif +endif +else + $(LD) $(DYLIB_OBJECTS) $(LDFLAGS) -shared -o "$(DYLIB_FILENAME)" +ifeq "$(SPLIT_DEBUG_SYMBOLS)" "YES" + $(OBJCOPY) --only-keep-debug "$(DYLIB_FILENAME)" "$(DYLIB_FILENAME).debug" + $(OBJCOPY) --strip-debug --add-gnu-debuglink="$(DYLIB_FILENAME).debug" "$(DYLIB_FILENAME)" "$(DYLIB_FILENAME)" +endif +endif + +#---------------------------------------------------------------------- +# Make the precompiled header and compile C++ sources against it +#---------------------------------------------------------------------- + +#ifneq "$(PCH_OUTPUT)" "" +$(PCH_OUTPUT) : $(PCH_CXX_SOURCE) + $(CXX) $(CXXFLAGS) -x c++-header -o $@ $< +%.o : %.cpp $(PCH_OUTPUT) + $(CXX) $(PCHFLAGS) $(CXXFLAGS) -c -o $@ $< +#endif + +#---------------------------------------------------------------------- +# Automatic variables based on items already entered. Below we create +# an object's lists from the list of sources by replacing all entries +# that end with .c with .o, and we also create a list of prerequisite +# files by replacing all .c files with .d. +#---------------------------------------------------------------------- +PREREQS := $(OBJECTS:.o=.d) +DWOS := $(OBJECTS:.o=.dwo) $(ARCHIVE_OBJECTS:.o=.dwo) +ifneq "$(DYLIB_NAME)" "" + DYLIB_PREREQS := $(DYLIB_OBJECTS:.o=.d) + DYLIB_DWOS := $(DYLIB_OBJECTS:.o=.dwo) +endif + +#---------------------------------------------------------------------- +# Rule for Generating Prerequisites Automatically using .d files and +# the compiler -MM option. The -M option will list all system headers, +# and the -MM option will list all non-system dependencies. +#---------------------------------------------------------------------- +%.d: %.c + @rm -f $@ $(JOIN_CMD) \ + $(CC) -M $(CFLAGS) $< > $@.tmp && \ + sed $(QUOTE)s,\($*\)\.o[ :]*,\1.o $@ : ,g$(QUOTE) < $@.tmp > $@ $(JOIN_CMD) \ + rm -f $@.tmp + +%.d: %.cpp + @rm -f $@ $(JOIN_CMD) \ + $(CXX) -M $(CXXFLAGS) $< > $@.tmp && \ + sed $(QUOTE)s,\($*\)\.o[ :]*,\1.o $@ : ,g$(QUOTE) < $@.tmp > $@ $(JOIN_CMD) \ + rm -f $@.tmp + +%.d: %.m + @rm -f $@ $(JOIN_CMD) \ + $(CC) -M $(CFLAGS) $< > $@.tmp && \ + sed $(QUOTE)s,\($*\)\.o[ :]*,\1.o $@ : ,g$(QUOTE) < $@.tmp > $@ $(JOIN_CMD) \ + rm -f $@.tmp + +%.d: %.mm + @rm -f $@ $(JOIN_CMD) \ + $(CXX) -M $(CXXFLAGS) $< > $@.tmp && \ + sed $(QUOTE)s,\($*\)\.o[ :]*,\1.o $@ : ,g$(QUOTE) < $@.tmp > $@ $(JOIN_CMD) \ + rm -f $@.tmp + +#---------------------------------------------------------------------- +# Include all of the makefiles for each source file so we don't have +# to manually track all of the prerequisites for each source file. +#---------------------------------------------------------------------- +sinclude $(PREREQS) +ifneq "$(DYLIB_NAME)" "" + sinclude $(DYLIB_PREREQS) +endif + +# Define a suffix rule for .mm -> .o +.SUFFIXES: .mm .o +.mm.o: + $(CXX) $(CXXFLAGS) -c $< + +.PHONY: clean +dsym: $(DSYM) +all: $(EXE) $(DSYM) +clean:: +ifeq "$(findstring lldb-test-build.noindex, $(BUILDDIR))" "" + $(error Trying to invoke the clean rule, but not using the default build tree layout) +else + $(RM) -r $(wildcard $(BUILDDIR)/*) +endif + +#---------------------------------------------------------------------- +# From http://blog.melski.net/tag/debugging-makefiles/ +# +# Usage: make print-CC print-CXX print-LD +#---------------------------------------------------------------------- +print-%: + @echo '$*=$($*)' + @echo ' origin = $(origin $*)' + @echo ' flavor = $(flavor $*)' + @echo ' value = $(value $*)' + +### Local Variables: ### +### mode:makefile ### +### End: ### diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/pseudo_barrier.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/pseudo_barrier.h new file mode 100644 index 00000000000..e4066b72e02 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/pseudo_barrier.h @@ -0,0 +1,21 @@ +#include <atomic> + +// Note that although hogging the CPU while waiting for a variable to change +// would be terrible in production code, it's great for testing since it avoids +// a lot of messy context switching to get multiple threads synchronized. + +typedef std::atomic<int> pseudo_barrier_t; + +#define pseudo_barrier_wait(barrier) \ + do \ + { \ + --(barrier); \ + while ((barrier).load() > 0) \ + ; \ + } while (0) + +#define pseudo_barrier_init(barrier, count) \ + do \ + { \ + (barrier) = (count); \ + } while (0) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/test_common.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/test_common.h new file mode 100644 index 00000000000..529d0952ed3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/make/test_common.h @@ -0,0 +1,47 @@ +// This header is included in all the test programs (C and C++) and provides a +// hook for dealing with platform-specifics. +#if defined(_WIN32) || defined(_WIN64) +#ifdef COMPILING_LLDB_TEST_DLL +#define LLDB_TEST_API __declspec(dllexport) +#else +#define LLDB_TEST_API __declspec(dllimport) +#endif +#else +#define LLDB_TEST_API +#endif + +#if defined(_WIN32) +#define LLVM_PRETTY_FUNCTION __FUNCSIG__ +#else +#define LLVM_PRETTY_FUNCTION LLVM_PRETTY_FUNCTION +#endif + + +// On some systems (e.g., some versions of linux) it is not possible to attach to a process +// without it giving us special permissions. This defines the lldb_enable_attach macro, which +// should perform any such actions, if needed by the platform. This is a macro instead of a +// function to avoid the need for complex linking of the test programs. +#if defined(__linux__) +#include <sys/prctl.h> + +// Android API <= 16 does not have these defined. +#ifndef PR_SET_PTRACER +#define PR_SET_PTRACER 0x59616d61 +#endif +#ifndef PR_SET_PTRACER_ANY +#define PR_SET_PTRACER_ANY ((unsigned long)-1) +#endif + +// For now we execute on best effort basis. If this fails for some reason, so be it. +#define lldb_enable_attach() \ + do \ + { \ + const int prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0); \ + (void)prctl_result; \ + } while (0) + +#else // not linux + +#define lldb_enable_attach() + +#endif diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_base.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_base.py new file mode 100644 index 00000000000..aede03da14c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_base.py @@ -0,0 +1,263 @@ +""" +If the build* function is passed the compiler argument, for example, 'llvm-gcc', +it is passed as a make variable to the make command. Otherwise, we check the +LLDB_CC environment variable; if it is defined, it is passed as a make variable +to the make command. + +If neither the compiler keyword argument nor the LLDB_CC environment variable is +specified, no CC make variable is passed to the make command. The Makefile gets +to define the default CC being used. + +Same idea holds for LLDB_ARCH environment variable, which maps to the ARCH make +variable. +""" + +# System imports +import os +import platform +import subprocess +import sys + +# Our imports +import lldbsuite.test.lldbtest as lldbtest +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test_event import build_exception + + +def getArchitecture(): + """Returns the architecture in effect the test suite is running with.""" + return os.environ["ARCH"] if "ARCH" in os.environ else "" + + +def getCompiler(): + """Returns the compiler in effect the test suite is running with.""" + compiler = os.environ.get("CC", "clang") + compiler = lldbutil.which(compiler) + return os.path.realpath(compiler) + + +def getArchFlag(): + """Returns the flag required to specify the arch""" + compiler = getCompiler() + if compiler is None: + return "" + elif "gcc" in compiler: + archflag = "-m" + elif "clang" in compiler: + archflag = "-arch" + else: + archflag = None + + return ("ARCHFLAG=" + archflag) if archflag else "" + +def getMake(test_subdir, test_name): + """Returns the invocation for GNU make. + The first argument is a tuple of the relative path to the testcase + and its filename stem.""" + if platform.system() == "FreeBSD" or platform.system() == "NetBSD": + make = "gmake" + else: + make = "make" + + # Construct the base make invocation. + lldb_test = os.environ["LLDB_TEST"] + lldb_build = os.environ["LLDB_BUILD"] + if not (lldb_test and lldb_build and test_subdir and test_name and + (not os.path.isabs(test_subdir))): + raise Exception("Could not derive test directories") + build_dir = os.path.join(lldb_build, test_subdir, test_name) + src_dir = os.path.join(lldb_test, test_subdir) + # This is a bit of a hack to make inline testcases work. + makefile = os.path.join(src_dir, "Makefile") + if not os.path.isfile(makefile): + makefile = os.path.join(build_dir, "Makefile") + return [make, + "VPATH="+src_dir, + "-C", build_dir, + "-I", src_dir, + "-I", os.path.join(lldb_test, "make"), + "-f", makefile] + + +def getArchSpec(architecture): + """ + Helper function to return the key-value string to specify the architecture + used for the make system. + """ + arch = architecture if architecture else None + if not arch and "ARCH" in os.environ: + arch = os.environ["ARCH"] + + return ("ARCH=" + arch) if arch else "" + + +def getCCSpec(compiler): + """ + Helper function to return the key-value string to specify the compiler + used for the make system. + """ + cc = compiler if compiler else None + if not cc and "CC" in os.environ: + cc = os.environ["CC"] + if cc: + return "CC=\"%s\"" % cc + else: + return "" + +def getDsymutilSpec(): + """ + Helper function to return the key-value string to specify the dsymutil + used for the make system. + """ + if "DSYMUTIL" in os.environ: + return "DSYMUTIL={}".format(os.environ["DSYMUTIL"]) + return ""; + +def getSDKRootSpec(): + """ + Helper function to return the key-value string to specify the SDK root + used for the make system. + """ + if "SDKROOT" in os.environ: + return "SDKROOT={}".format(os.environ["SDKROOT"]) + return ""; + +def getModuleCacheSpec(): + """ + Helper function to return the key-value string to specify the clang + module cache used for the make system. + """ + if "CLANG_MODULE_CACHE_DIR" in os.environ: + return "CLANG_MODULE_CACHE_DIR={}".format( + os.environ["CLANG_MODULE_CACHE_DIR"]) + return ""; + +def getCmdLine(d): + """ + Helper function to return a properly formatted command line argument(s) + string used for the make system. + """ + + # If d is None or an empty mapping, just return an empty string. + if not d: + return "" + pattern = '%s="%s"' if "win32" in sys.platform else "%s='%s'" + + def setOrAppendVariable(k, v): + append_vars = ["CFLAGS", "CFLAGS_EXTRAS", "LD_EXTRAS"] + if k in append_vars and k in os.environ: + v = os.environ[k] + " " + v + return pattern % (k, v) + cmdline = " ".join([setOrAppendVariable(k, v) for k, v in list(d.items())]) + + return cmdline + + +def runBuildCommands(commands, sender): + try: + lldbtest.system(commands, sender=sender) + except subprocess.CalledProcessError as called_process_error: + # Convert to a build-specific error. + # We don't do that in lldbtest.system() since that + # is more general purpose. + raise build_exception.BuildError(called_process_error) + + +def buildDefault( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None, + testname=None): + """Build the binaries the default way.""" + commands = [] + commands.append(getMake(testdir, testname) + + ["all", + getArchSpec(architecture), + getCCSpec(compiler), + getDsymutilSpec(), + getSDKRootSpec(), + getModuleCacheSpec(), + getCmdLine(dictionary)]) + + runBuildCommands(commands, sender=sender) + + # True signifies that we can handle building default. + return True + + +def buildDwarf( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None, + testname=None): + """Build the binaries with dwarf debug info.""" + commands = [] + commands.append(getMake(testdir, testname) + + ["MAKE_DSYM=NO", + getArchSpec(architecture), + getCCSpec(compiler), + getDsymutilSpec(), + getSDKRootSpec(), + getModuleCacheSpec(), + getCmdLine(dictionary)]) + + runBuildCommands(commands, sender=sender) + # True signifies that we can handle building dwarf. + return True + + +def buildDwo( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None, + testname=None): + """Build the binaries with dwarf debug info.""" + commands = [] + commands.append(getMake(testdir, testname) + + ["MAKE_DSYM=NO", + "MAKE_DWO=YES", + getArchSpec(architecture), + getCCSpec(compiler), + getDsymutilSpec(), + getSDKRootSpec(), + getModuleCacheSpec(), + getCmdLine(dictionary)]) + + runBuildCommands(commands, sender=sender) + # True signifies that we can handle building dwo. + return True + + +def buildGModules( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None, + testname=None): + """Build the binaries with dwarf debug info.""" + commands = [] + commands.append(getMake(testdir, testname) + + ["MAKE_DSYM=NO", + "MAKE_GMODULES=YES", + getArchSpec(architecture), + getCCSpec(compiler), + getDsymutilSpec(), + getSDKRootSpec(), + getModuleCacheSpec(), + getCmdLine(dictionary)]) + + lldbtest.system(commands, sender=sender) + # True signifies that we can handle building with gmodules. + return True + + +def cleanup(sender=None, dictionary=None): + """Perform a platform-specific cleanup after the test.""" + return True diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_darwin.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_darwin.py new file mode 100644 index 00000000000..e109f91945e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_darwin.py @@ -0,0 +1,24 @@ + +import lldbsuite.test.lldbtest as lldbtest + +from builder_base import * + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None, + testname=None): + """Build the binaries with dsym debug info.""" + commands = [] + commands.append(getMake(testdir, testname) + + ["MAKE_DSYM=YES", + getArchSpec(architecture), + getCCSpec(compiler), + "all", getCmdLine(dictionary)]) + + runBuildCommands(commands, sender=sender) + + # True signifies that we can handle building dsym. + return True diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_freebsd.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_freebsd.py new file mode 100644 index 00000000000..c3df36b5a36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_freebsd.py @@ -0,0 +1,10 @@ +from builder_base import * + + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None): + return False diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_linux.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_linux.py new file mode 100644 index 00000000000..c3df36b5a36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_linux.py @@ -0,0 +1,10 @@ +from builder_base import * + + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None): + return False diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_netbsd.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_netbsd.py new file mode 100644 index 00000000000..c3df36b5a36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_netbsd.py @@ -0,0 +1,10 @@ +from builder_base import * + + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None): + return False diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_openbsd.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_openbsd.py new file mode 100644 index 00000000000..c3df36b5a36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_openbsd.py @@ -0,0 +1,10 @@ +from builder_base import * + + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None): + return False diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_win32.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_win32.py new file mode 100644 index 00000000000..c3df36b5a36 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/plugins/builder_win32.py @@ -0,0 +1,10 @@ +from builder_base import * + + +def buildDsym( + sender=None, + architecture=None, + compiler=None, + dictionary=None, + testdir=None): + return False diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/.categories new file mode 100644 index 00000000000..db8069c3b9f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/.categories @@ -0,0 +1 @@ +pyapi diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py new file mode 100644 index 00000000000..dd578469634 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py @@ -0,0 +1,71 @@ +""" +Test SBBreakpoint APIs. +""" + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class BreakpointAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + def test_breakpoint_is_valid(self): + """Make sure that if an SBBreakpoint gets deleted its IsValid returns false.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'AFunction'. + breakpoint = target.BreakpointCreateByName('AFunction', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now delete it: + did_delete = target.BreakpointDelete(breakpoint.GetID()) + self.assertTrue( + did_delete, + "Did delete the breakpoint we just created.") + + # Make sure we can't find it: + del_bkpt = target.FindBreakpointByID(breakpoint.GetID()) + self.assertTrue(not del_bkpt, "We did delete the breakpoint.") + + # Finally make sure the original breakpoint is no longer valid. + self.assertTrue( + not breakpoint, + "Breakpoint we deleted is no longer valid.") + + @add_test_categories(['pyapi']) + def test_target_delete(self): + """Make sure that if an SBTarget gets deleted the associated + Breakpoint's IsValid returns false.""" + + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'AFunction'. + breakpoint = target.BreakpointCreateByName('AFunction', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + location = breakpoint.GetLocationAtIndex(0) + self.assertTrue(location.IsValid()) + + self.assertTrue(self.dbg.DeleteTarget(target)) + self.assertFalse(breakpoint.IsValid()) + self.assertFalse(location.IsValid()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/main.c new file mode 100644 index 00000000000..2677594e622 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/breakpoint/main.c @@ -0,0 +1,14 @@ +#include <stdio.h> + +void +AFunction() +{ + printf ("I am a function.\n"); +} + +int +main () +{ + AFunction(); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/class_members/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/class_members/Makefile new file mode 100644 index 00000000000..6f34ff7dd84 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/class_members/Makefile @@ -0,0 +1,3 @@ +OBJCXX_SOURCES := main.mm + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py new file mode 100644 index 00000000000..884043ac2ec --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py @@ -0,0 +1,117 @@ +""" +Test SBType APIs to fetch member function types. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SBTypeMemberFunctionsTest(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to break at. + self.source = 'main.mm' + self.line = line_number(self.source, '// set breakpoint here') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test(self): + """Test SBType APIs to fetch member function types.""" + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + exe = self.getBuildArtifact(self.exe_name) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Get Frame #0. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + + variable = frame0.FindVariable("d") + Derived = variable.GetType() + Base = Derived.GetDirectBaseClassAtIndex(0).GetType() + + self.assertEquals(2, + Derived.GetNumberOfMemberFunctions(), + "Derived declares two methods") + self.assertEquals("int", Derived.GetMemberFunctionAtIndex(0).GetType( + ).GetFunctionReturnType().GetName(), + "Derived::dImpl returns int") + + self.assertEquals(4, + Base.GetNumberOfMemberFunctions(), + "Base declares three methods") + self.assertEquals(3, Base.GetMemberFunctionAtIndex(3).GetType( + ).GetFunctionArgumentTypes().GetSize(), + "Base::sfunc takes three arguments") + self.assertEquals("sfunc", Base.GetMemberFunctionAtIndex( + 3).GetName(), "Base::sfunc not found") + self.assertEquals(lldb.eMemberFunctionKindStaticMethod, + Base.GetMemberFunctionAtIndex(3).GetKind(), + "Base::sfunc is a static") + self.assertEquals(0, Base.GetMemberFunctionAtIndex(2).GetType( + ).GetFunctionArgumentTypes().GetSize(), + "Base::dat takes no arguments") + self.assertEquals("char", + Base.GetMemberFunctionAtIndex(1).GetType().GetFunctionArgumentTypes( + ).GetTypeAtIndex(1).GetName(), + "Base::bar takes a second 'char' argument") + self.assertEquals("bar", + Base.GetMemberFunctionAtIndex(1).GetName(), "Base::bar not found") + + variable = frame0.FindVariable("thingy") + Thingy = variable.GetType() + + self.assertEquals( + 2, Thingy.GetNumberOfMemberFunctions(), + "Thingy declares two methods") + + self.assertEquals("id", Thingy.GetMemberFunctionAtIndex( + 0).GetReturnType().GetName(), "Thingy::init returns an id") + self.assertEquals(2, + Thingy.GetMemberFunctionAtIndex(1).GetNumberOfArguments(), + "Thingy::foo takes two arguments") + self.assertEquals("int", + Thingy.GetMemberFunctionAtIndex(1).GetArgumentTypeAtIndex( + 0).GetName(), "Thingy::foo takes an int") + + self.assertEquals("Derived::dImpl()", Derived.GetMemberFunctionAtIndex(0).GetDemangledName()) + self.assertEquals("Derived::baz(float)", Derived.GetMemberFunctionAtIndex(1).GetDemangledName()) + self.assertEquals("Base::foo(int, int)", Base.GetMemberFunctionAtIndex(0).GetDemangledName()) + self.assertEquals("Base::bar(int, char)", Base.GetMemberFunctionAtIndex(1).GetDemangledName()) + self.assertEquals("Base::dat()", Base.GetMemberFunctionAtIndex(2).GetDemangledName()) + self.assertEquals("Base::sfunc(char, int, float)", Base.GetMemberFunctionAtIndex(3).GetDemangledName()) + + self.assertEquals("_ZN7Derived5dImplEv", Derived.GetMemberFunctionAtIndex(0).GetMangledName()) + self.assertEquals("_ZN7Derived3bazEf", Derived.GetMemberFunctionAtIndex(1).GetMangledName()) + self.assertEquals("_ZN4Base3fooEii", Base.GetMemberFunctionAtIndex(0).GetMangledName()) + self.assertEquals("_ZN4Base3barEic", Base.GetMemberFunctionAtIndex(1).GetMangledName()) + self.assertEquals("_ZN4Base3datEv", Base.GetMemberFunctionAtIndex(2).GetMangledName()) + self.assertEquals("_ZN4Base5sfuncEcif", Base.GetMemberFunctionAtIndex(3).GetMangledName()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/class_members/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/class_members/main.mm new file mode 100644 index 00000000000..48a2c59ad4a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/class_members/main.mm @@ -0,0 +1,46 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +class Base { +public: + int foo(int x, int y) { return 1; } + char bar(int x, char y) { return 2; } + void dat() {} + static int sfunc(char, int, float) { return 3; } +}; + +class Derived: public Base { +protected: + int dImpl() { return 1; } +public: + float baz(float b) { return b + 1.0; } +}; + +@interface Thingy: NSObject { +} +- (id)init; +- (id)fooWithBar: (int)bar andBaz:(id)baz; +@end + +@implementation Thingy { +} +- (id)init { + return (self = [super init]); +} +- (id)fooWithBar: (int)bar andBaz:(id)baz { + return nil; +} +@end + +int main() { + Derived d; + Thingy *thingy = [[Thingy alloc] init]; + return 0; // set breakpoint here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py new file mode 100644 index 00000000000..32202acbe07 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py @@ -0,0 +1,45 @@ +""" +Test Debugger APIs. +""" + +import lldb + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DebuggerAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + def test_debugger_api_boundary_condition(self): + """Exercise SBDebugger APIs with boundary conditions.""" + self.dbg.HandleCommand(None) + self.dbg.SetDefaultArchitecture(None) + self.dbg.GetScriptingLanguage(None) + self.dbg.CreateTarget(None) + self.dbg.CreateTarget(None, None, None, True, lldb.SBError()) + self.dbg.CreateTargetWithFileAndTargetTriple(None, None) + self.dbg.CreateTargetWithFileAndArch(None, None) + self.dbg.FindTargetWithFileAndArch(None, None) + self.dbg.SetInternalVariable(None, None, None) + self.dbg.GetInternalVariableValue(None, None) + # FIXME (filcab): We must first allow for the swig bindings to know if + # a Python callback is set. (Check python-typemaps.swig) + # self.dbg.SetLoggingCallback(None) + self.dbg.SetPrompt(None) + self.dbg.SetCurrentPlatform(None) + self.dbg.SetCurrentPlatformSDKRoot(None) + + fresh_dbg = lldb.SBDebugger() + self.assertEquals(len(fresh_dbg), 0) + + @add_test_categories(['pyapi']) + def test_debugger_delete_invalid_target(self): + """SBDebugger.DeleteTarget() should not crash LLDB given and invalid target.""" + target = lldb.SBTarget() + self.assertFalse(target.IsValid()) + self.dbg.DeleteTarget(target) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py new file mode 100644 index 00000000000..e00206587ed --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py @@ -0,0 +1,398 @@ +""" +Test lldb Python API object's default constructor and make sure it is invalid +after initial construction. + +There are also some cases of boundary condition testings sprinkled throughout +the tests where None is passed to SB API which expects (const char *) in the +C++ API counterpart. Passing None should not crash lldb! + +There are three exceptions to the above general rules, though; API objects +SBCommadnReturnObject, SBStream, and SBSymbolContextList, are all valid objects +after default construction. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class APIDefaultConstructorTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + def test_SBAddress(self): + obj = lldb.SBAddress() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_address + sb_address.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBBlock(self): + obj = lldb.SBBlock() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_block + sb_block.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBBreakpoint(self): + obj = lldb.SBBreakpoint() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_breakpoint + sb_breakpoint.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBBreakpointLocation(self): + obj = lldb.SBBreakpointLocation() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_breakpointlocation + sb_breakpointlocation.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBBreakpointName(self): + obj = lldb.SBBreakpointName() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_breakpointname + sb_breakpointname.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBBroadcaster(self): + obj = lldb.SBBroadcaster() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_broadcaster + sb_broadcaster.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBCommandReturnObject(self): + """SBCommandReturnObject object is valid after default construction.""" + obj = lldb.SBCommandReturnObject() + if self.TraceOn(): + print(obj) + self.assertTrue(obj) + + @add_test_categories(['pyapi']) + def test_SBCommunication(self): + obj = lldb.SBCommunication() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_communication + sb_communication.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBCompileUnit(self): + obj = lldb.SBCompileUnit() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_compileunit + sb_compileunit.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBDebugger(self): + obj = lldb.SBDebugger() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_debugger + sb_debugger.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + # darwin: This test passes with swig 3.0.2, fails w/3.0.5 other tests fail + # with 2.0.12 http://llvm.org/pr23488 + def test_SBError(self): + obj = lldb.SBError() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_error + sb_error.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBEvent(self): + obj = lldb.SBEvent() + # This is just to test that typemap, as defined in lldb.swig, works. + obj2 = lldb.SBEvent(0, "abc") + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_event + sb_event.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBFileSpec(self): + obj = lldb.SBFileSpec() + # This is just to test that FileSpec(None) does not crash. + obj2 = lldb.SBFileSpec(None, True) + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_filespec + sb_filespec.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBFrame(self): + obj = lldb.SBFrame() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_frame + sb_frame.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBFunction(self): + obj = lldb.SBFunction() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_function + sb_function.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBFile(self): + sbf = lldb.SBFile() + self.assertFalse(sbf.IsValid()) + self.assertFalse(bool(sbf)) + e, n = sbf.Write(b'foo') + self.assertTrue(e.Fail()) + self.assertEqual(n, 0) + buffer = bytearray(100) + e, n = sbf.Read(buffer) + self.assertEqual(n, 0) + self.assertTrue(e.Fail()) + + @add_test_categories(['pyapi']) + def test_SBInstruction(self): + obj = lldb.SBInstruction() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_instruction + sb_instruction.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBInstructionList(self): + obj = lldb.SBInstructionList() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_instructionlist + sb_instructionlist.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBLineEntry(self): + obj = lldb.SBLineEntry() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_lineentry + sb_lineentry.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBListener(self): + obj = lldb.SBListener() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_listener + sb_listener.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + # Py3 asserts due to a bug in SWIG. Trying to upstream a patch to fix + # this in 3.0.8 + @skipIf(py_version=['>=', (3, 0)], swig_version=['<', (3, 0, 8)]) + def test_SBModule(self): + obj = lldb.SBModule() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_module + sb_module.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBProcess(self): + obj = lldb.SBProcess() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_process + sb_process.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBProcessInfo(self): + obj = lldb.SBProcessInfo() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_process_info + sb_process_info.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBSection(self): + obj = lldb.SBSection() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_section + sb_section.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBStream(self): + """SBStream object is valid after default construction.""" + obj = lldb.SBStream() + if self.TraceOn(): + print(obj) + self.assertTrue(obj) + + @add_test_categories(['pyapi']) + def test_SBStringList(self): + obj = lldb.SBStringList() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_stringlist + sb_stringlist.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBSymbol(self): + obj = lldb.SBSymbol() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_symbol + sb_symbol.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBSymbolContext(self): + obj = lldb.SBSymbolContext() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_symbolcontext + sb_symbolcontext.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBSymbolContextList(self): + """SBSymbolContextList object is valid after default construction.""" + obj = lldb.SBSymbolContextList() + if self.TraceOn(): + print(obj) + self.assertTrue(obj) + + @add_test_categories(['pyapi']) + def test_SBTarget(self): + obj = lldb.SBTarget() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_target + sb_target.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBThread(self): + obj = lldb.SBThread() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_thread + sb_thread.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBType(self): + try: + obj = lldb.SBType() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # If we reach here, the test fails. + self.fail("lldb.SBType() should fail, not succeed!") + except: + # Exception is expected. + return + + # Unreachable code because lldb.SBType() should fail. + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_type + sb_type.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBTypeList(self): + """SBTypeList object is valid after default construction.""" + obj = lldb.SBTypeList() + if self.TraceOn(): + print(obj) + self.assertTrue(obj) + + @add_test_categories(['pyapi']) + def test_SBValue(self): + obj = lldb.SBValue() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_value + sb_value.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBValueList(self): + obj = lldb.SBValueList() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_valuelist + sb_valuelist.fuzz_obj(obj) + + @add_test_categories(['pyapi']) + def test_SBWatchpoint(self): + obj = lldb.SBWatchpoint() + if self.TraceOn(): + print(obj) + self.assertFalse(obj) + # Do fuzz testing on the invalid obj, it should not crash lldb. + import sb_watchpoint + sb_watchpoint.fuzz_obj(obj) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py new file mode 100644 index 00000000000..8f9665d3a73 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py @@ -0,0 +1,23 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import sys +import lldb + + +def fuzz_obj(obj): + obj.GetFileAddress() + obj.GetLoadAddress(lldb.SBTarget()) + obj.SetLoadAddress(0xffff, lldb.SBTarget()) + obj.OffsetAddress(sys.maxsize) + obj.GetDescription(lldb.SBStream()) + obj.GetSection() + obj.GetSymbolContext(lldb.eSymbolContextEverything) + obj.GetModule() + obj.GetCompileUnit() + obj.GetFunction() + obj.GetBlock() + obj.GetSymbol() + obj.GetLineEntry() + obj.Clear() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py new file mode 100644 index 00000000000..299ca08910c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py @@ -0,0 +1,17 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.IsInlined() + obj.GetInlinedName() + obj.GetInlinedCallSiteFile() + obj.GetInlinedCallSiteLine() + obj.GetInlinedCallSiteColumn() + obj.GetParent() + obj.GetSibling() + obj.GetFirstChild() + obj.GetDescription(lldb.SBStream()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py new file mode 100644 index 00000000000..3bdf5879d30 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py @@ -0,0 +1,37 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import sys +import lldb + + +def fuzz_obj(obj): + obj.GetID() + obj.ClearAllBreakpointSites() + obj.FindLocationByAddress(sys.maxsize) + obj.FindLocationIDByAddress(sys.maxsize) + obj.FindLocationByID(0) + obj.GetLocationAtIndex(0) + obj.SetEnabled(True) + obj.IsEnabled() + obj.GetHitCount() + obj.SetIgnoreCount(1) + obj.GetIgnoreCount() + obj.SetCondition("i >= 10") + obj.GetCondition() + obj.SetThreadID(0) + obj.GetThreadID() + obj.SetThreadIndex(0) + obj.GetThreadIndex() + obj.SetThreadName("worker thread") + obj.GetThreadName() + obj.SetQueueName("my queue") + obj.GetQueueName() + obj.SetScriptCallbackFunction(None) + obj.SetScriptCallbackBody(None) + obj.GetNumResolvedLocations() + obj.GetNumLocations() + obj.GetDescription(lldb.SBStream()) + for bp_loc in obj: + s = str(bp_loc) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py new file mode 100644 index 00000000000..5ac1c065efe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py @@ -0,0 +1,28 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetAddress() + obj.GetLoadAddress() + obj.SetEnabled(True) + obj.IsEnabled() + obj.SetCondition("i >= 10") + obj.GetCondition() + obj.SetThreadID(0) + obj.GetThreadID() + obj.SetThreadIndex(0) + obj.GetThreadIndex() + obj.SetThreadName("worker thread") + obj.GetThreadName() + obj.SetQueueName("my queue") + obj.GetQueueName() + obj.IsResolved() + obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose) + breakpoint = obj.GetBreakpoint() + # Do fuzz testing on the breakpoint obj, it should not crash lldb. + import sb_breakpoint + sb_breakpoint.fuzz_obj(breakpoint) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointname.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointname.py new file mode 100644 index 00000000000..b32ed0d11aa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointname.py @@ -0,0 +1,41 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.IsValid() + obj.GetName() + obj.SetEnabled(True) + obj.IsEnabled() + obj.SetOneShot(True) + obj.IsOneShot() + obj.SetIgnoreCount(1) + obj.GetIgnoreCount() + obj.SetCondition("1 == 2") + obj.GetCondition() + obj.SetAutoContinue(False) + obj.GetAutoContinue() + obj.SetThreadID(0x1234) + obj.GetThreadID() + obj.SetThreadIndex(10) + obj.GetThreadIndex() + obj.SetThreadName("AThread") + obj.GetThreadName() + obj.SetQueueName("AQueue") + obj.GetQueueName() + obj.SetScriptCallbackFunction("AFunction") + commands = lldb.SBStringList() + obj.SetCommandLineCommands(commands) + obj.GetCommandLineCommands(commands) + obj.SetScriptCallbackBody("Insert Python Code here") + obj.GetAllowList() + obj.SetAllowList(False) + obj.GetAllowDelete() + obj.SetAllowDelete(False) + obj.GetAllowDisable() + obj.SetAllowDisable(False) + stream = lldb.SBStream() + obj.GetDescription(stream) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py new file mode 100644 index 00000000000..59491a762db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py @@ -0,0 +1,20 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.BroadcastEventByType(lldb.eBreakpointEventTypeInvalidType, True) + obj.BroadcastEvent(lldb.SBEvent(), False) + listener = lldb.SBListener("fuzz_testing") + obj.AddInitialEventsToListener(listener, 0xffffffff) + obj.AddInitialEventsToListener(listener, 0) + obj.AddListener(listener, 0xffffffff) + obj.AddListener(listener, 0) + obj.GetName() + obj.EventTypeHasListeners(0) + obj.RemoveListener(listener, 0xffffffff) + obj.RemoveListener(listener, 0) + obj.Clear() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py new file mode 100644 index 00000000000..1f5aefbc0d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py @@ -0,0 +1,28 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + broadcaster = obj.GetBroadcaster() + # Do fuzz testing on the broadcaster obj, it should not crash lldb. + import sb_broadcaster + sb_broadcaster.fuzz_obj(broadcaster) + obj.AdoptFileDesriptor(0, False) + obj.AdoptFileDesriptor(1, False) + obj.AdoptFileDesriptor(2, False) + obj.Connect("file:/tmp/myfile") + obj.Connect(None) + obj.Disconnect() + obj.IsConnected() + obj.GetCloseOnEOF() + obj.SetCloseOnEOF(True) + obj.SetCloseOnEOF(False) + #obj.Write(None, sys.maxint, None) + #obj.Read(None, sys.maxint, 0xffffffff, None) + obj.ReadThreadStart() + obj.ReadThreadStop() + obj.ReadThreadIsRunning() + obj.SetReadThreadBytesReceivedCallback(None, None) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py new file mode 100644 index 00000000000..4caef33a75f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py @@ -0,0 +1,16 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetFileSpec() + obj.GetNumLineEntries() + obj.GetLineEntryAtIndex(0xffffffff) + obj.FindLineEntryIndex(0, 0xffffffff, None) + obj.GetDescription(lldb.SBStream()) + len(obj) + for line_entry in obj: + s = str(line_entry) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py new file mode 100644 index 00000000000..e6267c8475e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py @@ -0,0 +1,63 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.SetAsync(True) + obj.SetAsync(False) + obj.GetAsync() + obj.SkipLLDBInitFiles(True) + obj.SetInputFileHandle(None, True) + obj.SetOutputFileHandle(None, True) + obj.SetErrorFileHandle(None, True) + obj.GetInputFileHandle() + obj.GetOutputFileHandle() + obj.GetErrorFileHandle() + obj.GetCommandInterpreter() + obj.HandleCommand("nothing here") + listener = obj.GetListener() + try: + obj.HandleProcessEvent(lldb.SBProcess(), lldb.SBEvent(), None, None) + except Exception: + pass + obj.CreateTargetWithFileAndTargetTriple("a.out", "A-B-C") + obj.CreateTargetWithFileAndArch("b.out", "arm") + obj.CreateTarget("c.out") + obj.DeleteTarget(lldb.SBTarget()) + obj.GetTargetAtIndex(0xffffffff) + obj.FindTargetWithProcessID(0) + obj.FindTargetWithFileAndArch("a.out", "arm") + obj.GetNumTargets() + obj.GetSelectedTarget() + obj.GetNumPlatforms() + obj.GetPlatformAtIndex(0xffffffff) + obj.GetNumAvailablePlatforms() + obj.GetAvailablePlatformInfoAtIndex(0xffffffff) + obj.GetSourceManager() + obj.SetSelectedTarget(lldb.SBTarget()) + obj.SetCurrentPlatformSDKRoot("tmp/sdk-root") + try: + obj.DispatchInput(None) + except Exception: + pass + obj.DispatchInputInterrupt() + obj.DispatchInputEndOfFile() + obj.GetInstanceName() + obj.GetDescription(lldb.SBStream()) + obj.GetTerminalWidth() + obj.SetTerminalWidth(0xffffffff) + obj.GetID() + obj.GetPrompt() + obj.SetPrompt("Hi, Mom!") + obj.GetScriptLanguage() + obj.SetScriptLanguage(lldb.eScriptLanguageNone) + obj.SetScriptLanguage(lldb.eScriptLanguagePython) + obj.GetCloseInputOnEOF() + obj.SetCloseInputOnEOF(True) + obj.SetCloseInputOnEOF(False) + obj.Clear() + for target in obj: + s = str(target) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py new file mode 100644 index 00000000000..7d14c3e5844 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py @@ -0,0 +1,25 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetCString() + obj.Fail() + obj.Success() + obj.GetError() + obj.GetType() + obj.SetError(5, lldb.eErrorTypeGeneric) + obj.SetErrorToErrno() + obj.SetErrorToGenericError() + obj.SetErrorString("xyz") + obj.SetErrorString(None) + obj.SetErrorStringWithFormat("%s!", "error") + obj.SetErrorStringWithFormat(None) + obj.SetErrorStringWithFormat("error") + obj.SetErrorStringWithFormat("%s %s", "warning", "danger") + obj.SetErrorStringWithFormat("%s %s %s", "danger", "will", "robinson") + obj.GetDescription(lldb.SBStream()) + obj.Clear() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py new file mode 100644 index 00000000000..aaf71d03051 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py @@ -0,0 +1,17 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetDataFlavor() + obj.GetType() + broadcaster = obj.GetBroadcaster() + # Do fuzz testing on the broadcaster obj, it should not crash lldb. + import sb_broadcaster + sb_broadcaster.fuzz_obj(broadcaster) + obj.BroadcasterMatchesRef(broadcaster) + obj.GetDescription(lldb.SBStream()) + obj.Clear() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py new file mode 100644 index 00000000000..4ab5c49c37e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py @@ -0,0 +1,14 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.Exists() + obj.ResolveExecutableLocation() + obj.GetFilename() + obj.GetDirectory() + obj.GetPath(None, 0) + obj.GetDescription(lldb.SBStream()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py new file mode 100644 index 00000000000..b81f1af7b0e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py @@ -0,0 +1,40 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetFrameID() + obj.GetPC() + obj.SetPC(0xffffffff) + obj.GetSP() + obj.GetFP() + obj.GetPCAddress() + obj.GetSymbolContext(0) + obj.GetModule() + obj.GetCompileUnit() + obj.GetFunction() + obj.GetSymbol() + obj.GetBlock() + obj.GetFunctionName() + obj.IsInlined() + obj.EvaluateExpression("x + y") + obj.EvaluateExpression("x + y", lldb.eDynamicCanRunTarget) + obj.GetFrameBlock() + obj.GetLineEntry() + obj.GetThread() + obj.Disassemble() + obj.GetVariables(True, True, True, True) + obj.GetVariables(True, True, True, False, lldb.eDynamicCanRunTarget) + obj.GetRegisters() + obj.FindVariable("my_var") + obj.FindVariable("my_var", lldb.eDynamicCanRunTarget) + obj.FindValue("your_var", lldb.eValueTypeVariableGlobal) + obj.FindValue( + "your_var", + lldb.eValueTypeVariableStatic, + lldb.eDynamicCanRunTarget) + obj.GetDescription(lldb.SBStream()) + obj.Clear() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py new file mode 100644 index 00000000000..764fb373b62 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py @@ -0,0 +1,19 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetName() + obj.GetMangledName() + obj.GetInstructions(lldb.SBTarget()) + sa = obj.GetStartAddress() + ea = obj.GetEndAddress() + # Do fuzz testing on the address obj, it should not crash lldb. + import sb_address + sb_address.fuzz_obj(sa) + sb_address.fuzz_obj(ea) + obj.GetPrologueByteSize + obj.GetDescription(lldb.SBStream()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py new file mode 100644 index 00000000000..fbfb2313688 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py @@ -0,0 +1,19 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetAddress() + obj.GetByteSize() + obj.DoesBranch() + try: + obj.Print(None) + except Exception: + pass + obj.GetDescription(lldb.SBStream()) + obj.EmulateWithFrame(lldb.SBFrame(), 0) + obj.DumpEmulation("armv7") + obj.TestEmulation(lldb.SBStream(), "my-file") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py new file mode 100644 index 00000000000..9e7ebf927f4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py @@ -0,0 +1,20 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetSize() + obj.GetInstructionAtIndex(0xffffffff) + obj.AppendInstruction(lldb.SBInstruction()) + try: + obj.Print(None) + except Exception: + pass + obj.GetDescription(lldb.SBStream()) + obj.DumpEmulationForAllInstructions("armv7") + obj.Clear() + for inst in obj: + s = str(inst) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py new file mode 100644 index 00000000000..53761a0c1fa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py @@ -0,0 +1,14 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetStartAddress() + obj.GetEndAddress() + obj.GetFileSpec() + obj.GetLine() + obj.GetColumn() + obj.GetDescription(lldb.SBStream()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py new file mode 100644 index 00000000000..b40cfd4d1c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py @@ -0,0 +1,23 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.AddEvent(lldb.SBEvent()) + obj.StartListeningForEvents(lldb.SBBroadcaster(), 0xffffffff) + obj.StopListeningForEvents(lldb.SBBroadcaster(), 0xffffffff) + event = lldb.SBEvent() + broadcaster = lldb.SBBroadcaster() + obj.WaitForEvent(5, event) + obj.WaitForEventForBroadcaster(5, broadcaster, event) + obj.WaitForEventForBroadcasterWithType(5, broadcaster, 0xffffffff, event) + obj.PeekAtNextEvent(event) + obj.PeekAtNextEventForBroadcaster(broadcaster, event) + obj.PeekAtNextEventForBroadcasterWithType(broadcaster, 0xffffffff, event) + obj.GetNextEvent(event) + obj.GetNextEventForBroadcaster(broadcaster, event) + obj.GetNextEventForBroadcasterWithType(broadcaster, 0xffffffff, event) + obj.HandleBroadcastEvent(event) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py new file mode 100644 index 00000000000..175550a5a0f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py @@ -0,0 +1,30 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import sys +import lldb + + +def fuzz_obj(obj): + obj.GetFileSpec() + obj.GetPlatformFileSpec() + obj.SetPlatformFileSpec(lldb.SBFileSpec()) + obj.GetUUIDString() + obj.ResolveFileAddress(sys.maxsize) + obj.ResolveSymbolContextForAddress(lldb.SBAddress(), 0) + obj.GetDescription(lldb.SBStream()) + obj.GetNumSymbols() + obj.GetSymbolAtIndex(sys.maxsize) + sc_list = obj.FindFunctions("my_func") + sc_list = obj.FindFunctions("my_func", lldb.eFunctionNameTypeAny) + obj.FindGlobalVariables(lldb.SBTarget(), "my_global_var", 1) + for section in obj.section_iter(): + s = str(section) + for symbol in obj.symbol_in_section_iter(lldb.SBSection()): + s = str(symbol) + for symbol in obj: + s = str(symbol) + obj.GetAddressByteSize() + obj.GetByteOrder() + obj.GetTriple() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py new file mode 100644 index 00000000000..93e43d4433f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py @@ -0,0 +1,53 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetTarget() + obj.GetByteOrder() + obj.PutSTDIN("my data") + obj.GetSTDOUT(6) + obj.GetSTDERR(6) + event = lldb.SBEvent() + try: + obj.ReportEventState(event, None) + except Exception: + pass + obj.AppendEventStateReport(event, lldb.SBCommandReturnObject()) + error = lldb.SBError() + obj.RemoteAttachToProcessWithID(123, error) + obj.RemoteLaunch(None, None, None, None, None, None, 0, False, error) + obj.GetNumThreads() + obj.GetThreadAtIndex(0) + obj.GetThreadByID(0) + obj.GetSelectedThread() + obj.SetSelectedThread(lldb.SBThread()) + obj.SetSelectedThreadByID(0) + obj.GetState() + obj.GetExitStatus() + obj.GetExitDescription() + obj.GetProcessID() + obj.GetAddressByteSize() + obj.Destroy() + obj.Continue() + obj.Stop() + obj.Kill() + obj.Detach() + obj.Signal(7) + obj.ReadMemory(0x0000ffff, 10, error) + obj.WriteMemory(0x0000ffff, "hi data", error) + obj.ReadCStringFromMemory(0x0, 128, error) + obj.ReadUnsignedFromMemory(0xff, 4, error) + obj.ReadPointerFromMemory(0xff, error) + obj.GetBroadcaster() + obj.GetDescription(lldb.SBStream()) + obj.LoadImage(lldb.SBFileSpec(), error) + obj.UnloadImage(0) + obj.Clear() + obj.GetNumSupportedHardwareWatchpoints(error) + for thread in obj: + s = str(thread) + len(obj) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process_info.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process_info.py new file mode 100644 index 00000000000..0c4562f9be9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process_info.py @@ -0,0 +1,21 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.IsValid() + obj.GetName() + obj.GetExecutableFile() + obj.GetProcessID() + obj.GetUserID() + obj.GetGroupID() + obj.UserIDIsValid() + obj.GroupIDIsValid() + obj.GetEffectiveUserID() + obj.GetEffectiveGroupID() + obj.EffectiveUserIDIsValid() + obj.EffectiveGroupIDIsValid() + obj.GetParentProcessID() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py new file mode 100644 index 00000000000..d6118186b4b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py @@ -0,0 +1,23 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.IsValid() + obj.GetName() + obj.FindSubSection("hello_section_name") + obj.GetNumSubSections() + obj.GetSubSectionAtIndex(600) + obj.GetFileAddress() + obj.GetByteSize() + obj.GetFileOffset() + obj.GetFileByteSize() + obj.GetSectionData(1000, 100) + obj.GetSectionType() + obj.GetDescription(lldb.SBStream()) + for subsec in obj: + s = str(subsec) + len(obj) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py new file mode 100644 index 00000000000..015de7aa7ac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py @@ -0,0 +1,17 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.AppendString("another string") + obj.AppendString(None) + obj.AppendList(None, 0) + obj.AppendList(lldb.SBStringList()) + obj.GetSize() + obj.GetStringAtIndex(0xffffffff) + obj.Clear() + for n in obj: + s = str(n) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py new file mode 100644 index 00000000000..ce942a9daa4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py @@ -0,0 +1,16 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetName() + obj.GetMangledName() + obj.GetInstructions(lldb.SBTarget()) + obj.GetStartAddress() + obj.GetEndAddress() + obj.GetPrologueByteSize() + obj.GetType() + obj.GetDescription(lldb.SBStream()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py new file mode 100644 index 00000000000..e46e4714be0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py @@ -0,0 +1,15 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetModule() + obj.GetCompileUnit() + obj.GetFunction() + obj.GetBlock() + obj.GetLineEntry() + obj.GetSymbol() + obj.GetDescription(lldb.SBStream()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py new file mode 100644 index 00000000000..3b521dcf6dd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py @@ -0,0 +1,65 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetProcess() + listener = lldb.SBListener() + error = lldb.SBError() + obj.Launch(listener, None, None, None, None, None, None, 0, True, error) + obj.LaunchSimple(None, None, None) + obj.AttachToProcessWithID(listener, 123, error) + obj.AttachToProcessWithName(listener, 'lldb', False, error) + obj.ConnectRemote(listener, "connect://to/here", None, error) + obj.GetExecutable() + obj.GetNumModules() + obj.GetModuleAtIndex(0xffffffff) + obj.GetDebugger() + filespec = lldb.SBFileSpec() + obj.FindModule(filespec) + sc_list = obj.FindFunctions("the_func") + sc_list = obj.FindFunctions("the_func", lldb.eFunctionNameTypeAny) + obj.FindFirstType("dont_care") + obj.FindTypes("dont_care") + obj.FindFirstType(None) + obj.GetInstructions(lldb.SBAddress(), bytearray()) + obj.GetSourceManager() + obj.FindGlobalVariables("my_global_var", 1) + address = obj.ResolveLoadAddress(0xffff) + obj.ResolveSymbolContextForAddress(address, 0) + obj.BreakpointCreateByLocation("filename", 20) + obj.BreakpointCreateByLocation(filespec, 20) + obj.BreakpointCreateByName("func", None) + obj.BreakpointCreateByRegex("func.", None) + obj.BreakpointCreateByAddress(0xf0f0) + obj.GetNumBreakpoints() + obj.GetBreakpointAtIndex(0) + obj.BreakpointDelete(0) + obj.FindBreakpointByID(0) + obj.EnableAllBreakpoints() + obj.DisableAllBreakpoints() + obj.DeleteAllBreakpoints() + obj.GetNumWatchpoints() + obj.GetWatchpointAtIndex(0) + obj.DeleteWatchpoint(0) + obj.FindWatchpointByID(0) + obj.EnableAllWatchpoints() + obj.DisableAllWatchpoints() + obj.DeleteAllWatchpoints() + obj.GetAddressByteSize() + obj.GetByteOrder() + obj.GetTriple() + error = lldb.SBError() + obj.WatchAddress(123, 8, True, True, error) + obj.GetBroadcaster() + obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelBrief) + obj.Clear() + for module in obj.module_iter(): + s = str(module) + for bp in obj.breakpoint_iter(): + s = str(bp) + for wp in obj.watchpoint_iter(): + s = str(wp) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py new file mode 100644 index 00000000000..0e5f9445db0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py @@ -0,0 +1,38 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetStopReason() + obj.GetStopReasonDataCount() + obj.GetStopReasonDataAtIndex(100) + obj.GetStopDescription(256) + obj.GetThreadID() + obj.GetIndexID() + obj.GetName() + obj.GetQueueName() + obj.StepOver(lldb.eOnlyDuringStepping) + obj.StepInto(lldb.eOnlyDuringStepping) + obj.StepOut() + frame = lldb.SBFrame() + obj.StepOutOfFrame(frame) + obj.StepInstruction(True) + filespec = lldb.SBFileSpec() + obj.StepOverUntil(frame, filespec, 1234) + obj.RunToAddress(0xabcd) + obj.Suspend() + obj.Resume() + obj.IsSuspended() + obj.GetNumFrames() + obj.GetFrameAtIndex(200) + obj.GetSelectedFrame() + obj.SetSelectedFrame(999) + obj.GetProcess() + obj.GetDescription(lldb.SBStream()) + obj.Clear() + for frame in obj: + s = str(frame) + len(obj) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py new file mode 100644 index 00000000000..54ab482484f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py @@ -0,0 +1,22 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetName() + obj.GetByteSize() + # obj.GetEncoding(5) + obj.GetNumberChildren(True) + member = lldb.SBTypeMember() + obj.GetChildAtIndex(True, 0, member) + obj.GetChildIndexForName(True, "_member_field") + obj.IsAPointerType() + obj.GetPointeeType() + obj.GetDescription(lldb.SBStream()) + obj.IsPointerType(None) + lldb.SBType.IsPointerType(None) + for child_type in obj: + s = str(child_type) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py new file mode 100644 index 00000000000..9e31a70a79b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py @@ -0,0 +1,67 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetError() + obj.GetID() + obj.GetName() + obj.GetTypeName() + obj.GetByteSize() + obj.IsInScope() + obj.GetFormat() + obj.SetFormat(lldb.eFormatBoolean) + obj.GetValue() + obj.GetValueType() + obj.GetValueDidChange() + obj.GetSummary() + obj.GetObjectDescription() + obj.GetLocation() + obj.SetValueFromCString("my_new_value") + obj.GetChildAtIndex(1) + obj.GetChildAtIndex(2, lldb.eNoDynamicValues, False) + obj.GetIndexOfChildWithName("my_first_child") + obj.GetChildMemberWithName("my_first_child") + obj.GetChildMemberWithName("my_first_child", lldb.eNoDynamicValues) + obj.GetNumChildren() + obj.GetOpaqueType() + obj.Dereference() + obj.TypeIsPointerType() + stream = lldb.SBStream() + obj.GetDescription(stream) + obj.GetExpressionPath(stream) + obj.GetExpressionPath(stream, True) + error = lldb.SBError() + obj.Watch(True, True, False, error) + obj.WatchPointee(True, False, True, error) + for child_val in obj: + s = str(child_val) + error = lldb.SBError() + obj.GetValueAsSigned(error, 0) + obj.GetValueAsUnsigned(error, 0) + obj.GetValueAsSigned(0) + obj.GetValueAsUnsigned(0) + obj.GetDynamicValue(lldb.eNoDynamicValues) + obj.GetStaticValue() + obj.IsDynamic() + invalid_type = lldb.SBType() + obj.CreateChildAtOffset("a", 12, invalid_type) + obj.Cast(invalid_type) + obj.CreateValueFromExpression("pt->x", "pt->x") + obj.CreateValueFromAddress("x", 0x123, invalid_type) + invalid_data = lldb.SBData() + obj.CreateValueFromData("x", invalid_data, invalid_type) + obj.GetValueForExpressionPath("[0]") + obj.AddressOf() + obj.GetLoadAddress() + obj.GetAddress() + obj.GetPointeeData(0, 1) + obj.GetData() + obj.GetTarget() + obj.GetProcess() + obj.GetThread() + obj.GetFrame() + obj.GetType() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py new file mode 100644 index 00000000000..f20c8775249 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py @@ -0,0 +1,14 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.Append(lldb.SBValue()) + obj.GetSize() + obj.GetValueAtIndex(100) + obj.FindValueObjectByUID(200) + for val in obj: + s = str(val) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py new file mode 100644 index 00000000000..8aa38126ad4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py @@ -0,0 +1,21 @@ +""" +Fuzz tests an object after the default construction to make sure it does not crash lldb. +""" + +import lldb + + +def fuzz_obj(obj): + obj.GetID() + obj.IsValid() + obj.GetHardwareIndex() + obj.GetWatchAddress() + obj.GetWatchSize() + obj.SetEnabled(True) + obj.IsEnabled() + obj.GetHitCount() + obj.GetIgnoreCount() + obj.SetIgnoreCount(5) + obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose) + obj.SetCondition("shouldWeStop()") + obj.GetCondition() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py new file mode 100644 index 00000000000..8e2bc4ac45d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py @@ -0,0 +1,58 @@ +""" +Use lldb Python API to disassemble raw machine code bytes +""" + +from __future__ import print_function + + +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DisassembleRawDataTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + @no_debug_info_test + @skipIfRemote + def test_disassemble_raw_data(self): + """Test disassembling raw bytes with the API.""" + # Create a target from the debugger. + arch = self.getArchitecture() + if re.match("mips*el", arch): + target = self.dbg.CreateTargetWithFileAndTargetTriple("", "mipsel") + raw_bytes = bytearray([0x21, 0xf0, 0xa0, 0x03]) + elif re.match("mips", arch): + target = self.dbg.CreateTargetWithFileAndTargetTriple("", "mips") + raw_bytes = bytearray([0x03, 0xa0, 0xf0, 0x21]) + elif re.match("powerpc64le", arch): + target = self.dbg.CreateTargetWithFileAndTargetTriple("", "powerpc64le") + raw_bytes = bytearray([0x00, 0x00, 0x80, 0x38]) + else: + target = self.dbg.CreateTargetWithFileAndTargetTriple("", "x86_64") + raw_bytes = bytearray([0x48, 0x89, 0xe5]) + + self.assertTrue(target, VALID_TARGET) + insts = target.GetInstructions(lldb.SBAddress(0, target), raw_bytes) + + inst = insts.GetInstructionAtIndex(0) + + if self.TraceOn(): + print() + print("Raw bytes: ", [hex(x) for x in raw_bytes]) + print("Disassembled%s" % str(inst)) + if re.match("mips", arch): + self.assertTrue(inst.GetMnemonic(target) == "move") + self.assertTrue(inst.GetOperands(target) == + '$' + "fp, " + '$' + "sp") + elif re.match("powerpc64le", arch): + self.assertTrue(inst.GetMnemonic(target) == "li") + self.assertTrue(inst.GetOperands(target) == "4, 0") + else: + self.assertTrue(inst.GetMnemonic(target) == "movq") + self.assertTrue(inst.GetOperands(target) == + '%' + "rsp, " + '%' + "rbp") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py new file mode 100644 index 00000000000..e4d085de7c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py @@ -0,0 +1,78 @@ +""" +Use lldb Python API to disassemble raw machine code bytes +""" + +from __future__ import print_function + +from io import StringIO +import sys + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class Disassemble_VST1_64(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + @no_debug_info_test + @skipIfLLVMTargetMissing("ARM") + def test_disassemble_invalid_vst_1_64_raw_data(self): + """Test disassembling invalid vst1.64 raw bytes with the API.""" + # Create a target from the debugger. + target = self.dbg.CreateTargetWithFileAndTargetTriple("", "thumbv7-apple-macosx") + self.assertTrue(target, VALID_TARGET) + + raw_bytes = bytearray([0xf0, 0xb5, 0x03, 0xaf, + 0x2d, 0xe9, 0x00, 0x0d, + 0xad, 0xf1, 0x40, 0x04, + 0x24, 0xf0, 0x0f, 0x04, + 0xa5, 0x46]) + + assembly = """ + push {r4, r5, r6, r7, lr} + add r7, sp, #0xc + push.w {r8, r10, r11} + sub.w r4, sp, #0x40 + bic r4, r4, #0xf + mov sp, r4 + """ + def split(s): + return [x.strip() for x in s.strip().splitlines()] + + insts = target.GetInstructions(lldb.SBAddress(), raw_bytes) + + if self.TraceOn(): + print() + for i in insts: + print("Disassembled %s" % str(i)) + + if sys.version_info.major >= 3: + sio = StringIO() + insts.Print(sio) + self.assertEqual(split(assembly), split(sio.getvalue())) + + self.assertEqual(insts.GetSize(), len(split(assembly))) + + if sys.version_info.major >= 3: + for i,asm in enumerate(split(assembly)): + inst = insts.GetInstructionAtIndex(i) + sio = StringIO() + inst.Print(sio) + self.assertEqual(asm, sio.getvalue().strip()) + + raw_bytes = bytearray([0x04, 0xf9, 0xed, 0x82]) + + insts = target.GetInstructions(lldb.SBAddress(), raw_bytes) + + inst = insts.GetInstructionAtIndex(0) + + if self.TraceOn(): + print() + print("Raw bytes: ", [hex(x) for x in raw_bytes]) + print("Disassembled%s" % str(inst)) + + self.assertTrue(inst.GetMnemonic(target) == "vst1.64") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/event/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/event/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/event/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/event/TestEvents.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/event/TestEvents.py new file mode 100644 index 00000000000..97ebe8ffc03 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/event/TestEvents.py @@ -0,0 +1,316 @@ +""" +Test lldb Python event APIs. +""" + +from __future__ import print_function + + +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +@skipIfLinux # llvm.org/pr25924, sometimes generating SIGSEGV +@skipIfDarwin +class EventAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + 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.') + + @add_test_categories(['pyapi']) + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23730 Flaky, fails ~1/10 cases") + @skipIfWindows # This is flakey on Windows AND when it fails, it hangs: llvm.org/pr38373 + @skipIfNetBSD + def test_listen_for_and_print_event(self): + """Exercise SBEvent API.""" + self.build() + exe = self.getBuildArtifact("a.out") + + self.dbg.SetAsync(True) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + + listener = lldb.SBListener("my listener") + + # Now launch the process, and do not stop at the entry point. + error = lldb.SBError() + process = target.Launch(listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error + + self.assertTrue( + process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + # Create an empty event object. + event = lldb.SBEvent() + + traceOn = self.TraceOn() + if traceOn: + lldbutil.print_stacktraces(process) + + # Create MyListeningThread class to wait for any kind of event. + import threading + + class MyListeningThread(threading.Thread): + + def run(self): + count = 0 + # Let's only try at most 4 times to retrieve any kind of event. + # After that, the thread exits. + while not count > 3: + if traceOn: + print("Try wait for event...") + if listener.WaitForEvent(5, event): + if traceOn: + desc = lldbutil.get_description(event) + print("Event description:", desc) + print("Event data flavor:", event.GetDataFlavor()) + print( + "Process state:", + lldbutil.state_type_to_str( + process.GetState())) + print() + else: + if traceOn: + print("timeout occurred waiting for event...") + count = count + 1 + listener.Clear() + return + + # Let's start the listening thread to retrieve the events. + my_thread = MyListeningThread() + my_thread.start() + + # Use Python API to continue the process. The listening thread should be + # able to receive the state changed events. + process.Continue() + + # Use Python API to kill the process. The listening thread should be + # able to receive the state changed event, too. + process.Kill() + + # Wait until the 'MyListeningThread' terminates. + my_thread.join() + + # Shouldn't we be testing against some kind of expectation here? + + @add_test_categories(['pyapi']) + @expectedFlakeyLinux("llvm.org/pr23730") # Flaky, fails ~1/100 cases + @skipIfWindows # This is flakey on Windows AND when it fails, it hangs: llvm.org/pr38373 + @skipIfNetBSD + def test_wait_for_event(self): + """Exercise SBListener.WaitForEvent() API.""" + self.build() + exe = self.getBuildArtifact("a.out") + + self.dbg.SetAsync(True) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Get the debugger listener. + listener = self.dbg.GetListener() + + # Now launch the process, and do not stop at entry point. + error = lldb.SBError() + process = target.Launch(listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error + self.assertTrue(error.Success() and process, PROCESS_IS_VALID) + + # Create an empty event object. + event = lldb.SBEvent() + self.assertFalse(event, "Event should not be valid initially") + + # Create MyListeningThread to wait for any kind of event. + import threading + + class MyListeningThread(threading.Thread): + + def run(self): + count = 0 + # Let's only try at most 3 times to retrieve any kind of event. + while not count > 3: + if listener.WaitForEvent(5, event): + #print("Got a valid event:", event) + #print("Event data flavor:", event.GetDataFlavor()) + #print("Event type:", lldbutil.state_type_to_str(event.GetType())) + listener.Clear() + return + count = count + 1 + print("Timeout: listener.WaitForEvent") + listener.Clear() + return + + # Use Python API to kill the process. The listening thread should be + # able to receive a state changed event. + process.Kill() + + # Let's start the listening thread to retrieve the event. + my_thread = MyListeningThread() + my_thread.start() + + # Wait until the 'MyListeningThread' terminates. + my_thread.join() + + self.assertTrue(event, + "My listening thread successfully received an event") + + @skipIfFreeBSD # llvm.org/pr21325 + @add_test_categories(['pyapi']) + @expectedFailureAll( + oslist=["linux"], + bugnumber="llvm.org/pr23617 Flaky, fails ~1/10 cases") + @skipIfWindows # This is flakey on Windows AND when it fails, it hangs: llvm.org/pr38373 + @expectedFlakeyNetBSD + def test_add_listener_to_broadcaster(self): + """Exercise some SBBroadcaster APIs.""" + self.build() + exe = self.getBuildArtifact("a.out") + + self.dbg.SetAsync(True) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + listener = lldb.SBListener("my listener") + + # Now launch the process, and do not stop at the entry point. + error = lldb.SBError() + process = target.Launch(listener, + None, # argv + None, # envp + None, # stdin_path + None, # stdout_path + None, # stderr_path + None, # working directory + 0, # launch flags + False, # Stop at entry + error) # error + + # Create an empty event object. + event = lldb.SBEvent() + self.assertFalse(event, "Event should not be valid initially") + + # The finite state machine for our custom listening thread, with an + # initial state of None, which means no event has been received. + # It changes to 'connected' after 'connected' event is received (for remote platforms) + # It changes to 'running' after 'running' event is received (should happen only if the + # currentstate is either 'None' or 'connected') + # It changes to 'stopped' if a 'stopped' event is received (should happen only if the + # current state is 'running'.) + self.state = None + + # Create MyListeningThread to wait for state changed events. + # By design, a "running" event is expected following by a "stopped" + # event. + import threading + + class MyListeningThread(threading.Thread): + + def run(self): + #print("Running MyListeningThread:", self) + + # Regular expression pattern for the event description. + pattern = re.compile("data = {.*, state = (.*)}$") + + # Let's only try at most 6 times to retrieve our events. + count = 0 + while True: + if listener.WaitForEvent(5, event): + desc = lldbutil.get_description(event) + #print("Event description:", desc) + match = pattern.search(desc) + if not match: + break + if match.group(1) == 'connected': + # When debugging remote targets with lldb-server, we + # first get the 'connected' event. + self.context.assertTrue(self.context.state is None) + self.context.state = 'connected' + continue + elif match.group(1) == 'running': + self.context.assertTrue( + self.context.state is None or self.context.state == 'connected') + self.context.state = 'running' + continue + elif match.group(1) == 'stopped': + self.context.assertTrue( + self.context.state == 'running') + # Whoopee, both events have been received! + self.context.state = 'stopped' + break + else: + break + print("Timeout: listener.WaitForEvent") + count = count + 1 + if count > 6: + break + listener.Clear() + return + + # Use Python API to continue the process. The listening thread should be + # able to receive the state changed events. + process.Continue() + + # Start the listening thread to receive the "running" followed by the + # "stopped" events. + my_thread = MyListeningThread() + # Supply the enclosing context so that our listening thread can access + # the 'state' variable. + my_thread.context = self + my_thread.start() + + # Wait until the 'MyListeningThread' terminates. + my_thread.join() + + # The final judgement. :-) + self.assertTrue(self.state == 'stopped', + "Both expected state changed events received") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/event/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/event/main.c new file mode 100644 index 00000000000..57369520dd1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/event/main.c @@ -0,0 +1,48 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to test the lldb Python API related to events. + +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; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py new file mode 100644 index 00000000000..19832aefee9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py @@ -0,0 +1,7 @@ +from lldbsuite.test import decorators +from lldbsuite.test import lldbinline + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, + decorators.skipIfWindows, decorators.skipIfNetBSD]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/main.mm b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/main.mm new file mode 100644 index 00000000000..365fe12dd60 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/main.mm @@ -0,0 +1,19 @@ +//===-- main.mm --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#import <Foundation/Foundation.h> +#include <vector> + +int main (int argc, char const *argv[]) +{ + std::vector<int> v{1,2,3,4,5}; + NSArray *a = @[@"Hello",@"World",@"From Me"]; + return 0; //% v = self.frame().FindVariable("v"); v0 = v.GetChildAtIndex(0); s = lldb.SBStream(); v0.GetExpressionPath(s); + //% self.runCmd("expr %s = 12" % s.GetData()); self.assertTrue(v0.GetValueAsUnsigned() == 12, "value change via expr failed") + //% a = self.frame().FindVariable("a"); a1 = a.GetChildAtIndex(1); s = lldb.SBStream(); a1.GetExpressionPath(s); + //% self.expect("po %s" % s.GetData(), substrs = ["World"]) +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/file_handle/TestFileHandle.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/file_handle/TestFileHandle.py new file mode 100644 index 00000000000..53ca64932d6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/file_handle/TestFileHandle.py @@ -0,0 +1,919 @@ +""" +Test lldb Python API for file handles. +""" + + +import os +import io +import re +import sys +from contextlib import contextmanager + +import lldb +from lldbsuite.test import lldbtest +from lldbsuite.test.decorators import * + +class OhNoe(Exception): + pass + +class BadIO(io.TextIOBase): + @property + def closed(self): + return False + def writable(self): + return True + def readable(self): + return True + def write(self, s): + raise OhNoe('OH NOE') + def read(self, n): + raise OhNoe("OH NOE") + def flush(self): + raise OhNoe('OH NOE') + +# This class will raise an exception while it's being +# converted into a C++ object by swig +class ReallyBadIO(io.TextIOBase): + def fileno(self): + return 999 + def writable(self): + raise OhNoe("OH NOE!!!") + +class MutableBool(): + def __init__(self, value): + self.value = value + def set(self, value): + self.value = bool(value) + def __bool__(self): + return self.value + +class FlushTestIO(io.StringIO): + def __init__(self, mutable_flushed, mutable_closed): + super(FlushTestIO, self).__init__() + self.mut_flushed = mutable_flushed + self.mut_closed = mutable_closed + def close(self): + self.mut_closed.set(True) + return super(FlushTestIO, self).close() + def flush(self): + self.mut_flushed.set(True) + return super(FlushTestIO, self).flush() + +@contextmanager +def replace_stdout(new): + old = sys.stdout + sys.stdout = new + try: + yield + finally: + sys.stdout = old + +def readStrippedLines(f): + def i(): + for line in f: + line = line.strip() + if line: + yield line + return list(i()) + + +class FileHandleTestCase(lldbtest.TestBase): + + NO_DEBUG_INFO_TESTCASE = True + mydir = lldbtest.Base.compute_mydir(__file__) + + # The way this class interacts with the debugger is different + # than normal. Most of these test cases will mess with the + # debugger I/O streams, so we want a fresh debugger for each + # test so those mutations don't interfere with each other. + # + # Also, the way normal tests evaluate debugger commands is + # by using a SBCommandInterpreter directly, which captures + # the output in a result object. For many of tests tests + # we want the debugger to write the output directly to + # its I/O streams like it would have done interactively. + # + # For this reason we also define handleCmd() here, even though + # it is similar to runCmd(). + + def setUp(self): + super(FileHandleTestCase, self).setUp() + self.debugger = lldb.SBDebugger.Create() + self.out_filename = self.getBuildArtifact('output') + self.in_filename = self.getBuildArtifact('input') + + def tearDown(self): + lldb.SBDebugger.Destroy(self.debugger) + super(FileHandleTestCase, self).tearDown() + for name in (self.out_filename, self.in_filename): + if os.path.exists(name): + os.unlink(name) + + # Similar to runCmd(), but this uses the per-test debugger, and it + # supports, letting the debugger just print the results instead + # of collecting them. + def handleCmd(self, cmd, check=True, collect_result=True): + assert not check or collect_result + ret = lldb.SBCommandReturnObject() + if collect_result: + interpreter = self.debugger.GetCommandInterpreter() + interpreter.HandleCommand(cmd, ret) + else: + self.debugger.HandleCommand(cmd) + self.debugger.GetOutputFile().Flush() + self.debugger.GetErrorFile().Flush() + if collect_result and check: + self.assertTrue(ret.Succeeded()) + return ret.GetOutput() + + + @add_test_categories(['pyapi']) + def test_legacy_file_out_script(self): + with open(self.out_filename, 'w') as f: + self.debugger.SetOutputFileHandle(f, False) + # scripts print to output even if you capture the results + # I'm not sure I love that behavior, but that's the way + # it's been for a long time. That's why this test works + # even with collect_result=True. + self.handleCmd('script 1+1') + self.debugger.GetOutputFileHandle().write('FOO\n') + lldb.SBDebugger.Destroy(self.debugger) + with open(self.out_filename, 'r') as f: + self.assertEqual(readStrippedLines(f), ['2', 'FOO']) + + + @add_test_categories(['pyapi']) + def test_legacy_file_out(self): + with open(self.out_filename, 'w') as f: + self.debugger.SetOutputFileHandle(f, False) + self.handleCmd('p/x 3735928559', collect_result=False, check=False) + lldb.SBDebugger.Destroy(self.debugger) + with open(self.out_filename, 'r') as f: + self.assertIn('deadbeef', f.read()) + + @add_test_categories(['pyapi']) + def test_legacy_file_err_with_get(self): + with open(self.out_filename, 'w') as f: + self.debugger.SetErrorFileHandle(f, False) + self.handleCmd('lolwut', check=False, collect_result=False) + f2 = self.debugger.GetErrorFileHandle() + f2.write('FOOBAR\n') + f2.flush() + lldb.SBDebugger.Destroy(self.debugger) + with open(self.out_filename, 'r') as f: + errors = f.read() + self.assertTrue(re.search(r'error:.*lolwut', errors)) + self.assertTrue(re.search(r'FOOBAR', errors)) + + + @add_test_categories(['pyapi']) + def test_legacy_file_err(self): + with open(self.out_filename, 'w') as f: + self.debugger.SetErrorFileHandle(f, False) + self.handleCmd('lol', check=False, collect_result=False) + lldb.SBDebugger.Destroy(self.debugger) + with open(self.out_filename, 'r') as f: + self.assertIn("is not a valid command", f.read()) + + + @add_test_categories(['pyapi']) + def test_legacy_file_error(self): + debugger = self.debugger + with open(self.out_filename, 'w') as f: + debugger.SetErrorFileHandle(f, False) + self.handleCmd('lolwut', check=False, collect_result=False) + with open(self.out_filename, 'r') as f: + errors = f.read() + self.assertTrue(re.search(r'error:.*lolwut', errors)) + + @add_test_categories(['pyapi']) + def test_sbfile_type_errors(self): + sbf = lldb.SBFile() + self.assertRaises(Exception, sbf.Write, None) + self.assertRaises(Exception, sbf.Read, None) + self.assertRaises(Exception, sbf.Read, b'this bytes is not mutable') + self.assertRaises(Exception, sbf.Write, u"ham sandwich") + self.assertRaises(Exception, sbf.Read, u"ham sandwich") + + + @add_test_categories(['pyapi']) + def test_sbfile_write_fileno(self): + with open(self.out_filename, 'w') as f: + sbf = lldb.SBFile(f.fileno(), "w", False) + self.assertTrue(sbf.IsValid()) + e, n = sbf.Write(b'FOO\nBAR') + self.assertTrue(e.Success()) + self.assertEqual(n, 7) + sbf.Close() + self.assertFalse(sbf.IsValid()) + with open(self.out_filename, 'r') as f: + self.assertEqual(readStrippedLines(f), ['FOO', 'BAR']) + + + @add_test_categories(['pyapi']) + def test_sbfile_write(self): + with open(self.out_filename, 'w') as f: + sbf = lldb.SBFile(f) + e, n = sbf.Write(b'FOO\n') + self.assertTrue(e.Success()) + self.assertEqual(n, 4) + sbf.Close() + self.assertTrue(f.closed) + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read().strip(), 'FOO') + + + @add_test_categories(['pyapi']) + def test_sbfile_read_fileno(self): + with open(self.out_filename, 'w') as f: + f.write('FOO') + with open(self.out_filename, 'r') as f: + sbf = lldb.SBFile(f.fileno(), "r", False) + self.assertTrue(sbf.IsValid()) + buffer = bytearray(100) + e, n = sbf.Read(buffer) + self.assertTrue(e.Success()) + self.assertEqual(buffer[:n], b'FOO') + + + @add_test_categories(['pyapi']) + def test_sbfile_read(self): + with open(self.out_filename, 'w') as f: + f.write('foo') + with open(self.out_filename, 'r') as f: + sbf = lldb.SBFile(f) + buf = bytearray(100) + e, n = sbf.Read(buf) + self.assertTrue(e.Success()) + self.assertEqual(n, 3) + self.assertEqual(buf[:n], b'foo') + sbf.Close() + self.assertTrue(f.closed) + + + @add_test_categories(['pyapi']) + def test_fileno_out(self): + with open(self.out_filename, 'w') as f: + sbf = lldb.SBFile(f.fileno(), "w", False) + status = self.debugger.SetOutputFile(sbf) + self.assertTrue(status.Success()) + self.handleCmd('script 1+2') + self.debugger.GetOutputFile().Write(b'quux') + + with open(self.out_filename, 'r') as f: + self.assertEqual(readStrippedLines(f), ['3', 'quux']) + + + @add_test_categories(['pyapi']) + def test_fileno_help(self): + with open(self.out_filename, 'w') as f: + sbf = lldb.SBFile(f.fileno(), "w", False) + status = self.debugger.SetOutputFile(sbf) + self.assertTrue(status.Success()) + self.handleCmd("help help", collect_result=False, check=False) + with open(self.out_filename, 'r') as f: + self.assertTrue(re.search(r'Show a list of all debugger commands', f.read())) + + + @add_test_categories(['pyapi']) + def test_help(self): + debugger = self.debugger + with open(self.out_filename, 'w') as f: + status = debugger.SetOutputFile(lldb.SBFile(f)) + self.assertTrue(status.Success()) + self.handleCmd("help help", check=False, collect_result=False) + with open(self.out_filename, 'r') as f: + self.assertIn('Show a list of all debugger commands', f.read()) + + + @add_test_categories(['pyapi']) + def test_immediate(self): + with open(self.out_filename, 'w') as f: + ret = lldb.SBCommandReturnObject() + ret.SetImmediateOutputFile(f) + interpreter = self.debugger.GetCommandInterpreter() + interpreter.HandleCommand("help help", ret) + # make sure the file wasn't closed early. + f.write("\nQUUX\n") + ret = None # call destructor and flush streams + with open(self.out_filename, 'r') as f: + output = f.read() + self.assertTrue(re.search(r'Show a list of all debugger commands', output)) + self.assertTrue(re.search(r'QUUX', output)) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_immediate_string(self): + f = io.StringIO() + ret = lldb.SBCommandReturnObject() + ret.SetImmediateOutputFile(f) + interpreter = self.debugger.GetCommandInterpreter() + interpreter.HandleCommand("help help", ret) + # make sure the file wasn't closed early. + f.write("\nQUUX\n") + ret = None # call destructor and flush streams + output = f.getvalue() + self.assertTrue(re.search(r'Show a list of all debugger commands', output)) + self.assertTrue(re.search(r'QUUX', output)) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_immediate_sbfile_string(self): + f = io.StringIO() + ret = lldb.SBCommandReturnObject() + ret.SetImmediateOutputFile(lldb.SBFile(f)) + interpreter = self.debugger.GetCommandInterpreter() + interpreter.HandleCommand("help help", ret) + output = f.getvalue() + ret = None # call destructor and flush streams + # sbfile default constructor doesn't borrow the file + self.assertTrue(f.closed) + self.assertTrue(re.search(r'Show a list of all debugger commands', output)) + + + @add_test_categories(['pyapi']) + def test_fileno_inout(self): + with open(self.in_filename, 'w') as f: + f.write("help help\n") + + with open(self.out_filename, 'w') as outf, open(self.in_filename, 'r') as inf: + + outsbf = lldb.SBFile(outf.fileno(), "w", False) + status = self.debugger.SetOutputFile(outsbf) + self.assertTrue(status.Success()) + + insbf = lldb.SBFile(inf.fileno(), "r", False) + status = self.debugger.SetInputFile(insbf) + self.assertTrue(status.Success()) + + opts = lldb.SBCommandInterpreterRunOptions() + self.debugger.RunCommandInterpreter(True, False, opts, 0, False, False) + self.debugger.GetOutputFile().Flush() + + with open(self.out_filename, 'r') as f: + self.assertTrue(re.search(r'Show a list of all debugger commands', f.read())) + + + @add_test_categories(['pyapi']) + def test_inout(self): + with open(self.in_filename, 'w') as f: + f.write("help help\n") + with open(self.out_filename, 'w') as outf, \ + open(self.in_filename, 'r') as inf: + status = self.debugger.SetOutputFile(lldb.SBFile(outf)) + self.assertTrue(status.Success()) + status = self.debugger.SetInputFile(lldb.SBFile(inf)) + self.assertTrue(status.Success()) + opts = lldb.SBCommandInterpreterRunOptions() + self.debugger.RunCommandInterpreter(True, False, opts, 0, False, False) + self.debugger.GetOutputFile().Flush() + with open(self.out_filename, 'r') as f: + output = f.read() + self.assertIn('Show a list of all debugger commands', output) + + + @add_test_categories(['pyapi']) + def test_binary_inout(self): + debugger = self.debugger + with open(self.in_filename, 'w') as f: + f.write("help help\n") + with open(self.out_filename, 'wb') as outf, \ + open(self.in_filename, 'rb') as inf: + status = debugger.SetOutputFile(lldb.SBFile(outf)) + self.assertTrue(status.Success()) + status = debugger.SetInputFile(lldb.SBFile(inf)) + self.assertTrue(status.Success()) + opts = lldb.SBCommandInterpreterRunOptions() + debugger.RunCommandInterpreter(True, False, opts, 0, False, False) + debugger.GetOutputFile().Flush() + with open(self.out_filename, 'r') as f: + output = f.read() + self.assertIn('Show a list of all debugger commands', output) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_string_inout(self): + inf = io.StringIO("help help\np/x ~0\n") + outf = io.StringIO() + status = self.debugger.SetOutputFile(lldb.SBFile(outf)) + self.assertTrue(status.Success()) + status = self.debugger.SetInputFile(lldb.SBFile(inf)) + self.assertTrue(status.Success()) + opts = lldb.SBCommandInterpreterRunOptions() + self.debugger.RunCommandInterpreter(True, False, opts, 0, False, False) + self.debugger.GetOutputFile().Flush() + output = outf.getvalue() + self.assertIn('Show a list of all debugger commands', output) + self.assertIn('0xfff', output) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_bytes_inout(self): + inf = io.BytesIO(b"help help\nhelp b\n") + outf = io.BytesIO() + status = self.debugger.SetOutputFile(lldb.SBFile(outf)) + self.assertTrue(status.Success()) + status = self.debugger.SetInputFile(lldb.SBFile(inf)) + self.assertTrue(status.Success()) + opts = lldb.SBCommandInterpreterRunOptions() + self.debugger.RunCommandInterpreter(True, False, opts, 0, False, False) + self.debugger.GetOutputFile().Flush() + output = outf.getvalue() + self.assertIn(b'Show a list of all debugger commands', output) + self.assertIn(b'Set a breakpoint', output) + + + @add_test_categories(['pyapi']) + def test_fileno_error(self): + with open(self.out_filename, 'w') as f: + + sbf = lldb.SBFile(f.fileno(), 'w', False) + status = self.debugger.SetErrorFile(sbf) + self.assertTrue(status.Success()) + + self.handleCmd('lolwut', check=False, collect_result=False) + + self.debugger.GetErrorFile().Write(b'\nzork\n') + + with open(self.out_filename, 'r') as f: + errors = f.read() + self.assertTrue(re.search(r'error:.*lolwut', errors)) + self.assertTrue(re.search(r'zork', errors)) + + + @add_test_categories(['pyapi']) + def test_replace_stdout(self): + f = io.StringIO() + with replace_stdout(f): + self.assertEqual(sys.stdout, f) + self.handleCmd('script sys.stdout.write("lol")', + collect_result=False, check=False) + self.assertEqual(sys.stdout, f) + + + @add_test_categories(['pyapi']) + def test_replace_stdout_with_nonfile(self): + debugger = self.debugger + f = io.StringIO() + with replace_stdout(f): + class Nothing(): + pass + with replace_stdout(Nothing): + self.assertEqual(sys.stdout, Nothing) + self.handleCmd('script sys.stdout.write("lol")', + check=False, collect_result=False) + self.assertEqual(sys.stdout, Nothing) + sys.stdout.write(u"FOO") + self.assertEqual(f.getvalue(), "FOO") + + + @add_test_categories(['pyapi']) + def test_sbfile_write_borrowed(self): + with open(self.out_filename, 'w') as f: + sbf = lldb.SBFile.Create(f, borrow=True) + e, n = sbf.Write(b'FOO') + self.assertTrue(e.Success()) + self.assertEqual(n, 3) + sbf.Close() + self.assertFalse(f.closed) + f.write('BAR\n') + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read().strip(), 'FOOBAR') + + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_sbfile_write_forced(self): + with open(self.out_filename, 'w') as f: + written = MutableBool(False) + orig_write = f.write + def mywrite(x): + written.set(True) + return orig_write(x) + f.write = mywrite + sbf = lldb.SBFile.Create(f, force_io_methods=True) + e, n = sbf.Write(b'FOO') + self.assertTrue(written) + self.assertTrue(e.Success()) + self.assertEqual(n, 3) + sbf.Close() + self.assertTrue(f.closed) + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read().strip(), 'FOO') + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_sbfile_write_forced_borrowed(self): + with open(self.out_filename, 'w') as f: + written = MutableBool(False) + orig_write = f.write + def mywrite(x): + written.set(True) + return orig_write(x) + f.write = mywrite + sbf = lldb.SBFile.Create(f, borrow=True, force_io_methods=True) + e, n = sbf.Write(b'FOO') + self.assertTrue(written) + self.assertTrue(e.Success()) + self.assertEqual(n, 3) + sbf.Close() + self.assertFalse(f.closed) + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read().strip(), 'FOO') + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_sbfile_write_string(self): + f = io.StringIO() + sbf = lldb.SBFile(f) + e, n = sbf.Write(b'FOO') + self.assertEqual(f.getvalue().strip(), "FOO") + self.assertTrue(e.Success()) + self.assertEqual(n, 3) + sbf.Close() + self.assertTrue(f.closed) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_string_out(self): + f = io.StringIO() + status = self.debugger.SetOutputFile(f) + self.assertTrue(status.Success()) + self.handleCmd("script 'foobar'") + self.assertEqual(f.getvalue().strip(), "'foobar'") + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_string_error(self): + f = io.StringIO() + debugger = self.debugger + status = debugger.SetErrorFile(f) + self.assertTrue(status.Success()) + self.handleCmd('lolwut', check=False, collect_result=False) + errors = f.getvalue() + self.assertTrue(re.search(r'error:.*lolwut', errors)) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_sbfile_write_bytes(self): + f = io.BytesIO() + sbf = lldb.SBFile(f) + e, n = sbf.Write(b'FOO') + self.assertEqual(f.getvalue().strip(), b"FOO") + self.assertTrue(e.Success()) + self.assertEqual(n, 3) + sbf.Close() + self.assertTrue(f.closed) + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_sbfile_read_string(self): + f = io.StringIO('zork') + sbf = lldb.SBFile(f) + buf = bytearray(100) + e, n = sbf.Read(buf) + self.assertTrue(e.Success()) + self.assertEqual(buf[:n], b'zork') + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_sbfile_read_string_one_byte(self): + f = io.StringIO('z') + sbf = lldb.SBFile(f) + buf = bytearray(1) + e, n = sbf.Read(buf) + self.assertTrue(e.Fail()) + self.assertEqual(n, 0) + self.assertEqual(e.GetCString(), "can't read less than 6 bytes from a utf8 text stream") + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_sbfile_read_bytes(self): + f = io.BytesIO(b'zork') + sbf = lldb.SBFile(f) + buf = bytearray(100) + e, n = sbf.Read(buf) + self.assertTrue(e.Success()) + self.assertEqual(buf[:n], b'zork') + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_sbfile_out(self): + with open(self.out_filename, 'w') as f: + sbf = lldb.SBFile(f) + status = self.debugger.SetOutputFile(sbf) + self.assertTrue(status.Success()) + self.handleCmd('script 2+2') + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read().strip(), '4') + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_file_out(self): + with open(self.out_filename, 'w') as f: + status = self.debugger.SetOutputFile(f) + self.assertTrue(status.Success()) + self.handleCmd('script 2+2') + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read().strip(), '4') + + + @add_test_categories(['pyapi']) + def test_sbfile_error(self): + with open(self.out_filename, 'w') as f: + sbf = lldb.SBFile(f) + status = self.debugger.SetErrorFile(sbf) + self.assertTrue(status.Success()) + self.handleCmd('lolwut', check=False, collect_result=False) + with open(self.out_filename, 'r') as f: + errors = f.read() + self.assertTrue(re.search(r'error:.*lolwut', errors)) + + + @add_test_categories(['pyapi']) + def test_file_error(self): + with open(self.out_filename, 'w') as f: + status = self.debugger.SetErrorFile(f) + self.assertTrue(status.Success()) + self.handleCmd('lolwut', check=False, collect_result=False) + with open(self.out_filename, 'r') as f: + errors = f.read() + self.assertTrue(re.search(r'error:.*lolwut', errors)) + + + @add_test_categories(['pyapi']) + def test_exceptions(self): + self.assertRaises(Exception, lldb.SBFile, None) + self.assertRaises(Exception, lldb.SBFile, "ham sandwich") + if sys.version_info[0] < 3: + self.assertRaises(Exception, lldb.SBFile, ReallyBadIO()) + else: + self.assertRaises(OhNoe, lldb.SBFile, ReallyBadIO()) + error, n = lldb.SBFile(BadIO()).Write(b"FOO") + self.assertEqual(n, 0) + self.assertTrue(error.Fail()) + self.assertIn('OH NOE', error.GetCString()) + error, n = lldb.SBFile(BadIO()).Read(bytearray(100)) + self.assertEqual(n, 0) + self.assertTrue(error.Fail()) + self.assertIn('OH NOE', error.GetCString()) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_exceptions_logged(self): + messages = list() + self.debugger.SetLoggingCallback(messages.append) + self.handleCmd('log enable lldb script') + self.debugger.SetOutputFile(lldb.SBFile(BadIO())) + self.handleCmd('script 1+1') + self.assertTrue(any('OH NOE' in msg for msg in messages)) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_flush(self): + flushed = MutableBool(False) + closed = MutableBool(False) + f = FlushTestIO(flushed, closed) + self.assertFalse(flushed) + self.assertFalse(closed) + sbf = lldb.SBFile(f) + self.assertFalse(flushed) + self.assertFalse(closed) + sbf = None + self.assertFalse(flushed) + self.assertTrue(closed) + self.assertTrue(f.closed) + + flushed = MutableBool(False) + closed = MutableBool(False) + f = FlushTestIO(flushed, closed) + self.assertFalse(flushed) + self.assertFalse(closed) + sbf = lldb.SBFile.Create(f, borrow=True) + self.assertFalse(flushed) + self.assertFalse(closed) + sbf = None + self.assertTrue(flushed) + self.assertFalse(closed) + self.assertFalse(f.closed) + + + @add_test_categories(['pyapi']) + def test_fileno_flush(self): + with open(self.out_filename, 'w') as f: + f.write("foo") + sbf = lldb.SBFile(f) + sbf.Write(b'bar') + sbf = None + self.assertTrue(f.closed) + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read(), 'foobar') + + with open(self.out_filename, 'w+') as f: + f.write("foo") + sbf = lldb.SBFile.Create(f, borrow=True) + sbf.Write(b'bar') + sbf = None + self.assertFalse(f.closed) + f.seek(0) + self.assertEqual(f.read(), 'foobar') + + + @add_test_categories(['pyapi']) + def test_close(self): + debugger = self.debugger + with open(self.out_filename, 'w') as f: + status = debugger.SetOutputFile(f) + self.assertTrue(status.Success()) + self.handleCmd("help help", check=False, collect_result=False) + # make sure the file wasn't closed early. + f.write("\nZAP\n") + lldb.SBDebugger.Destroy(debugger) + # check that output file was closed when debugger was destroyed. + with self.assertRaises(ValueError): + f.write("\nQUUX\n") + with open(self.out_filename, 'r') as f: + output = f.read() + self.assertTrue(re.search(r'Show a list of all debugger commands', output)) + self.assertTrue(re.search(r'ZAP', output)) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_stdout(self): + f = io.StringIO() + status = self.debugger.SetOutputFile(f) + self.assertTrue(status.Success()) + self.handleCmd(r"script sys.stdout.write('foobar\n')") + self.assertEqual(f.getvalue().strip().split(), ["foobar", "7"]) + + + @add_test_categories(['pyapi']) + def test_stdout_file(self): + with open(self.out_filename, 'w') as f: + status = self.debugger.SetOutputFile(f) + self.assertTrue(status.Success()) + self.handleCmd(r"script sys.stdout.write('foobar\n')") + with open(self.out_filename, 'r') as f: + # In python2 sys.stdout.write() returns None, which + # the REPL will ignore, but in python3 it will + # return the number of bytes written, which the REPL + # will print out. + lines = [x for x in f.read().strip().split() if x != "7"] + self.assertEqual(lines, ["foobar"]) + + + @add_test_categories(['pyapi']) + @skipIf(py_version=['<', (3,)]) + def test_identity(self): + + f = io.StringIO() + sbf = lldb.SBFile(f) + self.assertTrue(f is sbf.GetFile()) + sbf.Close() + self.assertTrue(f.closed) + + f = io.StringIO() + sbf = lldb.SBFile.Create(f, borrow=True) + self.assertTrue(f is sbf.GetFile()) + sbf.Close() + self.assertFalse(f.closed) + + with open(self.out_filename, 'w') as f: + sbf = lldb.SBFile(f) + self.assertTrue(f is sbf.GetFile()) + sbf.Close() + self.assertTrue(f.closed) + + with open(self.out_filename, 'w') as f: + sbf = lldb.SBFile.Create(f, borrow=True) + self.assertFalse(f is sbf.GetFile()) + sbf.Write(b"foobar\n") + self.assertEqual(f.fileno(), sbf.GetFile().fileno()) + sbf.Close() + self.assertFalse(f.closed) + + with open(self.out_filename, 'r') as f: + self.assertEqual("foobar", f.read().strip()) + + with open(self.out_filename, 'wb') as f: + sbf = lldb.SBFile.Create(f, borrow=True, force_io_methods=True) + self.assertTrue(f is sbf.GetFile()) + sbf.Write(b"foobar\n") + self.assertEqual(f.fileno(), sbf.GetFile().fileno()) + sbf.Close() + self.assertFalse(f.closed) + + with open(self.out_filename, 'r') as f: + self.assertEqual("foobar", f.read().strip()) + + with open(self.out_filename, 'wb') as f: + sbf = lldb.SBFile.Create(f, force_io_methods=True) + self.assertTrue(f is sbf.GetFile()) + sbf.Write(b"foobar\n") + self.assertEqual(f.fileno(), sbf.GetFile().fileno()) + sbf.Close() + self.assertTrue(f.closed) + + with open(self.out_filename, 'r') as f: + self.assertEqual("foobar", f.read().strip()) + + + @add_test_categories(['pyapi']) + def test_back_and_forth(self): + with open(self.out_filename, 'w') as f: + # at each step here we're borrowing the file, so we have to keep + # them all alive until the end. + sbf = lldb.SBFile.Create(f, borrow=True) + def i(sbf): + for i in range(10): + f = sbf.GetFile() + self.assertEqual(f.mode, "w") + yield f + sbf = lldb.SBFile.Create(f, borrow=True) + yield sbf + sbf.Write(str(i).encode('ascii') + b"\n") + files = list(i(sbf)) + with open(self.out_filename, 'r') as f: + self.assertEqual(list(range(10)), list(map(int, f.read().strip().split()))) + + + @add_test_categories(['pyapi']) + def test_set_filehandle_none(self): + self.assertRaises(Exception, self.debugger.SetOutputFile, None) + self.assertRaises(Exception, self.debugger.SetOutputFile, "ham sandwich") + self.assertRaises(Exception, self.debugger.SetOutputFileHandle, "ham sandwich") + self.assertRaises(Exception, self.debugger.SetInputFile, None) + self.assertRaises(Exception, self.debugger.SetInputFile, "ham sandwich") + self.assertRaises(Exception, self.debugger.SetInputFileHandle, "ham sandwich") + self.assertRaises(Exception, self.debugger.SetErrorFile, None) + self.assertRaises(Exception, self.debugger.SetErrorFile, "ham sandwich") + self.assertRaises(Exception, self.debugger.SetErrorFileHandle, "ham sandwich") + + with open(self.out_filename, 'w') as f: + status = self.debugger.SetOutputFile(f) + self.assertTrue(status.Success()) + status = self.debugger.SetErrorFile(f) + self.assertTrue(status.Success()) + self.debugger.SetOutputFileHandle(None, False) + self.debugger.SetErrorFileHandle(None, False) + sbf = self.debugger.GetOutputFile() + if sys.version_info.major >= 3: + # python 2 lacks PyFile_FromFd, so GetFile() will + # have to duplicate the file descriptor and make a FILE* + # in order to convert a NativeFile it back to a python + # file. + self.assertEqual(sbf.GetFile().fileno(), 1) + sbf = self.debugger.GetErrorFile() + if sys.version_info.major >= 3: + self.assertEqual(sbf.GetFile().fileno(), 2) + with open(self.out_filename, 'r') as f: + status = self.debugger.SetInputFile(f) + self.assertTrue(status.Success()) + self.debugger.SetInputFileHandle(None, False) + sbf = self.debugger.GetInputFile() + if sys.version_info.major >= 3: + self.assertEqual(sbf.GetFile().fileno(), 0) + + + @add_test_categories(['pyapi']) + def test_sbstream(self): + + with open(self.out_filename, 'w') as f: + stream = lldb.SBStream() + stream.RedirectToFile(f) + stream.Print("zork") + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read().strip(), "zork") + + with open(self.out_filename, 'w') as f: + stream = lldb.SBStream() + stream.RedirectToFileHandle(f, True) + stream.Print("Yendor") + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read().strip(), "Yendor") + + stream = lldb.SBStream() + f = open(self.out_filename, 'w') + stream.RedirectToFile(lldb.SBFile.Create(f, borrow=False)) + stream.Print("Frobozz") + stream = None + self.assertTrue(f.closed) + with open(self.out_filename, 'r') as f: + self.assertEqual(f.read().strip(), "Frobozz") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/Makefile new file mode 100644 index 00000000000..33da5d0645e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/Makefile @@ -0,0 +1,8 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules + +# Clean renamed executable on 'make clean' +clean:: + $(RM) -f no_synth + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py new file mode 100644 index 00000000000..0c9e2800768 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py @@ -0,0 +1,80 @@ +"""Test that SBFrame::FindValue finds things but does not duplicate the entire variables list""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SBFrameFindValueTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + def test_formatters_api(self): + """Test that SBFrame::FindValue finds things but does not duplicate the entire variables list""" + self.build() + self.setTearDownCleanup() + + exe = self.getBuildArtifact("a.out") + + # Create the target + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Set the breakpoints + breakpoint = target.BreakpointCreateBySourceRegex( + 'Set breakpoint here', lldb.SBFileSpec("main.cpp")) + self.assertTrue(breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be at our breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + + self.assertTrue(len(threads) == 1) + self.thread = threads[0] + self.frame = self.thread.frames[0] + self.assertTrue(self.frame, "Frame 0 is valid.") + + self.assertTrue( + self.frame.GetVariables( + True, + True, + False, + True).GetSize() == 2, + "variable count is off") + self.assertFalse( + self.frame.FindValue( + "NoSuchThing", + lldb.eValueTypeVariableArgument, + lldb.eDynamicCanRunTarget).IsValid(), + "found something that should not be here") + self.assertTrue( + self.frame.GetVariables( + True, + True, + False, + True).GetSize() == 2, + "variable count is off after failed FindValue()") + self.assertTrue( + self.frame.FindValue( + "a", + lldb.eValueTypeVariableArgument, + lldb.eDynamicCanRunTarget).IsValid(), + "FindValue() didn't find an argument") + self.assertTrue( + self.frame.GetVariables( + True, + True, + False, + True).GetSize() == 2, + "variable count is off after successful FindValue()") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/main.cpp new file mode 100644 index 00000000000..7058d46b04a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/findvalue_duplist/main.cpp @@ -0,0 +1,7 @@ +int foo(int a, int b) { + return a + b; // Set breakpoint here +} + +int main() { + return foo(1,3); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/Makefile new file mode 100644 index 00000000000..16a823213db --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/Makefile @@ -0,0 +1,7 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules + +# Clean renamed executable on 'make clean' +clean:: + $(RM) -f no_synth diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py new file mode 100644 index 00000000000..f01d7c457c5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py @@ -0,0 +1,500 @@ +"""Test Python APIs for working with formatters""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SBFormattersAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.line = line_number('main.cpp', '// Set break point at this line.') + + @add_test_categories(['pyapi']) + def test_formatters_api(self): + """Test Python APIs for working with formatters""" + self.build() + self.setTearDownCleanup() + + """Test Python APIs for working with formatters""" + self.runCmd("file " + self.getBuildArtifact("a.out"), + CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synthetic clear', check=False) + self.runCmd('type category delete foobar', check=False) + self.runCmd('type category delete JASSynth', check=False) + self.runCmd('type category delete newbar', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + format = lldb.SBTypeFormat(lldb.eFormatHex) + category = self.dbg.GetDefaultCategory() + category.AddTypeFormat(lldb.SBTypeNameSpecifier("int"), format) + + self.expect("frame variable foo.A", + substrs=['0x00000001']) + self.expect("frame variable foo.E", matching=False, + substrs=['b8cca70a']) + + category.AddTypeFormat(lldb.SBTypeNameSpecifier("long"), format) + self.expect("frame variable foo.A", + substrs=['0x00000001']) + self.expect("frame variable foo.E", + substrs=['b8cca70a']) + + format.SetFormat(lldb.eFormatOctal) + category.AddTypeFormat(lldb.SBTypeNameSpecifier("int"), format) + self.expect("frame variable foo.A", + substrs=[' 01']) + self.expect("frame variable foo.E", + substrs=['b8cca70a']) + + category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("int")) + category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("long")) + self.expect("frame variable foo.A", matching=False, + substrs=[' 01']) + self.expect("frame variable foo.E", matching=False, + substrs=['b8cca70a']) + + summary = lldb.SBTypeSummary.CreateWithSummaryString( + "the hello world you'll never see") + summary.SetSummaryString('hello world') + new_category = self.dbg.GetCategory("foobar") + self.assertFalse( + new_category.IsValid(), + "getting a non-existing category worked") + new_category = self.dbg.CreateCategory("foobar") + new_category.SetEnabled(True) + new_category.AddTypeSummary( + lldb.SBTypeNameSpecifier( + "^.*t$", + True, # is_regexp + ), summary) + + self.expect("frame variable foo.A", + substrs=['hello world']) + self.expect("frame variable foo.E", matching=False, + substrs=['hello world']) + self.expect("frame variable foo.B", + substrs=['hello world']) + self.expect("frame variable foo.F", + substrs=['hello world']) + new_category.SetEnabled(False) + self.expect("frame variable foo.A", matching=False, + substrs=['hello world']) + self.expect("frame variable foo.E", matching=False, + substrs=['hello world']) + self.expect("frame variable foo.B", matching=False, + substrs=['hello world']) + self.expect("frame variable foo.F", matching=False, + substrs=['hello world']) + self.dbg.DeleteCategory(new_category.GetName()) + self.expect("frame variable foo.A", matching=False, + substrs=['hello world']) + self.expect("frame variable foo.E", matching=False, + substrs=['hello world']) + self.expect("frame variable foo.B", matching=False, + substrs=['hello world']) + self.expect("frame variable foo.F", matching=False, + substrs=['hello world']) + + filter = lldb.SBTypeFilter(0) + filter.AppendExpressionPath("A") + filter.AppendExpressionPath("D") + self.assertTrue( + filter.GetNumberOfExpressionPaths() == 2, + "filter with two items does not have two items") + + category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"), filter) + self.expect("frame variable foo", + substrs=['A = 1', 'D = 6.28']) + self.expect("frame variable foo", matching=False, + substrs=['B = ', 'C = ', 'E = ', 'F = ']) + + category.DeleteTypeFilter( + lldb.SBTypeNameSpecifier( + "JustAStruct", True)) + self.expect("frame variable foo", + substrs=['A = 1', 'D = 6.28']) + self.expect("frame variable foo", matching=False, + substrs=['B = ', 'C = ', 'E = ', 'F = ']) + + category.DeleteTypeFilter( + lldb.SBTypeNameSpecifier( + "JustAStruct", False)) + self.expect("frame variable foo", + substrs=['A = 1', 'D = 6.28']) + self.expect("frame variable foo", matching=True, + substrs=['B = ', 'C = ', 'E = ', 'F = ']) + + self.runCmd("command script import --allow-reload ./synth.py") + + self.expect("frame variable foo", matching=False, + substrs=['X = 1']) + + self.dbg.GetCategory("JASSynth").SetEnabled(True) + self.expect("frame variable foo", matching=True, + substrs=['X = 1']) + + self.dbg.GetCategory("CCCSynth").SetEnabled(True) + self.expect( + "frame variable ccc", + matching=True, + substrs=[ + 'CCC object with leading value (int) a = 111', + 'a = 111', + 'b = 222', + 'c = 333']) + + foo_var = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('foo') + self.assertTrue(foo_var.IsValid(), 'could not find foo') + self.assertTrue( + foo_var.GetDeclaration().IsValid(), + 'foo declaration is invalid') + + self.assertTrue( + foo_var.GetNumChildren() == 2, + 'synthetic value has wrong number of child items (synth)') + self.assertTrue( + foo_var.GetChildMemberWithName('X').GetValueAsUnsigned() == 1, + 'foo_synth.X has wrong value (synth)') + self.assertFalse( + foo_var.GetChildMemberWithName('B').IsValid(), + 'foo_synth.B is valid but should not (synth)') + + self.dbg.GetCategory("JASSynth").SetEnabled(False) + foo_var = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('foo') + self.assertTrue(foo_var.IsValid(), 'could not find foo') + + self.assertFalse( + foo_var.GetNumChildren() == 2, + 'still seeing synthetic value') + + filter = lldb.SBTypeFilter(0) + filter.AppendExpressionPath("A") + filter.AppendExpressionPath("D") + category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"), filter) + self.expect("frame variable foo", + substrs=['A = 1', 'D = 6.28']) + + foo_var = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('foo') + self.assertTrue(foo_var.IsValid(), 'could not find foo') + + self.assertTrue( + foo_var.GetNumChildren() == 2, + 'synthetic value has wrong number of child items (filter)') + self.assertTrue( + foo_var.GetChildMemberWithName('X').GetValueAsUnsigned() == 0, + 'foo_synth.X has wrong value (filter)') + self.assertTrue( + foo_var.GetChildMemberWithName('A').GetValueAsUnsigned() == 1, + 'foo_synth.A has wrong value (filter)') + + self.assertTrue(filter.ReplaceExpressionPathAtIndex( + 0, "C"), "failed to replace an expression path in filter") + self.expect("frame variable foo", + substrs=['A = 1', 'D = 6.28']) + category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"), filter) + self.expect("frame variable foo", + substrs=["C = 'e'", 'D = 6.28']) + category.AddTypeFilter(lldb.SBTypeNameSpecifier("FooType"), filter) + filter.ReplaceExpressionPathAtIndex(1, "F") + self.expect("frame variable foo", + substrs=["C = 'e'", 'D = 6.28']) + category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"), filter) + self.expect("frame variable foo", + substrs=["C = 'e'", 'F = 0']) + self.expect("frame variable bar", + substrs=["C = 'e'", 'D = 6.28']) + + foo_var = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame().FindVariable('foo') + self.assertTrue(foo_var.IsValid(), 'could not find foo') + self.assertTrue( + foo_var.GetChildMemberWithName('C').GetValueAsUnsigned() == ord('e'), + 'foo_synth.C has wrong value (filter)') + + chosen = self.dbg.GetFilterForType( + lldb.SBTypeNameSpecifier("JustAStruct")) + self.assertTrue( + chosen.count == 2, + "wrong filter found for JustAStruct") + self.assertTrue( + chosen.GetExpressionPathAtIndex(0) == 'C', + "wrong item at index 0 for JustAStruct") + self.assertTrue( + chosen.GetExpressionPathAtIndex(1) == 'F', + "wrong item at index 1 for JustAStruct") + + self.assertFalse( + category.DeleteTypeFilter( + lldb.SBTypeNameSpecifier("NoSuchType")), + "deleting a non-existing filter worked") + self.assertFalse( + category.DeleteTypeSummary( + lldb.SBTypeNameSpecifier("NoSuchType")), + "deleting a non-existing summary worked") + self.assertFalse( + category.DeleteTypeFormat( + lldb.SBTypeNameSpecifier("NoSuchType")), + "deleting a non-existing format worked") + self.assertFalse( + category.DeleteTypeSynthetic( + lldb.SBTypeNameSpecifier("NoSuchType")), + "deleting a non-existing synthetic worked") + + self.assertFalse( + category.DeleteTypeFilter( + lldb.SBTypeNameSpecifier("")), + "deleting a filter for '' worked") + self.assertFalse( + category.DeleteTypeSummary( + lldb.SBTypeNameSpecifier("")), + "deleting a summary for '' worked") + self.assertFalse( + category.DeleteTypeFormat( + lldb.SBTypeNameSpecifier("")), + "deleting a format for '' worked") + self.assertFalse( + category.DeleteTypeSynthetic( + lldb.SBTypeNameSpecifier("")), + "deleting a synthetic for '' worked") + + try: + self.assertFalse( + category.AddTypeSummary( + lldb.SBTypeNameSpecifier("NoneSuchType"), + None), + "adding a summary valued None worked") + except: + pass + else: + self.assertFalse(True, "adding a summary valued None worked") + + try: + self.assertFalse( + category.AddTypeFilter( + lldb.SBTypeNameSpecifier("NoneSuchType"), + None), + "adding a filter valued None worked") + except: + pass + else: + self.assertFalse(True, "adding a filter valued None worked") + + try: + self.assertFalse( + category.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("NoneSuchType"), + None), + "adding a synthetic valued None worked") + except: + pass + else: + self.assertFalse(True, "adding a synthetic valued None worked") + + try: + self.assertFalse( + category.AddTypeFormat( + lldb.SBTypeNameSpecifier("NoneSuchType"), + None), + "adding a format valued None worked") + except: + pass + else: + self.assertFalse(True, "adding a format valued None worked") + + self.assertFalse( + category.AddTypeSummary( + lldb.SBTypeNameSpecifier("EmptySuchType"), + lldb.SBTypeSummary()), + "adding a summary without value worked") + self.assertFalse( + category.AddTypeFilter( + lldb.SBTypeNameSpecifier("EmptySuchType"), + lldb.SBTypeFilter()), + "adding a filter without value worked") + self.assertFalse( + category.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("EmptySuchType"), + lldb.SBTypeSynthetic()), + "adding a synthetic without value worked") + self.assertFalse( + category.AddTypeFormat( + lldb.SBTypeNameSpecifier("EmptySuchType"), + lldb.SBTypeFormat()), + "adding a format without value worked") + + self.assertFalse( + category.AddTypeSummary( + lldb.SBTypeNameSpecifier(""), + lldb.SBTypeSummary.CreateWithSummaryString("")), + "adding a summary for an invalid type worked") + self.assertFalse( + category.AddTypeFilter( + lldb.SBTypeNameSpecifier(""), + lldb.SBTypeFilter(0)), + "adding a filter for an invalid type worked") + self.assertFalse( + category.AddTypeSynthetic( + lldb.SBTypeNameSpecifier(""), + lldb.SBTypeSynthetic.CreateWithClassName("")), + "adding a synthetic for an invalid type worked") + self.assertFalse( + category.AddTypeFormat( + lldb.SBTypeNameSpecifier(""), + lldb.SBTypeFormat( + lldb.eFormatHex)), + "adding a format for an invalid type worked") + + new_category = self.dbg.CreateCategory("newbar") + new_category.AddTypeSummary( + lldb.SBTypeNameSpecifier("JustAStruct"), + lldb.SBTypeSummary.CreateWithScriptCode("return 'hello scripted world';")) + self.expect("frame variable foo", matching=False, + substrs=['hello scripted world']) + new_category.SetEnabled(True) + self.expect("frame variable foo", matching=True, + substrs=['hello scripted world']) + + self.expect("frame variable foo_ptr", matching=True, + substrs=['hello scripted world']) + new_category.AddTypeSummary( + lldb.SBTypeNameSpecifier("JustAStruct"), + lldb.SBTypeSummary.CreateWithScriptCode( + "return 'hello scripted world';", + lldb.eTypeOptionSkipPointers)) + self.expect("frame variable foo", matching=True, + substrs=['hello scripted world']) + + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() + foo_ptr = frame.FindVariable("foo_ptr") + summary = foo_ptr.GetTypeSummary() + + self.assertFalse( + summary.IsValid(), + "summary found for foo* when none was planned") + + self.expect("frame variable foo_ptr", matching=False, + substrs=['hello scripted world']) + + new_category.AddTypeSummary( + lldb.SBTypeNameSpecifier("JustAStruct"), + lldb.SBTypeSummary.CreateWithSummaryString( + "hello static world", + lldb.eTypeOptionNone)) + + summary = foo_ptr.GetTypeSummary() + + self.assertTrue( + summary.IsValid(), + "no summary found for foo* when one was in place") + self.assertTrue( + summary.GetData() == "hello static world", + "wrong summary found for foo*") + + self.expect("frame variable e1", substrs=["I am an empty Empty1 {}"]) + self.expect("frame variable e2", substrs=["I am an empty Empty2"]) + self.expect( + "frame variable e2", + substrs=["I am an empty Empty2 {}"], + matching=False) + + self.assertTrue( + self.dbg.GetCategory( + lldb.eLanguageTypeObjC) is not None, + "ObjC category is None") + + @add_test_categories(['pyapi']) + def test_force_synth_off(self): + """Test that one can have the public API return non-synthetic SBValues if desired""" + self.build(dictionary={'EXE': 'no_synth'}) + self.setTearDownCleanup() + + self.runCmd("file " + self.getBuildArtifact("no_synth"), + CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synthetic clear', check=False) + self.runCmd('type category delete foobar', check=False) + self.runCmd('type category delete JASSynth', check=False) + self.runCmd('type category delete newbar', check=False) + self.runCmd('settings set target.enable-synthetic-value true') + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() + int_vector = frame.FindVariable("int_vector") + if self.TraceOn(): + print(int_vector) + self.assertTrue( + int_vector.GetNumChildren() == 0, + 'synthetic vector is empty') + + self.runCmd('settings set target.enable-synthetic-value false') + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() + int_vector = frame.FindVariable("int_vector") + if self.TraceOn(): + print(int_vector) + self.assertFalse( + int_vector.GetNumChildren() == 0, + '"physical" vector is not empty') + + self.runCmd('settings set target.enable-synthetic-value true') + frame = self.dbg.GetSelectedTarget().GetProcess( + ).GetSelectedThread().GetSelectedFrame() + int_vector = frame.FindVariable("int_vector") + if self.TraceOn(): + print(int_vector) + self.assertTrue( + int_vector.GetNumChildren() == 0, + 'synthetic vector is still empty') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/main.cpp new file mode 100644 index 00000000000..f21c956144c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/main.cpp @@ -0,0 +1,59 @@ +#include <stdio.h> +#include <vector> + +struct JustAStruct +{ + int A; + float B; + char C; + double D; + long E; + short F; +}; + +struct FooType +{ + int A; + float B; + char C; + double D; + long E; + short F; +}; + +struct CCC +{ + int a, b, c; +}; + +struct Empty1 { void *data; }; +struct Empty2 { void *data; }; + + +int main(int argc, char const *argv[]) { + JustAStruct foo; + foo.A = 1; + foo.B = 3.14; + foo.C = 'e'; + foo.D = 6.28; + foo.E = 3100419850; + foo.F = 0; + + FooType bar; + bar.A = 1; + bar.B = 3.14; + bar.C = 'e'; + bar.D = 6.28; + bar.E = 3100419850; + bar.F = 0; + JustAStruct* foo_ptr = &foo; + + std::vector<int> int_vector; + + CCC ccc = {111, 222, 333}; + + Empty1 e1; + Empty2 e2; + + return 0; // Set break point at this line. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/synth.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/synth.py new file mode 100644 index 00000000000..75a8d6cfc65 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/formatters/synth.py @@ -0,0 +1,117 @@ +import lldb + + +class jasSynthProvider: + + def __init__(self, valobj, dict): + self.valobj = valobj + + def num_children(self): + return 2 + + def get_child_at_index(self, index): + child = None + if index == 0: + child = self.valobj.GetChildMemberWithName('A') + if index == 1: + child = self.valobj.CreateValueFromExpression('X', '(int)1') + return child + + def get_child_index(self, name): + if name == 'A': + return 0 + if name == 'X': + return 1 + return None + + +def ccc_summary(sbvalue, internal_dict): + sbvalue = sbvalue.GetNonSyntheticValue() + # This tests that the SBValue.GetNonSyntheticValue() actually returns a + # non-synthetic value. If it does not, then sbvalue.GetChildMemberWithName("a") + # in the following statement will call the 'get_child_index' method of the + # synthetic child provider CCCSynthProvider below (which raises an + # exception). + return "CCC object with leading value " + \ + str(sbvalue.GetChildMemberWithName("a")) + + +class CCCSynthProvider(object): + + def __init__(self, sbvalue, internal_dict): + self._sbvalue = sbvalue + + def num_children(self): + return 3 + + def get_child_index(self, name): + raise RuntimeError("I don't want to be called!") + + def get_child_at_index(self, index): + if index == 0: + return self._sbvalue.GetChildMemberWithName("a") + if index == 1: + return self._sbvalue.GetChildMemberWithName("b") + if index == 2: + return self._sbvalue.GetChildMemberWithName("c") + + +def empty1_summary(sbvalue, internal_dict): + return "I am an empty Empty1" + + +class Empty1SynthProvider(object): + + def __init__(self, sbvalue, internal_dict): + self._sbvalue = sbvalue + + def num_children(self): + return 0 + + def get_child_at_index(self, index): + return None + + +def empty2_summary(sbvalue, internal_dict): + return "I am an empty Empty2" + + +class Empty2SynthProvider(object): + + def __init__(self, sbvalue, internal_dict): + self._sbvalue = sbvalue + + def num_children(self): + return 0 + + def get_child_at_index(self, index): + return None + + +def __lldb_init_module(debugger, dict): + debugger.CreateCategory("JASSynth").AddTypeSynthetic( + lldb.SBTypeNameSpecifier("JustAStruct"), + lldb.SBTypeSynthetic.CreateWithClassName("synth.jasSynthProvider")) + cat = debugger.CreateCategory("CCCSynth") + cat.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("CCC"), + lldb.SBTypeSynthetic.CreateWithClassName("synth.CCCSynthProvider", + lldb.eTypeOptionCascade)) + cat.AddTypeSummary( + lldb.SBTypeNameSpecifier("CCC"), + lldb.SBTypeSummary.CreateWithFunctionName("synth.ccc_summary", + lldb.eTypeOptionCascade)) + cat.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("Empty1"), + lldb.SBTypeSynthetic.CreateWithClassName("synth.Empty1SynthProvider")) + cat.AddTypeSummary( + lldb.SBTypeNameSpecifier("Empty1"), + lldb.SBTypeSummary.CreateWithFunctionName("synth.empty1_summary")) + cat.AddTypeSynthetic( + lldb.SBTypeNameSpecifier("Empty2"), + lldb.SBTypeSynthetic.CreateWithClassName("synth.Empty2SynthProvider")) + cat.AddTypeSummary( + lldb.SBTypeNameSpecifier("Empty2"), + lldb.SBTypeSummary.CreateWithFunctionName( + "synth.empty2_summary", + lldb.eTypeOptionHideEmptyAggregates)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py new file mode 100644 index 00000000000..91ac30e36e3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py @@ -0,0 +1,221 @@ +""" +Use lldb Python SBFrame API to get the argument values of the call stacks. +And other SBFrame API tests. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class FrameAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + def test_get_arg_vals_for_call_stack(self): + """Exercise SBFrame.GetVariables() API to get argument vals.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + # Keeps track of the number of times 'a' is called where it is within a + # depth of 3 of the 'c' leaf function. + callsOfA = 0 + + from six import StringIO as SixStringIO + session = SixStringIO() + while process.GetState() == lldb.eStateStopped: + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + # Inspect at most 3 frames. + numFrames = min(3, thread.GetNumFrames()) + for i in range(numFrames): + frame = thread.GetFrameAtIndex(i) + if self.TraceOn(): + print("frame:", frame) + + name = frame.GetFunction().GetName() + if name == 'a': + callsOfA = callsOfA + 1 + + # We'll inspect only the arguments for the current frame: + # + # arguments => True + # locals => False + # statics => False + # in_scope_only => True + valList = frame.GetVariables(True, False, False, True) + argList = [] + for val in valList: + argList.append("(%s)%s=%s" % (val.GetTypeName(), + val.GetName(), + val.GetValue())) + print("%s(%s)" % (name, ", ".join(argList)), file=session) + + # Also check the generic pc & stack pointer. We can't test their absolute values, + # but they should be valid. Uses get_GPRs() from the lldbutil + # module. + gpr_reg_set = lldbutil.get_GPRs(frame) + pc_value = gpr_reg_set.GetChildMemberWithName("pc") + self.assertTrue(pc_value, "We should have a valid PC.") + pc_value_int = int(pc_value.GetValue(), 0) + # Make sure on arm targets we dont mismatch PC value on the basis of thumb bit. + # Frame PC will not have thumb bit set in case of a thumb + # instruction as PC. + if self.getArchitecture() in ['arm', 'armv7', 'armv7k']: + pc_value_int &= ~1 + self.assertTrue( + pc_value_int == frame.GetPC(), + "PC gotten as a value should equal frame's GetPC") + sp_value = gpr_reg_set.GetChildMemberWithName("sp") + self.assertTrue( + sp_value, "We should have a valid Stack Pointer.") + self.assertTrue(int(sp_value.GetValue(), 0) == frame.GetSP( + ), "SP gotten as a value should equal frame's GetSP") + + print("---", file=session) + process.Continue() + + # At this point, the inferior process should have exited. + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) + + # Expect to find 'a' on the call stacks two times. + self.assertTrue(callsOfA == 2, + "Expect to find 'a' on the call stacks two times") + # By design, the 'a' call frame has the following arg vals: + # o a((int)val=1, (char)ch='A') + # o a((int)val=3, (char)ch='A') + if self.TraceOn(): + print("Full stack traces when stopped on the breakpoint 'c':") + print(session.getvalue()) + self.expect(session.getvalue(), "Argugment values displayed correctly", + exe=False, + substrs=["a((int)val=1, (char)ch='A')", + "a((int)val=3, (char)ch='A')"]) + + @add_test_categories(['pyapi']) + def test_frame_api_boundary_condition(self): + """Exercise SBFrame APIs with boundary condition inputs.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + frame = thread.GetFrameAtIndex(0) + if self.TraceOn(): + print("frame:", frame) + + # Boundary condition testings. + val1 = frame.FindVariable(None, True) + val2 = frame.FindVariable(None, False) + val3 = frame.FindValue(None, lldb.eValueTypeVariableGlobal) + if self.TraceOn(): + print("val1:", val1) + print("val2:", val2) + + frame.EvaluateExpression(None) + + @add_test_categories(['pyapi']) + def test_frame_api_IsEqual(self): + """Exercise SBFrame API IsEqual.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + frameEntered = thread.GetFrameAtIndex(0) + if self.TraceOn(): + print(frameEntered) + lldbutil.print_stacktrace(thread) + self.assertTrue(frameEntered) + + # Doing two step overs while still inside c(). + thread.StepOver() + thread.StepOver() + self.assertTrue(thread) + frameNow = thread.GetFrameAtIndex(0) + if self.TraceOn(): + print(frameNow) + lldbutil.print_stacktrace(thread) + self.assertTrue(frameNow) + + # The latest two frames are considered equal. + self.assertTrue(frameEntered.IsEqual(frameNow)) + + # Now let's step out of frame c(). + thread.StepOutOfFrame(frameNow) + frameOutOfC = thread.GetFrameAtIndex(0) + if self.TraceOn(): + print(frameOutOfC) + lldbutil.print_stacktrace(thread) + self.assertTrue(frameOutOfC) + + # The latest two frames should not be equal. + self.assertFalse(frameOutOfC.IsEqual(frameNow)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/TestGetVariables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/TestGetVariables.py new file mode 100644 index 00000000000..7ced4ddb98f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/TestGetVariables.py @@ -0,0 +1,294 @@ +""" +Test that SBFrame::GetVariables() calls work correctly. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbplatform +from lldbsuite.test import lldbutil + + +def get_names_from_value_list(value_list): + names = list() + for value in value_list: + names.append(value.GetName()) + return names + + +class TestGetVariables(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.source = 'main.c' + + def verify_variable_names(self, description, value_list, names): + copy_names = list(names) + actual_names = get_names_from_value_list(value_list) + for name in actual_names: + if name in copy_names: + copy_names.remove(name) + else: + self.assertTrue( + False, "didn't find '%s' in %s" % + (name, copy_names)) + self.assertEqual( + len(copy_names), 0, "%s: we didn't find variables: %s in value list (%s)" % + (description, copy_names, actual_names)) + + def test(self): + self.build() + + # Set debugger into synchronous mode + self.dbg.SetAsync(False) + + # Create a target by the debugger. + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + line1 = line_number(self.source, '// breakpoint 1') + line2 = line_number(self.source, '// breakpoint 2') + line3 = line_number(self.source, '// breakpoint 3') + + breakpoint1 = target.BreakpointCreateByLocation(self.source, line1) + breakpoint2 = target.BreakpointCreateByLocation(self.source, line2) + breakpoint3 = target.BreakpointCreateByLocation(self.source, line3) + + self.assertTrue(breakpoint1.GetNumLocations() >= 1, PROCESS_IS_VALID) + self.assertTrue(breakpoint2.GetNumLocations() >= 1, PROCESS_IS_VALID) + self.assertTrue(breakpoint3.GetNumLocations() >= 1, PROCESS_IS_VALID) + + # Register our shared libraries for remote targets so they get + # automatically uploaded + arguments = None + environment = None + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + arguments, environment, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint1) + self.assertEqual( + len(threads), + 1, + "There should be a thread stopped at breakpoint 1") + + thread = threads[0] + self.assertTrue(thread.IsValid(), "Thread must be valid") + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame.IsValid(), "Frame must be valid") + + arg_names = ['argc', 'argv'] + local_names = ['i', 'j', 'k'] + static_names = ['static_var', 'g_global_var', 'g_static_var'] + breakpoint1_locals = ['i'] + breakpoint1_statics = ['static_var'] + num_args = len(arg_names) + num_locals = len(local_names) + num_statics = len(static_names) + args_yes = True + args_no = False + locals_yes = True + locals_no = False + statics_yes = True + statics_no = False + in_scopy_only = True + ignore_scope = False + + # Verify if we ask for only arguments that we got what we expect + vars = frame.GetVariables( + args_yes, locals_no, statics_no, ignore_scope) + self.assertEqual( + vars.GetSize(), + num_args, + "There should be %i arguments, but we are reporting %i" % + (num_args, + vars.GetSize())) + self.verify_variable_names("check names of arguments", vars, arg_names) + self.assertEqual( + len(arg_names), + num_args, + "make sure verify_variable_names() didn't mutate list") + + # Verify if we ask for only locals that we got what we expect + vars = frame.GetVariables( + args_no, locals_yes, statics_no, ignore_scope) + self.assertEqual( + vars.GetSize(), + num_locals, + "There should be %i local variables, but we are reporting %i" % + (num_locals, + vars.GetSize())) + self.verify_variable_names("check names of locals", vars, local_names) + + # Verify if we ask for only statics that we got what we expect + vars = frame.GetVariables( + args_no, locals_no, statics_yes, ignore_scope) + print('statics: ', str(vars)) + self.assertEqual( + vars.GetSize(), + num_statics, + "There should be %i static variables, but we are reporting %i" % + (num_statics, + vars.GetSize())) + self.verify_variable_names( + "check names of statics", vars, static_names) + + # Verify if we ask for arguments and locals that we got what we expect + vars = frame.GetVariables( + args_yes, locals_yes, statics_no, ignore_scope) + desc = 'arguments + locals' + names = arg_names + local_names + count = len(names) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) + self.verify_variable_names("check names of %s" % (desc), vars, names) + + # Verify if we ask for arguments and statics that we got what we expect + vars = frame.GetVariables( + args_yes, locals_no, statics_yes, ignore_scope) + desc = 'arguments + statics' + names = arg_names + static_names + count = len(names) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) + self.verify_variable_names("check names of %s" % (desc), vars, names) + + # Verify if we ask for locals and statics that we got what we expect + vars = frame.GetVariables( + args_no, locals_yes, statics_yes, ignore_scope) + desc = 'locals + statics' + names = local_names + static_names + count = len(names) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) + self.verify_variable_names("check names of %s" % (desc), vars, names) + + # Verify if we ask for arguments, locals and statics that we got what + # we expect + vars = frame.GetVariables( + args_yes, locals_yes, statics_yes, ignore_scope) + desc = 'arguments + locals + statics' + names = arg_names + local_names + static_names + count = len(names) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) + self.verify_variable_names("check names of %s" % (desc), vars, names) + + # Verify if we ask for in scope locals that we got what we expect + vars = frame.GetVariables( + args_no, locals_yes, statics_no, in_scopy_only) + desc = 'in scope locals at breakpoint 1' + names = ['i'] + count = len(names) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) + self.verify_variable_names("check names of %s" % (desc), vars, names) + + # Continue to breakpoint 2 + process.Continue() + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint2) + self.assertEqual( + len(threads), + 1, + "There should be a thread stopped at breakpoint 2") + + thread = threads[0] + self.assertTrue(thread.IsValid(), "Thread must be valid") + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame.IsValid(), "Frame must be valid") + + # Verify if we ask for in scope locals that we got what we expect + vars = frame.GetVariables( + args_no, locals_yes, statics_no, in_scopy_only) + desc = 'in scope locals at breakpoint 2' + names = ['i', 'j'] + count = len(names) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) + self.verify_variable_names("check names of %s" % (desc), vars, names) + + # Continue to breakpoint 3 + process.Continue() + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint3) + self.assertEqual( + len(threads), + 1, + "There should be a thread stopped at breakpoint 3") + + thread = threads[0] + self.assertTrue(thread.IsValid(), "Thread must be valid") + frame = thread.GetFrameAtIndex(0) + self.assertTrue(frame.IsValid(), "Frame must be valid") + + # Verify if we ask for in scope locals that we got what we expect + vars = frame.GetVariables( + args_no, locals_yes, statics_no, in_scopy_only) + desc = 'in scope locals at breakpoint 3' + names = ['i', 'j', 'k'] + count = len(names) + self.assertEqual( + vars.GetSize(), + count, + "There should be %i %s (%s) but we are reporting %i (%s)" % + (count, + desc, + names, + vars.GetSize(), + get_names_from_value_list(vars))) + self.verify_variable_names("check names of %s" % (desc), vars, names) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/main.c new file mode 100644 index 00000000000..7606e2ac909 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/get-variables/main.c @@ -0,0 +1,28 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +int g_global_var = 123; +static int g_static_var = 123; + +int main (int argc, char const *argv[]) +{ + static int static_var = 123; + g_static_var = 123; // clang bug. Need to touch this variable, otherwise it disappears. + int i = 0; // breakpoint 1 + for (i=0; i<1; ++i) + { + int j = i*2; + printf("i = %i, j = %i\n", i, j); // breakpoint 2 + { + int k = i*j*3; + printf("i = %i, j = %i\n", i, j); // breakpoint 3 + } + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/Makefile new file mode 100644 index 00000000000..e6d9d8310a0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/Makefile @@ -0,0 +1,7 @@ +C_SOURCES := inlines.c + +ifneq (,$(findstring icc,$(CC))) + CFLAGS_EXTRAS := -debug inline-debug-info +endif + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py new file mode 100644 index 00000000000..da4e9cb06e7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py @@ -0,0 +1,94 @@ +""" +Testlldb Python SBFrame APIs IsInlined() and GetFunctionName(). +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class InlinedFrameAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to of function 'c'. + self.source = 'inlines.c' + self.first_stop = line_number( + self.source, '// This should correspond to the first break stop.') + self.second_stop = line_number( + self.source, '// This should correspond to the second break stop.') + + @add_test_categories(['pyapi']) + def test_stop_at_outer_inline(self): + """Exercise SBFrame.IsInlined() and SBFrame.GetFunctionName().""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by the name of 'inner_inline'. + breakpoint = target.BreakpointCreateByName('inner_inline', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() > 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + import lldbsuite.test.lldbutil as lldbutil + stack_traces1 = lldbutil.print_stacktraces(process, string_buffer=True) + if self.TraceOn(): + print( + "Full stack traces when first stopped on the breakpoint 'inner_inline':") + print(stack_traces1) + + # The first breakpoint should correspond to an inlined call frame. + # If it's an inlined call frame, expect to find, in the stack trace, + # that there is a frame which corresponds to the following call site: + # + # outer_inline (argc); + # + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + frame0 = thread.GetFrameAtIndex(0) + if frame0.IsInlined(): + filename = frame0.GetLineEntry().GetFileSpec().GetFilename() + self.assertTrue(filename == self.source) + self.expect( + stack_traces1, "First stop at %s:%d" % + (self.source, self.first_stop), exe=False, substrs=[ + '%s:%d' % + (self.source, self.first_stop)]) + + # Expect to break again for the second time. + process.Continue() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + stack_traces2 = lldbutil.print_stacktraces( + process, string_buffer=True) + if self.TraceOn(): + print( + "Full stack traces when stopped on the breakpoint 'inner_inline' for the second time:") + print(stack_traces2) + self.expect( + stack_traces2, "Second stop at %s:%d" % + (self.source, self.second_stop), exe=False, substrs=[ + '%s:%d' % + (self.source, self.second_stop)]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.c new file mode 100644 index 00000000000..a2a8212278d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.c @@ -0,0 +1,53 @@ +#include <stdio.h> +#include "inlines.h" + +#define INLINE_ME __inline__ __attribute__((always_inline)) + +int +not_inlined_2 (int input) +{ + printf ("Called in not_inlined_2 with : %d.\n", input); + return input; +} + +int +not_inlined_1 (int input) +{ + printf ("Called in not_inlined_1 with %d.\n", input); + return not_inlined_2(input); +} + +INLINE_ME int +inner_inline (int inner_input, int mod_value) +{ + int inner_result; + inner_result = inner_input % mod_value; + printf ("Returning: %d.\n", inner_result); + return not_inlined_1 (inner_result); +} + +INLINE_ME int +outer_inline (int outer_input) +{ + int outer_result; + + outer_result = inner_inline (outer_input, outer_input % 3); + return outer_result; +} + +int +main (int argc, char **argv) +{ + printf ("Starting...\n"); + + int (*func_ptr) (int); + func_ptr = outer_inline; + + outer_inline (argc); // This should correspond to the first break stop. + + func_ptr (argc); // This should correspond to the second break stop. + + return 0; +} + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.h new file mode 100644 index 00000000000..265d7b4966e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.h @@ -0,0 +1,4 @@ +int inner_inline (int inner_input, int mod_value); +int outer_inline (int outer_input); +int not_inlined_2 (int input); +int not_inlined_1 (int input); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/main.c new file mode 100644 index 00000000000..75f4448758b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/frame/main.c @@ -0,0 +1,57 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to test the lldb Python API related to frames. + +int a(int, char); +int b(int, char); +int c(int, char); + +int a(int val, char ch) +{ + int my_val = val; + char my_ch = ch; + printf("a(val=%d, ch='%c')\n", val, ch); + if (val <= 1) + return b(val+1, ch+1); + else if (val >= 3) + return c(val+1, ch+1); + + return val; +} + +int b(int val, char ch) +{ + int my_val = val; + char my_ch = ch; + printf("b(val=%d, ch='%c')\n", val, ch); + return c(val+1, ch+1); +} + +int c(int val, char ch) +{ + int my_val = val; + char my_ch = ch; + printf("c(val=%d, ch='%c')\n", val, ch); + return val + 3 + ch; +} + +int main (int argc, char const *argv[]) +{ + int A1 = a(1, 'A'); // a(1, 'A') -> b(2, 'B') -> c(3, 'C') + printf("a(1, 'A') returns %d\n", A1); + + int B2 = b(2, 'B'); // b(2, 'B') -> c(3, 'C') + printf("b(2, 'B') returns %d\n", B2); + + int A3 = a(3, 'A'); // a(3, 'A') -> c(4, 'B') + printf("a(3, 'A') returns %d\n", A3); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py new file mode 100644 index 00000000000..2278d69fbbe --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py @@ -0,0 +1,123 @@ +""" +Test retrieval of SBAddress from function/symbol, disassembly, and SBAddress APIs. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DisasmAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to of function 'c'. + self.line1 = line_number( + 'main.c', '// Find the line number for breakpoint 1 here.') + self.line2 = line_number( + 'main.c', '// Find the line number for breakpoint 2 here.') + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber='llvm.org/pr21765') + def test(self): + """Exercise getting SBAddress objects, disassembly, and SBAddress APIs.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create the two breakpoints inside function 'a'. + breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1) + breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2) + #print("breakpoint1:", breakpoint1) + #print("breakpoint2:", breakpoint2) + self.assertTrue(breakpoint1 and + breakpoint1.GetNumLocations() == 1, + VALID_BREAKPOINT) + self.assertTrue(breakpoint2 and + breakpoint2.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.line1. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + lineEntry = frame0.GetLineEntry() + self.assertTrue(lineEntry.GetLine() == self.line1) + + address1 = lineEntry.GetStartAddress() + #print("address1:", address1) + + # Now call SBTarget.ResolveSymbolContextForAddress() with address1. + context1 = target.ResolveSymbolContextForAddress( + address1, lldb.eSymbolContextEverything) + + self.assertTrue(context1) + if self.TraceOn(): + print("context1:", context1) + + # Continue the inferior, the breakpoint 2 should be hit. + process.Continue() + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + lineEntry = frame0.GetLineEntry() + self.assertTrue(lineEntry.GetLine() == self.line2) + + # Verify that the symbol and the function has the same address range + # per function 'a'. + symbol = context1.GetSymbol() + function = frame0.GetFunction() + self.assertTrue(symbol and function) + + disasm_output = lldbutil.disassemble(target, symbol) + if self.TraceOn(): + print("symbol:", symbol) + print("disassembly=>\n", disasm_output) + + disasm_output = lldbutil.disassemble(target, function) + if self.TraceOn(): + print("function:", function) + print("disassembly=>\n", disasm_output) + + sa1 = symbol.GetStartAddress() + #print("sa1:", sa1) + #print("sa1.GetFileAddress():", hex(sa1.GetFileAddress())) + #ea1 = symbol.GetEndAddress() + #print("ea1:", ea1) + sa2 = function.GetStartAddress() + #print("sa2:", sa2) + #print("sa2.GetFileAddress():", hex(sa2.GetFileAddress())) + #ea2 = function.GetEndAddress() + #print("ea2:", ea2) + self.assertTrue(sa1 and sa2 and sa1 == sa2, + "The two starting addresses should be the same") + + from lldbsuite.test.lldbutil import get_description + desc1 = get_description(sa1) + desc2 = get_description(sa2) + self.assertTrue( + desc1 and desc2 and desc1 == desc2, + "SBAddress.GetDescription() API of sa1 and sa2 should return the same string") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py new file mode 100644 index 00000000000..56fa73c84ad --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py @@ -0,0 +1,92 @@ +""" +Test newly added SBSymbol and SBAddress APIs. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SymbolAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to of function 'c'. + self.line1 = line_number( + 'main.c', '// Find the line number for breakpoint 1 here.') + self.line2 = line_number( + 'main.c', '// Find the line number for breakpoint 2 here.') + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber='llvm.org/pr21765') + def test(self): + """Exercise some SBSymbol and SBAddress APIs.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create the two breakpoints inside function 'a'. + breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1) + breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2) + #print("breakpoint1:", breakpoint1) + #print("breakpoint2:", breakpoint2) + self.assertTrue(breakpoint1 and + breakpoint1.GetNumLocations() == 1, + VALID_BREAKPOINT) + self.assertTrue(breakpoint2 and + breakpoint2.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.line1. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + symbol_line1 = frame0.GetSymbol() + # We should have a symbol type of code. + self.assertTrue(symbol_line1.GetType() == lldb.eSymbolTypeCode) + addr_line1 = symbol_line1.GetStartAddress() + # And a section type of code, too. + self.assertTrue(addr_line1.GetSection().GetSectionType() + == lldb.eSectionTypeCode) + + # Continue the inferior, the breakpoint 2 should be hit. + process.Continue() + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + symbol_line2 = frame0.GetSymbol() + # We should have a symbol type of code. + self.assertTrue(symbol_line2.GetType() == lldb.eSymbolTypeCode) + addr_line2 = symbol_line2.GetStartAddress() + # And a section type of code, too. + self.assertTrue(addr_line2.GetSection().GetSectionType() + == lldb.eSectionTypeCode) + + # Now verify that both addresses point to the same module. + if self.TraceOn(): + print("UUID:", addr_line1.GetModule().GetUUIDString()) + self.assertTrue(addr_line1.GetModule().GetUUIDString() + == addr_line2.GetModule().GetUUIDString()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/main.c new file mode 100644 index 00000000000..33eea200bc4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/function_symbol/main.c @@ -0,0 +1,59 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to test the lldb Python APIs SBTarget, SBFrame, +// SBFunction, SBSymbol, and SBAddress. +// +// When stopped on breakppint 1, we can get the line entry using SBFrame API +// SBFrame.GetLineEntry(). We'll get the start address for the line entry +// with the SBAddress type, resolve the symbol context using the SBTarget API +// SBTarget.ResolveSymbolContextForAddress() in order to get the SBSymbol. +// +// We then stop at breakpoint 2, get the SBFrame, and the SBFunction object. +// +// The address from calling GetStartAddress() on the symbol and the function +// should point to the same address, and we also verify that. + +int a(int); +int b(int); +int c(int); + +int a(int val) +{ + if (val <= 1) // Find the line number for breakpoint 1 here. + val = b(val); + else if (val >= 3) + val = c(val); + + return val; // Find the line number for breakpoint 2 here. +} + +int b(int val) +{ + return c(val); +} + +int c(int val) +{ + return val + 3; +} + +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; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/get-value-32bit-int/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/get-value-32bit-int/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/get-value-32bit-int/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/get-value-32bit-int/TestGetValue32BitInt.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/get-value-32bit-int/TestGetValue32BitInt.py new file mode 100644 index 00000000000..025226471bd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/get-value-32bit-int/TestGetValue32BitInt.py @@ -0,0 +1,19 @@ +""" +Check that SBValue.GetValueAsSigned() does the right thing for a 32-bit -1. +""" + +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + +class TestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_with_run_command(self): + self.build() + lldbutil.run_to_source_breakpoint(self,"// break here", lldb.SBFileSpec("main.cpp")) + + self.assertEqual(self.frame().FindVariable("myvar").GetValueAsSigned(), -1) + self.assertEqual(self.frame().FindVariable("myvar").GetValueAsUnsigned(), 0xFFFFFFFF) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/get-value-32bit-int/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/get-value-32bit-int/main.cpp new file mode 100644 index 00000000000..61f40fb2a78 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/get-value-32bit-int/main.cpp @@ -0,0 +1,5 @@ +#include <cstdint> +int main () { + int32_t myvar = -1; + return myvar; // break here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/hello_world/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/hello_world/Makefile new file mode 100644 index 00000000000..73625f4733f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/hello_world/Makefile @@ -0,0 +1,5 @@ +C_SOURCES := main.c +# See TestHelloWorld.py, which specifies the executable name with a dictionary. +EXE := hello_world + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py new file mode 100644 index 00000000000..fc6ef4882a0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py @@ -0,0 +1,155 @@ +"""Test Python APIs for target (launch and attach), breakpoint, and process.""" + + + +import os + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + +class HelloWorldTestCase(TestBase): + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find a couple of the line numbers within main.c. + self.line1 = line_number('main.c', '// Set break point at this line.') + self.line2 = line_number('main.c', '// Waiting to be attached...') + + def tearDown(self): + # Destroy process before TestBase.tearDown() + self.dbg.GetSelectedTarget().GetProcess().Destroy() + # Call super's tearDown(). + TestBase.tearDown(self) + + @add_test_categories(['pyapi']) + @skipIfiOSSimulator + def test_with_process_launch_api(self): + """Create target, breakpoint, launch a process, and then kill it.""" + # Get the full path to our executable to be attached/debugged. + exe = '%s_%d'%(self.getBuildArtifact(self.testMethodName), os.getpid()) + d = {'EXE': exe} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + target = self.dbg.CreateTarget(exe) + + breakpoint = target.BreakpointCreateByLocation("main.c", self.line1) + + # The default state after breakpoint creation should be enabled. + self.assertTrue(breakpoint.IsEnabled(), + "Breakpoint should be enabled after creation") + + breakpoint.SetEnabled(False) + self.assertTrue(not breakpoint.IsEnabled(), + "Breakpoint.SetEnabled(False) works") + + breakpoint.SetEnabled(True) + self.assertTrue(breakpoint.IsEnabled(), + "Breakpoint.SetEnabled(True) works") + + # rdar://problem/8364687 + # SBTarget.Launch() issue (or is there some race condition)? + + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + # The following isn't needed anymore, rdar://8364687 is fixed. + # + # Apply some dances after LaunchProcess() in order to break at "main". + # It only works sometimes. + #self.breakAfterLaunch(process, "main") + + process = target.GetProcess() + self.assertTrue(process, PROCESS_IS_VALID) + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + # The breakpoint should have a hit count of 1. + self.assertEqual(breakpoint.GetHitCount(), 1, BREAKPOINT_HIT_ONCE) + + @add_test_categories(['pyapi']) + @skipIfiOSSimulator + @expectedFailureNetBSD + def test_with_attach_to_process_with_id_api(self): + """Create target, spawn a process, and attach to it with process id.""" + exe = '%s_%d'%(self.testMethodName, os.getpid()) + d = {'EXE': exe} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + target = self.dbg.CreateTarget(self.getBuildArtifact(exe)) + + # Spawn a new process + token = exe+'.token' + if not lldb.remote_platform: + token = self.getBuildArtifact(token) + if os.path.exists(token): + os.remove(token) + popen = self.spawnSubprocess(self.getBuildArtifact(exe), [token]) + self.addTearDownHook(self.cleanupSubprocesses) + lldbutil.wait_for_file_on_target(self, token) + + listener = lldb.SBListener("my.attach.listener") + error = lldb.SBError() + process = target.AttachToProcessWithID(listener, popen.pid, error) + + self.assertTrue(error.Success() and process, PROCESS_IS_VALID) + + # Let's check the stack traces of the attached process. + stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) + self.expect(stacktraces, exe=False, + substrs=['main.c:%d' % self.line2, + '(int)argc=2']) + + @add_test_categories(['pyapi']) + @skipIfiOSSimulator + @skipIfAsan # FIXME: Hangs indefinitely. + @expectedFailureNetBSD + def test_with_attach_to_process_with_name_api(self): + """Create target, spawn a process, and attach to it with process name.""" + exe = '%s_%d'%(self.testMethodName, os.getpid()) + d = {'EXE': exe} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + target = self.dbg.CreateTarget(self.getBuildArtifact(exe)) + + # Spawn a new process. + token = exe+'.token' + if not lldb.remote_platform: + token = self.getBuildArtifact(token) + if os.path.exists(token): + os.remove(token) + popen = self.spawnSubprocess(self.getBuildArtifact(exe), [token]) + self.addTearDownHook(self.cleanupSubprocesses) + lldbutil.wait_for_file_on_target(self, token) + + listener = lldb.SBListener("my.attach.listener") + error = lldb.SBError() + # Pass 'False' since we don't want to wait for new instance of + # "hello_world" to be launched. + name = os.path.basename(exe) + + # While we're at it, make sure that passing a None as the process name + # does not hang LLDB. + target.AttachToProcessWithName(listener, None, False, error) + # Also boundary condition test ConnectRemote(), too. + target.ConnectRemote(listener, None, None, error) + + process = target.AttachToProcessWithName(listener, name, False, error) + self.assertTrue(error.Success() and process, PROCESS_IS_VALID) + + # Verify that after attach, our selected target indeed matches name. + self.expect( + self.dbg.GetSelectedTarget().GetExecutable().GetFilename(), + exe=False, + startstr=name) + + # Let's check the stack traces of the attached process. + stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) + self.expect(stacktraces, exe=False, + substrs=['main.c:%d' % self.line2, + '(int)argc=2']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/hello_world/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/hello_world/main.c new file mode 100644 index 00000000000..c516f923614 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/hello_world/main.c @@ -0,0 +1,29 @@ +#include <stdio.h> +#ifdef _MSC_VER +#include <windows.h> +#define sleep(x) Sleep((x) * 1000) +#else +#include <unistd.h> +#endif + +int main(int argc, char const *argv[]) +{ + lldb_enable_attach(); + + printf("Hello world.\n"); // Set break point at this line. + if (argc == 1) + return 1; + + // Create the synchronization token. + FILE *f; + if (f = fopen(argv[1], "wx")) { + fputs("\n", f); + fflush(f); + fclose(f); + } else + return 1; + + // Waiting to be attached by the debugger, otherwise. + while (1) + sleep(1); // Waiting to be attached... +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py new file mode 100644 index 00000000000..a920ce845b8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py @@ -0,0 +1,91 @@ +"""Test the SBCommandInterpreter APIs.""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class CommandInterpreterAPICase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break on inside main.cpp. + self.line = line_number('main.c', 'Hello world.') + + @add_test_categories(['pyapi']) + def test_with_process_launch_api(self): + """Test the SBCommandInterpreter APIs.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Retrieve the associated command interpreter from our debugger. + ci = self.dbg.GetCommandInterpreter() + self.assertTrue(ci, VALID_COMMAND_INTERPRETER) + + # Exercise some APIs.... + + self.assertTrue(ci.HasCommands()) + self.assertTrue(ci.HasAliases()) + self.assertTrue(ci.HasAliasOptions()) + self.assertTrue(ci.CommandExists("breakpoint")) + self.assertTrue(ci.CommandExists("target")) + self.assertTrue(ci.CommandExists("platform")) + self.assertTrue(ci.AliasExists("file")) + self.assertTrue(ci.AliasExists("run")) + self.assertTrue(ci.AliasExists("bt")) + + res = lldb.SBCommandReturnObject() + ci.HandleCommand("breakpoint set -f main.c -l %d" % self.line, res) + self.assertTrue(res.Succeeded()) + ci.HandleCommand("process launch", res) + self.assertTrue(res.Succeeded()) + + # Boundary conditions should not crash lldb! + self.assertFalse(ci.CommandExists(None)) + self.assertFalse(ci.AliasExists(None)) + ci.HandleCommand(None, res) + self.assertFalse(res.Succeeded()) + res.AppendMessage("Just appended a message.") + res.AppendMessage(None) + if self.TraceOn(): + print(res) + + process = ci.GetProcess() + self.assertTrue(process) + + import lldbsuite.test.lldbutil as lldbutil + if process.GetState() != lldb.eStateStopped: + self.fail("Process should be in the 'stopped' state, " + "instead the actual state is: '%s'" % + lldbutil.state_type_to_str(process.GetState())) + + if self.TraceOn(): + lldbutil.print_stacktraces(process) + + @add_test_categories(['pyapi']) + def test_command_output(self): + """Test command output handling.""" + ci = self.dbg.GetCommandInterpreter() + self.assertTrue(ci, VALID_COMMAND_INTERPRETER) + + # Test that a command which produces no output returns "" instead of + # None. + res = lldb.SBCommandReturnObject() + ci.HandleCommand("settings set use-color false", res) + self.assertTrue(res.Succeeded()) + self.assertIsNotNone(res.GetOutput()) + self.assertEquals(res.GetOutput(), "") + self.assertIsNotNone(res.GetError()) + self.assertEquals(res.GetError(), "") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestRunCommandInterpreterAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestRunCommandInterpreterAPI.py new file mode 100644 index 00000000000..a32805bf859 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/TestRunCommandInterpreterAPI.py @@ -0,0 +1,75 @@ +"""Test the RunCommandInterpreter API.""" + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + +class CommandRunInterpreterLegacyAPICase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + + self.stdin_path = self.getBuildArtifact("stdin.txt") + + with open(self.stdin_path, 'w') as input_handle: + input_handle.write("nonexistingcommand\nquit") + + # Python will close the file descriptor if all references + # to the filehandle object lapse, so we need to keep one + # around. + self.filehandle = open(self.stdin_path, 'r') + self.dbg.SetInputFileHandle(self.filehandle, False) + + # No need to track the output + self.devnull = open(os.devnull, 'w') + self.dbg.SetOutputFileHandle(self.devnull, False) + self.dbg.SetErrorFileHandle (self.devnull, False) + + @add_test_categories(['pyapi']) + def test_run_session_with_error_and_quit_legacy(self): + """Run non-existing and quit command returns appropriate values""" + + n_errors, quit_requested, has_crashed = self.dbg.RunCommandInterpreter( + True, False, lldb.SBCommandInterpreterRunOptions(), 0, False, + False) + + self.assertGreater(n_errors, 0) + self.assertTrue(quit_requested) + self.assertFalse(has_crashed) + + +class CommandRunInterpreterAPICase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + TestBase.setUp(self) + + self.stdin_path = self.getBuildArtifact("stdin.txt") + + with open(self.stdin_path, 'w') as input_handle: + input_handle.write("nonexistingcommand\nquit") + + self.dbg.SetInputFile(open(self.stdin_path, 'r')) + + # No need to track the output + devnull = open(os.devnull, 'w') + self.dbg.SetOutputFile(devnull) + self.dbg.SetErrorFile(devnull) + + @add_test_categories(['pyapi']) + def test_run_session_with_error_and_quit(self): + """Run non-existing and quit command returns appropriate values""" + + n_errors, quit_requested, has_crashed = self.dbg.RunCommandInterpreter( + True, False, lldb.SBCommandInterpreterRunOptions(), 0, False, + False) + + self.assertGreater(n_errors, 0) + self.assertTrue(quit_requested) + self.assertFalse(has_crashed) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/main.c new file mode 100644 index 00000000000..277aa54a4ee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/interpreter/main.c @@ -0,0 +1,6 @@ +#include <stdio.h> + +int main(int argc, char const *argv[]) { + printf("Hello world.\n"); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/TestSwigVersion.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/TestSwigVersion.py new file mode 100644 index 00000000000..8c5c6efda53 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/TestSwigVersion.py @@ -0,0 +1,27 @@ +""" +Test that we embed the swig version into the lldb module +""" + + +""" +import os +import time +import re +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test import lldbutil +""" +from lldbsuite.test.lldbtest import * + +class SwigVersionTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test(self): + self.assertTrue(getattr(lldb, "swig_version")) + self.assertIsInstance(lldb.swig_version, tuple) + self.assertEqual(len(lldb.swig_version), 3) + self.assertGreaterEqual(lldb.swig_version[0], 1) + for v in lldb.swig_version: + self.assertGreaterEqual(v, 0) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/Makefile new file mode 100644 index 00000000000..c5fa38429c6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +MAKE_DSYM :=NO + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py new file mode 100644 index 00000000000..ec8d1f84ded --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py @@ -0,0 +1,63 @@ +""" +Test utility functions for the frame object. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class FrameUtilsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number('main.c', + "// Find the line number here.") + + @add_test_categories(['pyapi']) + def test_frame_utils(self): + """Test utility functions for the frame object.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.c", self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.LaunchProcess() failed") + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + + import lldbsuite.test.lldbutil as lldbutil + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue(thread) + frame0 = thread.GetFrameAtIndex(0) + self.assertTrue(frame0) + frame1 = thread.GetFrameAtIndex(1) + self.assertTrue(frame1) + parent = lldbutil.get_parent_frame(frame0) + self.assertTrue(parent and parent.GetFrameID() == frame1.GetFrameID()) + frame0_args = lldbutil.get_args_as_string(frame0) + parent_args = lldbutil.get_args_as_string(parent) + self.assertTrue( + frame0_args and parent_args and "(int)val=1" in frame0_args) + if self.TraceOn(): + lldbutil.print_stacktrace(thread) + print("Current frame: %s" % frame0_args) + print("Parent frame: %s" % parent_args) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/main.c new file mode 100644 index 00000000000..f83709616e5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/frame/main.c @@ -0,0 +1,46 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +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 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; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/Makefile new file mode 100644 index 00000000000..4d11bbc8b6a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/Makefile @@ -0,0 +1,6 @@ +CFLAGS_EXTRAS := -D__STDC_LIMIT_MACROS +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp +MAKE_DSYM := NO + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py new file mode 100644 index 00000000000..050ec87fb2b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py @@ -0,0 +1,126 @@ +""" +Test the iteration protocol for some lldb container objects. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class LLDBIteratorTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line numbers to break inside main(). + self.line1 = line_number( + 'main.cpp', '// Set break point at this line.') + self.line2 = line_number('main.cpp', '// And that line.') + + @add_test_categories(['pyapi']) + def test_lldb_iter_module(self): + """Test module_iter works correctly for SBTarget -> SBModule.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.LaunchProcess() failed") + + from lldbsuite.test.lldbutil import get_description + yours = [] + for i in range(target.GetNumModules()): + yours.append(target.GetModuleAtIndex(i)) + mine = [] + for m in target.module_iter(): + mine.append(m) + + self.assertTrue(len(yours) == len(mine)) + for i in range(len(yours)): + if self.TraceOn(): + print("yours[%d]='%s'" % (i, get_description(yours[i]))) + print("mine[%d]='%s'" % (i, get_description(mine[i]))) + self.assertTrue( + yours[i] == mine[i], + "UUID+FileSpec of yours[{0}] and mine[{0}] matches".format(i)) + + @add_test_categories(['pyapi']) + def test_lldb_iter_breakpoint(self): + """Test breakpoint_iter works correctly for SBTarget -> SBBreakpoint.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line2) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + self.assertTrue(target.GetNumBreakpoints() == 2) + + from lldbsuite.test.lldbutil import get_description + yours = [] + for i in range(target.GetNumBreakpoints()): + yours.append(target.GetBreakpointAtIndex(i)) + mine = [] + for b in target.breakpoint_iter(): + mine.append(b) + + self.assertTrue(len(yours) == len(mine)) + for i in range(len(yours)): + if self.TraceOn(): + print("yours[%d]='%s'" % (i, get_description(yours[i]))) + print("mine[%d]='%s'" % (i, get_description(mine[i]))) + self.assertTrue(yours[i] == mine[i], + "ID of yours[{0}] and mine[{0}] matches".format(i)) + + @add_test_categories(['pyapi']) + def test_lldb_iter_frame(self): + """Test iterator works correctly for SBProcess->SBThread->SBFrame.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.LaunchProcess() failed") + + from lldbsuite.test.lldbutil import print_stacktrace + stopped_due_to_breakpoint = False + for thread in process: + if self.TraceOn(): + print_stacktrace(thread) + ID = thread.GetThreadID() + if thread.GetStopReason() == lldb.eStopReasonBreakpoint: + stopped_due_to_breakpoint = True + for frame in thread: + self.assertTrue(frame.GetThread().GetThreadID() == ID) + if self.TraceOn(): + print(frame) + + self.assertTrue(stopped_due_to_breakpoint) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py new file mode 100644 index 00000000000..fbb8bff4128 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py @@ -0,0 +1,105 @@ +""" +Test the iteration protocol for frame registers. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class RegistersIteratorTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line1 = line_number( + 'main.cpp', '// Set break point at this line.') + + @add_test_categories(['pyapi']) + def test_iter_registers(self): + """Test iterator works correctly for lldbutil.iter_registers().""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if not process: + self.fail("SBTarget.LaunchProcess() failed") + + import lldbsuite.test.lldbutil as lldbutil + for thread in process: + if thread.GetStopReason() == lldb.eStopReasonBreakpoint: + for frame in thread: + # Dump the registers of this frame using + # lldbutil.get_GPRs() and friends. + if self.TraceOn(): + print(frame) + + REGs = lldbutil.get_GPRs(frame) + num = len(REGs) + if self.TraceOn(): + print( + "\nNumber of general purpose registers: %d" % + num) + for reg in REGs: + self.assertTrue(reg) + if self.TraceOn(): + print("%s => %s" % (reg.GetName(), reg.GetValue())) + + REGs = lldbutil.get_FPRs(frame) + num = len(REGs) + if self.TraceOn(): + print("\nNumber of floating point registers: %d" % num) + for reg in REGs: + self.assertTrue(reg) + if self.TraceOn(): + print("%s => %s" % (reg.GetName(), reg.GetValue())) + + REGs = lldbutil.get_ESRs(frame) + if self.platformIsDarwin(): + if self.getArchitecture() != 'armv7' and self.getArchitecture() != 'armv7k': + num = len(REGs) + if self.TraceOn(): + print( + "\nNumber of exception state registers: %d" % + num) + for reg in REGs: + self.assertTrue(reg) + if self.TraceOn(): + print( + "%s => %s" % + (reg.GetName(), reg.GetValue())) + else: + self.assertIsNone(REGs) + + # And these should also work. + for kind in ["General Purpose Registers", + "Floating Point Registers"]: + REGs = lldbutil.get_registers(frame, kind) + self.assertTrue(REGs) + + REGs = lldbutil.get_registers( + frame, "Exception State Registers") + if self.platformIsDarwin(): + if self.getArchitecture() != 'armv7' and self.getArchitecture() != 'armv7k': + self.assertIsNotNone(REGs) + else: + self.assertIsNone(REGs) + + # We've finished dumping the registers for frame #0. + break diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/main.cpp new file mode 100644 index 00000000000..6823ccc4eb8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/iter/main.cpp @@ -0,0 +1,133 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +// C includes +#include <stdio.h> +#include <stdint.h> +#include <stdlib.h> + +// C++ includes +#include <chrono> +#include <mutex> +#include <random> +#include <thread> + +std::thread g_thread_1; +std::thread g_thread_2; +std::thread g_thread_3; +std::mutex g_mask_mutex; + +enum MaskAction { + eGet, + eAssign, + eClearBits +}; + +uint32_t mask_access (MaskAction action, uint32_t mask = 0); + +uint32_t +mask_access (MaskAction action, uint32_t mask) +{ + static uint32_t g_mask = 0; + + std::lock_guard<std::mutex> lock(g_mask_mutex); + switch (action) + { + case eGet: + break; + + case eAssign: + g_mask |= mask; + break; + + case eClearBits: + g_mask &= ~mask; + break; + } + return g_mask; +} + +void * +thread_func (void *arg) +{ + uint32_t thread_index = *((uint32_t *)arg); + uint32_t thread_mask = (1u << (thread_index)); + printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index); + + std::default_random_engine generator; + std::uniform_int_distribution<int> distribution(0, 3000000); + + while (mask_access(eGet) & thread_mask) + { + // random micro second sleep from zero to 3 seconds + int usec = distribution(generator); + printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec); + + std::chrono::microseconds duration(usec); + std::this_thread::sleep_for(duration); + printf ("%s (thread = %u) after usleep ...\n", __FUNCTION__, thread_index); // Set break point at this line. + } + printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index); + return NULL; +} + + +int main (int argc, char const *argv[]) +{ + uint32_t thread_index_1 = 1; + uint32_t thread_index_2 = 2; + uint32_t thread_index_3 = 3; + uint32_t thread_mask_1 = (1u << thread_index_1); + uint32_t thread_mask_2 = (1u << thread_index_2); + uint32_t thread_mask_3 = (1u << thread_index_3); + + // Make a mask that will keep all threads alive + mask_access (eAssign, thread_mask_1 | thread_mask_2 | thread_mask_3); // And that line. + + // Create 3 threads + g_thread_1 = std::thread(thread_func, (void*)&thread_index_1); + g_thread_2 = std::thread(thread_func, (void*)&thread_index_2); + g_thread_3 = std::thread(thread_func, (void*)&thread_index_3); + + char line[64]; + while (mask_access(eGet) != 0) + { + printf ("Enter thread index to kill or ENTER for all:\n"); + fflush (stdout); + // Kill threads by index, or ENTER for all threads + + if (fgets (line, sizeof(line), stdin)) + { + if (line[0] == '\n' || line[0] == '\r' || line[0] == '\0') + { + printf ("Exiting all threads...\n"); + break; + } + int32_t index = strtoul (line, NULL, 0); + switch (index) + { + case 1: mask_access (eClearBits, thread_mask_1); break; + case 2: mask_access (eClearBits, thread_mask_2); break; + case 3: mask_access (eClearBits, thread_mask_3); break; + } + continue; + } + + break; + } + + // Clear all thread bits to they all exit + mask_access (eClearBits, UINT32_MAX); + + // Join all of our threads + g_thread_1.join(); + g_thread_2.join(); + g_thread_3.join(); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/Makefile new file mode 100644 index 00000000000..6b33049a78b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/Makefile @@ -0,0 +1,6 @@ +CFLAGS_EXTRAS := -D__STDC_LIMIT_MACROS +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp +MAKE_DSYM :=NO + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py new file mode 100644 index 00000000000..123b60e4cd7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py @@ -0,0 +1,25 @@ +""" +Test SBprocess and SBThread APIs with printing of the stack traces using lldbutil. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ThreadsStackTracesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + def test_stack_traces(self): + """Test SBprocess and SBThread APIs with printing of the stack traces.""" + self.build() + (_, process, _, _) = lldbutil.run_to_source_breakpoint(self, + "// BREAK HERE", lldb.SBFileSpec("main.cpp")) + stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) + self.expect(stacktraces, exe=False, + substrs=['(int)x=4', '(int)y=6', '(int)x=3', '(int)argc=1']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/main.cpp new file mode 100644 index 00000000000..a490d8f9900 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/lldbutil/process/main.cpp @@ -0,0 +1,20 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +static int foo(int x, int y) { + return x + y; // BREAK HERE +} + +static int bar(int x) { + return foo(x + 1, x * 2); +} + +int main (int argc, char const *argv[]) +{ + return bar(argc + 2); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/Makefile new file mode 100644 index 00000000000..79209db9696 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/Makefile @@ -0,0 +1,6 @@ +CFLAGS_EXTRAS := -D__STDC_LIMIT_MACROS +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp b.cpp c.cpp +MAKE_DSYM :=NO + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py new file mode 100644 index 00000000000..95d457697e7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py @@ -0,0 +1,167 @@ +""" +Test some SBModule and SBSection APIs. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +from lldbsuite.test.lldbutil import symbol_type_to_str + + +class ModuleAndSectionAPIsTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # Py3 asserts due to a bug in SWIG. A fix for this was upstreamed into + # SWIG 3.0.8. + @skipIf(py_version=['>=', (3, 0)], swig_version=['<', (3, 0, 8)]) + @add_test_categories(['pyapi']) + def test_module_and_section(self): + """Test module and section APIs.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + self.assertTrue(target.GetNumModules() > 0) + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + print("Number of modules for the target: %d" % target.GetNumModules()) + for module in target.module_iter(): + print(module) + + # Get the executable module at index 0. + exe_module = target.GetModuleAtIndex(0) + + print("Exe module: %s" % str(exe_module)) + print("Number of sections: %d" % exe_module.GetNumSections()) + print("Number of symbols: %d" % len(exe_module)) + INDENT = ' ' * 4 + INDENT2 = INDENT * 2 + for sec in exe_module.section_iter(): + print(sec) + print( + INDENT + + "Number of subsections: %d" % + sec.GetNumSubSections()) + if sec.GetNumSubSections() == 0: + for sym in exe_module.symbol_in_section_iter(sec): + print(INDENT + str(sym)) + print( + INDENT + + "symbol type: %s" % + symbol_type_to_str( + sym.GetType())) + else: + for subsec in sec: + print(INDENT + str(subsec)) + # Now print the symbols belonging to the subsection.... + for sym in exe_module.symbol_in_section_iter(subsec): + print(INDENT2 + str(sym)) + print( + INDENT2 + + "symbol type: %s" % + symbol_type_to_str( + sym.GetType())) + + @add_test_categories(['pyapi']) + def test_module_and_section_boundary_condition(self): + """Test module and section APIs by passing None when it expects a Python string.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + self.assertTrue(target.GetNumModules() > 0) + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + print("Number of modules for the target: %d" % target.GetNumModules()) + for module in target.module_iter(): + print(module) + + # Get the executable module at index 0. + exe_module = target.GetModuleAtIndex(0) + + print("Exe module: %s" % str(exe_module)) + print("Number of sections: %d" % exe_module.GetNumSections()) + + # Boundary condition testings. Should not crash lldb! + exe_module.FindFirstType(None) + exe_module.FindTypes(None) + exe_module.FindGlobalVariables(target, None, 1) + exe_module.FindFunctions(None, 0) + exe_module.FindSection(None) + + # Get the section at index 1. + if exe_module.GetNumSections() > 1: + sec1 = exe_module.GetSectionAtIndex(1) + print(sec1) + else: + sec1 = None + + if sec1: + sec1.FindSubSection(None) + + @add_test_categories(['pyapi']) + def test_module_compile_unit_iter(self): + """Test module's compile unit iterator APIs.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + self.assertTrue(target.GetNumModules() > 0) + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + print("Number of modules for the target: %d" % target.GetNumModules()) + for module in target.module_iter(): + print(module) + + # Get the executable module at index 0. + exe_module = target.GetModuleAtIndex(0) + + print("Exe module: %s" % str(exe_module)) + print("Number of compile units: %d" % exe_module.GetNumCompileUnits()) + INDENT = ' ' * 4 + INDENT2 = INDENT * 2 + for cu in exe_module.compile_unit_iter(): + print(cu) + + @add_test_categories(['pyapi']) + def test_find_compile_units(self): + """Exercise SBModule.FindCompileUnits() API.""" + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.find_compile_units(self.getBuildArtifact('b.out')) + + def find_compile_units(self, exe): + """Exercise SBModule.FindCompileUnits() API.""" + source_name_list = ["main.cpp", "b.cpp", "c.cpp"] + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + num_modules = target.GetNumModules() + for i in range(num_modules): + module = target.GetModuleAtIndex(i) + for source_name in source_name_list: + list = module.FindCompileUnits(lldb.SBFileSpec(source_name, False)) + for sc in list: + self.assertTrue( + sc.GetCompileUnit().GetFileSpec().GetFilename() == + source_name) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/b.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/b.cpp new file mode 100644 index 00000000000..4e3e54138e5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/b.cpp @@ -0,0 +1,3 @@ +int b_function(int input) { + return input * 2; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/c.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/c.cpp new file mode 100644 index 00000000000..3c87bfe30c6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/c.cpp @@ -0,0 +1,3 @@ +int c_function(int input) { + return input * 3; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/main.cpp new file mode 100644 index 00000000000..943123b4059 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/module_section/main.cpp @@ -0,0 +1,5 @@ +#include <stdio.h> + +int main() { + printf("Hello World\n"); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/name_lookup/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/name_lookup/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/name_lookup/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/name_lookup/TestNameLookup.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/name_lookup/TestNameLookup.py new file mode 100644 index 00000000000..6cd8d4fa9c4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/name_lookup/TestNameLookup.py @@ -0,0 +1,63 @@ +""" +Test SBTarget APIs. +""" + + + +import unittest2 +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestNameLookup(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber='llvm.org/pr21765') + def test_target(self): + """Exercise SBTarget.FindFunctions() with various name masks. + + A previous regression caused mangled names to not be able to be looked up. + This test verifies that using a mangled name with eFunctionNameTypeFull works + and that using a function basename with eFunctionNameTypeFull works for all + C++ functions that are at the global namespace level.""" + self.build(); + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + exe_module = target.FindModule(target.GetExecutable()) + + c_name_to_symbol = {} + cpp_name_to_symbol = {} + mangled_to_symbol = {} + num_symbols = exe_module.GetNumSymbols(); + for i in range(num_symbols): + symbol = exe_module.GetSymbolAtIndex(i); + name = symbol.GetName() + if name and 'unique_function_name' in name and '__PRETTY_FUNCTION__' not in name: + mangled = symbol.GetMangledName() + if mangled: + mangled_to_symbol[mangled] = symbol + if name: + cpp_name_to_symbol[name] = symbol + elif name: + c_name_to_symbol[name] = symbol + + # Make sure each mangled name turns up exactly one match when looking up + # functions by full name and using the mangled name as the name in the + # lookup + self.assertGreaterEqual(len(mangled_to_symbol), 6) + for mangled in mangled_to_symbol.keys(): + symbol_contexts = target.FindFunctions(mangled, lldb.eFunctionNameTypeFull) + self.assertTrue(symbol_contexts.GetSize() == 1) + for symbol_context in symbol_contexts: + self.assertTrue(symbol_context.GetFunction().IsValid()) + self.assertTrue(symbol_context.GetSymbol().IsValid()) + + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/name_lookup/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/name_lookup/main.cpp new file mode 100644 index 00000000000..b38208ce2a3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/name_lookup/main.cpp @@ -0,0 +1,54 @@ +#include <stdio.h> + +extern "C" int unique_function_name(int i) +{ + return puts(__PRETTY_FUNCTION__); +} + +int unique_function_name() +{ + return puts(__PRETTY_FUNCTION__); +} + +int unique_function_name(float f) +{ + return puts(__PRETTY_FUNCTION__); +} + +namespace e +{ + int unique_function_name() + { + return puts(__PRETTY_FUNCTION__); + } + + namespace g + { + int unique_function_name() + { + return puts(__PRETTY_FUNCTION__); + } + } +} + +class g +{ +public: + int unique_function_name() + { + return puts(__PRETTY_FUNCTION__); + } + + int unique_function_name(int i) + { + return puts(__PRETTY_FUNCTION__); + } +}; + +int main (int argc, char const *argv[]) +{ + g g; + g.unique_function_name(); + g.unique_function_name(argc); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/objc_type/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/objc_type/Makefile new file mode 100644 index 00000000000..8b322ff320b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/objc_type/Makefile @@ -0,0 +1,8 @@ +OBJC_SOURCES := main.m + +CFLAGS_EXTRAS := -w + + + +LD_EXTRAS := -framework Foundation +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py new file mode 100644 index 00000000000..37f53758d44 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py @@ -0,0 +1,70 @@ +""" +Test SBType for ObjC classes. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ObjCSBTypeTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + self.line = line_number("main.m", '// Break at this line') + + @skipUnlessDarwin + @add_test_categories(['pyapi']) + def test(self): + """Test SBType for ObjC classes.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation("main.m", self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Get Frame #0. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + + aBar = self.frame().FindVariable("aBar") + aBarType = aBar.GetType() + self.assertTrue(aBarType.IsValid(), "Bar should be a valid data type") + self.assertTrue( + aBarType.GetName() == "Bar *", + "Bar has the right name") + + self.assertTrue( + aBarType.GetNumberOfDirectBaseClasses() == 1, + "Bar has a superclass") + aFooType = aBarType.GetDirectBaseClassAtIndex(0) + + self.assertTrue(aFooType.IsValid(), "Foo should be a valid data type") + self.assertTrue(aFooType.GetName() == "Foo", "Foo has the right name") + + self.assertTrue(aBarType.GetNumberOfFields() == 1, "Bar has a field") + aBarField = aBarType.GetFieldAtIndex(0) + + self.assertTrue( + aBarField.GetName() == "_iVar", + "The field has the right name") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/objc_type/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/objc_type/main.m new file mode 100644 index 00000000000..a2a7b0b4bce --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/objc_type/main.m @@ -0,0 +1,51 @@ +//===-- main.m ------------------------------------------------*- ObjC -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#import <Foundation/Foundation.h> + +@interface Foo: NSObject +{} +- (id) init; +@end + +@interface Bar: Foo +{ + int _iVar; +} +- (id) init; +@end + +@implementation Foo + +- (id) init +{ + self = [super init]; + return self; +} + +@end + +@implementation Bar + +- (id) init +{ + self = [super init]; + if (self) + self->_iVar = 5; + return self; +} + +@end + +int main() +{ + Bar* aBar = [Bar new]; + id nothing = [aBar noSuchSelector]; // Break at this line + return 0; +} + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py new file mode 100644 index 00000000000..d26933a4289 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py @@ -0,0 +1,401 @@ +""" +Test SBProcess APIs, including ReadMemory(), WriteMemory(), and others. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test.lldbutil import get_stopped_thread, state_type_to_str + + +class ProcessAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.line = line_number( + "main.cpp", + "// Set break point at this line and check variable 'my_char'.") + + @add_test_categories(['pyapi']) + def test_read_memory(self): + """Test Python SBProcess.ReadMemory() API.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + frame = thread.GetFrameAtIndex(0) + + # Get the SBValue for the global variable 'my_char'. + val = frame.FindValue("my_char", lldb.eValueTypeVariableGlobal) + self.DebugSBValue(val) + + # Due to the typemap magic (see lldb.swig), we pass in 1 to ReadMemory and + # expect to get a Python string as the result object! + error = lldb.SBError() + self.assertFalse(val.TypeIsPointerType()) + content = process.ReadMemory( + val.AddressOf().GetValueAsUnsigned(), 1, error) + if not error.Success(): + self.fail("SBProcess.ReadMemory() failed") + if self.TraceOn(): + print("memory content:", content) + + self.expect( + content, + "Result from SBProcess.ReadMemory() matches our expected output: 'x'", + exe=False, + startstr=b'x') + + # Read (char *)my_char_ptr. + val = frame.FindValue("my_char_ptr", lldb.eValueTypeVariableGlobal) + self.DebugSBValue(val) + cstring = process.ReadCStringFromMemory( + val.GetValueAsUnsigned(), 256, error) + if not error.Success(): + self.fail("SBProcess.ReadCStringFromMemory() failed") + if self.TraceOn(): + print("cstring read is:", cstring) + + self.expect( + cstring, + "Result from SBProcess.ReadCStringFromMemory() matches our expected output", + exe=False, + startstr='Does it work?') + + # Get the SBValue for the global variable 'my_cstring'. + val = frame.FindValue("my_cstring", lldb.eValueTypeVariableGlobal) + self.DebugSBValue(val) + + # Due to the typemap magic (see lldb.swig), we pass in 256 to read at most 256 bytes + # from the address, and expect to get a Python string as the result + # object! + self.assertFalse(val.TypeIsPointerType()) + cstring = process.ReadCStringFromMemory( + val.AddressOf().GetValueAsUnsigned(), 256, error) + if not error.Success(): + self.fail("SBProcess.ReadCStringFromMemory() failed") + if self.TraceOn(): + print("cstring read is:", cstring) + + self.expect( + cstring, + "Result from SBProcess.ReadCStringFromMemory() matches our expected output", + exe=False, + startstr='lldb.SBProcess.ReadCStringFromMemory() works!') + + # Get the SBValue for the global variable 'my_uint32'. + val = frame.FindValue("my_uint32", lldb.eValueTypeVariableGlobal) + self.DebugSBValue(val) + + # Due to the typemap magic (see lldb.swig), we pass in 4 to read 4 bytes + # from the address, and expect to get an int as the result! + self.assertFalse(val.TypeIsPointerType()) + my_uint32 = process.ReadUnsignedFromMemory( + val.AddressOf().GetValueAsUnsigned(), 4, error) + if not error.Success(): + self.fail("SBProcess.ReadCStringFromMemory() failed") + if self.TraceOn(): + print("uint32 read is:", my_uint32) + + if my_uint32 != 12345: + self.fail( + "Result from SBProcess.ReadUnsignedFromMemory() does not match our expected output") + + @add_test_categories(['pyapi']) + def test_write_memory(self): + """Test Python SBProcess.WriteMemory() API.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + frame = thread.GetFrameAtIndex(0) + + # Get the SBValue for the global variable 'my_char'. + val = frame.FindValue("my_char", lldb.eValueTypeVariableGlobal) + self.DebugSBValue(val) + + # If the variable does not have a load address, there's no sense + # continuing. + if not val.GetLocation().startswith("0x"): + return + + # OK, let's get the hex location of the variable. + location = int(val.GetLocation(), 16) + + # The program logic makes the 'my_char' variable to have memory content as 'x'. + # But we want to use the WriteMemory() API to assign 'a' to the + # variable. + + # Now use WriteMemory() API to write 'a' into the global variable. + error = lldb.SBError() + result = process.WriteMemory(location, 'a', error) + if not error.Success() or result != 1: + self.fail("SBProcess.WriteMemory() failed") + + # Read from the memory location. This time it should be 'a'. + # Due to the typemap magic (see lldb.swig), we pass in 1 to ReadMemory and + # expect to get a Python string as the result object! + content = process.ReadMemory(location, 1, error) + if not error.Success(): + self.fail("SBProcess.ReadMemory() failed") + if self.TraceOn(): + print("memory content:", content) + + self.expect( + content, + "Result from SBProcess.ReadMemory() matches our expected output: 'a'", + exe=False, + startstr=b'a') + + @add_test_categories(['pyapi']) + def test_access_my_int(self): + """Test access 'my_int' using Python SBProcess.GetByteOrder() and other APIs.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + frame = thread.GetFrameAtIndex(0) + + # Get the SBValue for the global variable 'my_int'. + val = frame.FindValue("my_int", lldb.eValueTypeVariableGlobal) + self.DebugSBValue(val) + + # If the variable does not have a load address, there's no sense + # continuing. + if not val.GetLocation().startswith("0x"): + return + + # OK, let's get the hex location of the variable. + location = int(val.GetLocation(), 16) + + # Note that the canonical from of the bytearray is little endian. + from lldbsuite.test.lldbutil import int_to_bytearray, bytearray_to_int + + byteSize = val.GetByteSize() + bytes = int_to_bytearray(256, byteSize) + + byteOrder = process.GetByteOrder() + if byteOrder == lldb.eByteOrderBig: + bytes.reverse() + elif byteOrder == lldb.eByteOrderLittle: + pass + else: + # Neither big endian nor little endian? Return for now. + # Add more logic here if we want to handle other types. + return + + # The program logic makes the 'my_int' variable to have int type and value of 0. + # But we want to use the WriteMemory() API to assign 256 to the + # variable. + + # Now use WriteMemory() API to write 256 into the global variable. + error = lldb.SBError() + result = process.WriteMemory(location, bytes, error) + if not error.Success() or result != byteSize: + self.fail("SBProcess.WriteMemory() failed") + + # Make sure that the val we got originally updates itself to notice the + # change: + self.expect( + val.GetValue(), + "SBProcess.ReadMemory() successfully writes (int)256 to the memory location for 'my_int'", + exe=False, + startstr='256') + + # And for grins, get the SBValue for the global variable 'my_int' + # again, to make sure that also tracks the new value: + val = frame.FindValue("my_int", lldb.eValueTypeVariableGlobal) + self.expect( + val.GetValue(), + "SBProcess.ReadMemory() successfully writes (int)256 to the memory location for 'my_int'", + exe=False, + startstr='256') + + # Now read the memory content. The bytearray should have (byte)1 as + # the second element. + content = process.ReadMemory(location, byteSize, error) + if not error.Success(): + self.fail("SBProcess.ReadMemory() failed") + + # The bytearray_to_int utility function expects a little endian + # bytearray. + if byteOrder == lldb.eByteOrderBig: + content = bytearray(content, 'ascii') + content.reverse() + + new_value = bytearray_to_int(content, byteSize) + if new_value != 256: + self.fail("Memory content read from 'my_int' does not match (int)256") + + # Dump the memory content.... + if self.TraceOn(): + for i in content: + print("byte:", i) + + @add_test_categories(['pyapi']) + def test_remote_launch(self): + """Test SBProcess.RemoteLaunch() API with a process not in eStateConnected, and it should fail.""" + self.build() + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + if self.TraceOn(): + print("process state:", state_type_to_str(process.GetState())) + self.assertTrue(process.GetState() != lldb.eStateConnected) + + error = lldb.SBError() + success = process.RemoteLaunch( + None, None, None, None, None, None, 0, False, error) + self.assertTrue( + not success, + "RemoteLaunch() should fail for process state != eStateConnected") + + @add_test_categories(['pyapi']) + def test_get_num_supported_hardware_watchpoints(self): + """Test SBProcess.GetNumSupportedHardwareWatchpoints() API with a process.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + error = lldb.SBError() + num = process.GetNumSupportedHardwareWatchpoints(error) + if self.TraceOn() and error.Success(): + print("Number of supported hardware watchpoints: %d" % num) + + @add_test_categories(['pyapi']) + @no_debug_info_test + def test_get_process_info(self): + """Test SBProcess::GetProcessInfo() API with a locally launched process.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Launch the process and stop at the entry point. + launch_info = lldb.SBLaunchInfo(None) + launch_info.SetWorkingDirectory(self.get_process_working_directory()) + launch_flags = launch_info.GetLaunchFlags() + launch_flags |= lldb.eLaunchFlagStopAtEntry + launch_info.SetLaunchFlags(launch_flags) + error = lldb.SBError() + process = target.Launch(launch_info, error) + + if not error.Success(): + self.fail("Failed to launch process") + + # Verify basic process info can be retrieved successfully + process_info = process.GetProcessInfo() + self.assertTrue(process_info.IsValid()) + file_spec = process_info.GetExecutableFile() + self.assertTrue(file_spec.IsValid()) + process_name = process_info.GetName() + self.assertIsNotNone(process_name, "Process has a name") + self.assertGreater(len(process_name), 0, "Process name isn't blank") + self.assertEqual(file_spec.GetFilename(), "a.out") + self.assertNotEqual( + process_info.GetProcessID(), lldb.LLDB_INVALID_PROCESS_ID, + "Process ID is valid") + + # Additional process info varies by platform, so just check that + # whatever info was retrieved is consistent and nothing blows up. + if process_info.UserIDIsValid(): + self.assertNotEqual( + process_info.GetUserID(), lldb.UINT32_MAX, + "Process user ID is valid") + else: + self.assertEqual( + process_info.GetUserID(), lldb.UINT32_MAX, + "Process user ID is invalid") + + if process_info.GroupIDIsValid(): + self.assertNotEqual( + process_info.GetGroupID(), lldb.UINT32_MAX, + "Process group ID is valid") + else: + self.assertEqual( + process_info.GetGroupID(), lldb.UINT32_MAX, + "Process group ID is invalid") + + if process_info.EffectiveUserIDIsValid(): + self.assertNotEqual( + process_info.GetEffectiveUserID(), lldb.UINT32_MAX, + "Process effective user ID is valid") + else: + self.assertEqual( + process_info.GetEffectiveUserID(), lldb.UINT32_MAX, + "Process effective user ID is invalid") + + if process_info.EffectiveGroupIDIsValid(): + self.assertNotEqual( + process_info.GetEffectiveGroupID(), lldb.UINT32_MAX, + "Process effective group ID is valid") + else: + self.assertEqual( + process_info.GetEffectiveGroupID(), lldb.UINT32_MAX, + "Process effective group ID is invalid") + + process_info.GetParentProcessID() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/io/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/io/Makefile new file mode 100644 index 00000000000..4aa78325888 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/io/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +EXE := process_io + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py new file mode 100644 index 00000000000..365d486650f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py @@ -0,0 +1,239 @@ +"""Test Python APIs for process IO.""" + +from __future__ import print_function + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ProcessIOTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setup_test(self): + # Get the full path to our executable to be debugged. + self.exe = self.getBuildArtifact("process_io") + self.local_input_file = self.getBuildArtifact("input.txt") + self.local_output_file = self.getBuildArtifact("output.txt") + self.local_error_file = self.getBuildArtifact("error.txt") + + self.input_file = os.path.join( + self.get_process_working_directory(), "input.txt") + self.output_file = os.path.join( + self.get_process_working_directory(), "output.txt") + self.error_file = os.path.join( + self.get_process_working_directory(), "error.txt") + self.lines = ["Line 1", "Line 2", "Line 3"] + + @skipIfWindows # stdio manipulation unsupported on Windows + @add_test_categories(['pyapi']) + @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") + @skipIfDarwinEmbedded # I/O redirection like this is not supported on remote iOS devices yet <rdar://problem/54581135> + def test_stdin_by_api(self): + """Exercise SBProcess.PutSTDIN().""" + self.setup_test() + self.build() + self.create_target() + self.run_process(True) + output = self.process.GetSTDOUT(1000) + self.check_process_output(output, output) + + @skipIfWindows # stdio manipulation unsupported on Windows + @add_test_categories(['pyapi']) + @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") + def test_stdin_redirection(self): + """Exercise SBLaunchInfo::AddOpenFileAction() for STDIN without specifying STDOUT or STDERR.""" + self.setup_test() + self.build() + self.create_target() + self.redirect_stdin() + self.run_process(False) + output = self.process.GetSTDOUT(1000) + self.check_process_output(output, output) + + @skipIfWindows # stdio manipulation unsupported on Windows + @add_test_categories(['pyapi']) + @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") + @skipIfDarwinEmbedded # debugserver can't create/write files on the device + def test_stdout_redirection(self): + """Exercise SBLaunchInfo::AddOpenFileAction() for STDOUT without specifying STDIN or STDERR.""" + self.setup_test() + self.build() + self.create_target() + self.redirect_stdout() + self.run_process(True) + output = self.read_output_file_and_delete() + error = self.process.GetSTDOUT(1000) + self.check_process_output(output, error) + + @skipIfWindows # stdio manipulation unsupported on Windows + @add_test_categories(['pyapi']) + @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") + @skipIfDarwinEmbedded # debugserver can't create/write files on the device + def test_stderr_redirection(self): + """Exercise SBLaunchInfo::AddOpenFileAction() for STDERR without specifying STDIN or STDOUT.""" + self.setup_test() + self.build() + self.create_target() + self.redirect_stderr() + self.run_process(True) + output = self.process.GetSTDOUT(1000) + error = self.read_error_file_and_delete() + self.check_process_output(output, error) + + @skipIfWindows # stdio manipulation unsupported on Windows + @add_test_categories(['pyapi']) + @expectedFlakeyLinux(bugnumber="llvm.org/pr26437") + @skipIfDarwinEmbedded # debugserver can't create/write files on the device + def test_stdout_stderr_redirection(self): + """Exercise SBLaunchInfo::AddOpenFileAction() for STDOUT and STDERR without redirecting STDIN.""" + self.setup_test() + self.build() + self.create_target() + self.redirect_stdout() + self.redirect_stderr() + self.run_process(True) + output = self.read_output_file_and_delete() + error = self.read_error_file_and_delete() + self.check_process_output(output, error) + + # target_file - path on local file system or remote file system if running remote + # local_file - path on local system + def read_file_and_delete(self, target_file, local_file): + if lldb.remote_platform: + self.runCmd('platform get-file "{remote}" "{local}"'.format( + remote=target_file, local=local_file)) + + self.assertTrue( + os.path.exists(local_file), + 'Make sure "{local}" file exists'.format( + local=local_file)) + f = open(local_file, 'r') + contents = f.read() + f.close() + + # TODO: add 'platform delete-file' file command + # if lldb.remote_platform: + # self.runCmd('platform delete-file "{remote}"'.format(remote=target_file)) + os.unlink(local_file) + return contents + + def read_output_file_and_delete(self): + return self.read_file_and_delete( + self.output_file, self.local_output_file) + + def read_error_file_and_delete(self): + return self.read_file_and_delete( + self.error_file, self.local_error_file) + + def create_target(self): + '''Create the target and launch info that will be used by all tests''' + self.target = self.dbg.CreateTarget(self.exe) + self.launch_info = lldb.SBLaunchInfo([self.exe]) + self.launch_info.SetWorkingDirectory( + self.get_process_working_directory()) + + def redirect_stdin(self): + '''Redirect STDIN (file descriptor 0) to use our input.txt file + + Make the input.txt file to use when redirecting STDIN, setup a cleanup action + to delete the input.txt at the end of the test in case exceptions are thrown, + and redirect STDIN in the launch info.''' + f = open(self.local_input_file, 'w') + for line in self.lines: + f.write(line + "\n") + f.close() + + if lldb.remote_platform: + self.runCmd('platform put-file "{local}" "{remote}"'.format( + local=self.local_input_file, remote=self.input_file)) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + os.unlink(self.local_input_file) + # TODO: add 'platform delete-file' file command + # if lldb.remote_platform: + # self.runCmd('platform delete-file "{remote}"'.format(remote=self.input_file)) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + self.launch_info.AddOpenFileAction(0, self.input_file, True, False) + + def redirect_stdout(self): + '''Redirect STDOUT (file descriptor 1) to use our output.txt file''' + self.launch_info.AddOpenFileAction(1, self.output_file, False, True) + + def redirect_stderr(self): + '''Redirect STDERR (file descriptor 2) to use our error.txt file''' + self.launch_info.AddOpenFileAction(2, self.error_file, False, True) + + def run_process(self, put_stdin): + '''Run the process to completion and optionally put lines to STDIN via the API if "put_stdin" is True''' + # Set the breakpoints + self.breakpoint = self.target.BreakpointCreateBySourceRegex( + 'Set breakpoint here', lldb.SBFileSpec("main.c")) + self.assertTrue( + self.breakpoint.GetNumLocations() > 0, + VALID_BREAKPOINT) + + # Launch the process, and do not stop at the entry point. + error = lldb.SBError() + # This should launch the process and it should exit by the time we get back + # because we have synchronous mode enabled + self.process = self.target.Launch(self.launch_info, error) + + self.assertTrue( + error.Success(), + "Make sure process launched successfully") + self.assertTrue(self.process, PROCESS_IS_VALID) + + if self.TraceOn(): + print("process launched.") + + # Frame #0 should be at our breakpoint. + threads = lldbutil.get_threads_stopped_at_breakpoint( + self.process, self.breakpoint) + + self.assertTrue(len(threads) == 1) + self.thread = threads[0] + self.frame = self.thread.frames[0] + self.assertTrue(self.frame, "Frame 0 is valid.") + + if self.TraceOn(): + print("process stopped at breakpoint, sending STDIN via LLDB API.") + + # Write data to stdin via the public API if we were asked to + if put_stdin: + for line in self.lines: + self.process.PutSTDIN(line + "\n") + + # Let process continue so it will exit + self.process.Continue() + state = self.process.GetState() + self.assertTrue(state == lldb.eStateExited, PROCESS_IS_VALID) + + def check_process_output(self, output, error): + # Since we launched the process without specifying stdin/out/err, + # a pseudo terminal is used for stdout/err, and we are satisfied + # once "input line=>1" appears in stdout. + # See also main.c. + if self.TraceOn(): + print("output = '%s'" % output) + print("error = '%s'" % error) + + for line in self.lines: + check_line = 'input line to stdout: %s' % (line) + self.assertTrue( + check_line in output, + "verify stdout line shows up in STDOUT") + for line in self.lines: + check_line = 'input line to stderr: %s' % (line) + self.assertTrue( + check_line in error, + "verify stderr line shows up in STDERR") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/io/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/io/main.c new file mode 100644 index 00000000000..c9a5707f0e1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/io/main.c @@ -0,0 +1,19 @@ +#include <stdio.h> + +int main(int argc, char const *argv[]) { + printf("Hello world.\n"); // Set breakpoint here + char line[100]; + if (fgets(line, sizeof(line), stdin)) { + fprintf(stdout, "input line to stdout: %s", line); + fprintf(stderr, "input line to stderr: %s", line); + } + if (fgets(line, sizeof(line), stdin)) { + fprintf(stdout, "input line to stdout: %s", line); + fprintf(stderr, "input line to stderr: %s", line); + } + if (fgets(line, sizeof(line), stdin)) { + fprintf(stdout, "input line to stdout: %s", line); + fprintf(stderr, "input line to stderr: %s", line); + } + printf("Exiting now\n"); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/main.cpp new file mode 100644 index 00000000000..32c6dee8044 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/main.cpp @@ -0,0 +1,30 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +// This simple program is to test the lldb Python API related to process. + +char my_char = 'u'; +char my_cstring[] = "lldb.SBProcess.ReadCStringFromMemory() works!"; +char *my_char_ptr = (char *)"Does it work?"; +uint32_t my_uint32 = 12345; +int my_int = 0; + +int main (int argc, char const *argv[]) +{ + for (int i = 0; i < 3; ++i) { + printf("my_char='%c'\n", my_char); + ++my_char; + } + + printf("after the loop: my_char='%c'\n", my_char); // 'my_char' should print out as 'x'. + + return 0; // Set break point at this line and check variable 'my_char'. + // Use lldb Python API to set memory content for my_int and check the result. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/read-mem-cstring/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/read-mem-cstring/Makefile new file mode 100644 index 00000000000..6bc1b47f1f3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/read-mem-cstring/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +EXE := read-mem-cstring + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/read-mem-cstring/TestReadMemCString.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/read-mem-cstring/TestReadMemCString.py new file mode 100644 index 00000000000..fc26c3b6c86 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/read-mem-cstring/TestReadMemCString.py @@ -0,0 +1,58 @@ +"""Test reading c-strings from memory via SB API.""" + + +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestReadMemCString(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_read_memory_c_string(self): + """Test corner case behavior of SBProcess::ReadCStringFromMemory""" + self.build() + self.dbg.SetAsync(False) + + self.main_source = "main.c" + self.main_source_path = os.path.join(self.getSourceDir(), + self.main_source) + self.main_source_spec = lldb.SBFileSpec(self.main_source_path) + self.exe = self.getBuildArtifact("read-mem-cstring") + + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint( + self, 'breakpoint here', self.main_source_spec, None, self.exe) + + frame = thread.GetFrameAtIndex(0) + + err = lldb.SBError() + + empty_str_addr = frame.FindVariable("empty_string").GetValueAsUnsigned(err) + self.assertTrue(err.Success()) + self.assertTrue(empty_str_addr != lldb.LLDB_INVALID_ADDRESS) + + one_letter_str_addr = frame.FindVariable("one_letter_string").GetValueAsUnsigned(err) + self.assertTrue(err.Success()) + self.assertTrue(one_letter_str_addr != lldb.LLDB_INVALID_ADDRESS) + + invalid_memory_str_addr = frame.FindVariable("invalid_memory_string").GetValueAsUnsigned(err) + self.assertTrue(err.Success()) + self.assertTrue(invalid_memory_str_addr != lldb.LLDB_INVALID_ADDRESS) + + # Important: An empty (0-length) c-string must come back as a Python string, not a + # None object. + empty_str = process.ReadCStringFromMemory(empty_str_addr, 2048, err) + self.assertTrue(err.Success()) + self.assertTrue(empty_str == "") + + one_letter_string = process.ReadCStringFromMemory(one_letter_str_addr, 2048, err) + self.assertTrue(err.Success()) + self.assertTrue(one_letter_string == "1") + + invalid_memory_string = process.ReadCStringFromMemory(invalid_memory_str_addr, 2048, err) + self.assertTrue(err.Fail()) + self.assertTrue(invalid_memory_string == "" or invalid_memory_string == None) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/read-mem-cstring/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/read-mem-cstring/main.c new file mode 100644 index 00000000000..03c66741712 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process/read-mem-cstring/main.c @@ -0,0 +1,11 @@ +#include <stdlib.h> +int main () +{ + const char *empty_string = ""; + const char *one_letter_string = "1"; + // This expects that lower 4k of memory will be mapped unreadable, which most + // OSs do (to catch null pointer dereferences). + const char *invalid_memory_string = (char*)0x100; + + return empty_string[0] + one_letter_string[0]; // breakpoint here +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbdata/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbdata/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbdata/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py new file mode 100644 index 00000000000..a12f683d601 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py @@ -0,0 +1,521 @@ +"""Test the SBData APIs.""" + + + +from math import fabs +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SBDataAPICase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break on inside main.cpp. + self.line = line_number('main.cpp', '// set breakpoint here') + + @add_test_categories(['pyapi']) + def test_byte_order_and_address_byte_size(self): + """Test the SBData::SetData() to ensure the byte order and address + byte size are obeyed""" + addr_data = b'\x11\x22\x33\x44\x55\x66\x77\x88' + error = lldb.SBError() + data = lldb.SBData() + data.SetData(error, addr_data, lldb.eByteOrderBig, 4) + addr = data.GetAddress(error, 0) + self.assertTrue(addr == 0x11223344); + data.SetData(error, addr_data, lldb.eByteOrderBig, 8) + addr = data.GetAddress(error, 0) + self.assertTrue(addr == 0x1122334455667788); + data.SetData(error, addr_data, lldb.eByteOrderLittle, 4) + addr = data.GetAddress(error, 0) + self.assertTrue(addr == 0x44332211); + data.SetData(error, addr_data, lldb.eByteOrderLittle, 8) + addr = data.GetAddress(error, 0) + self.assertTrue(addr == 0x8877665544332211); + + @add_test_categories(['pyapi']) + def test_with_run_command(self): + """Test the SBData APIs.""" + self.build() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + target = self.dbg.GetSelectedTarget() + + process = target.GetProcess() + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertIsNotNone(thread) + + frame = thread.GetSelectedFrame() + foobar = frame.FindVariable('foobar') + self.assertTrue(foobar.IsValid()) + data = foobar.GetPointeeData(0, 2) + offset = 0 + error = lldb.SBError() + + self.assert_data(data.GetUnsignedInt32, offset, 1) + offset += 4 + low = data.GetSignedInt16(error, offset) + self.assertTrue(error.Success()) + offset += 2 + high = data.GetSignedInt16(error, offset) + self.assertTrue(error.Success()) + offset += 2 + self.assertTrue( + (low == 9 and high == 0) or ( + low == 0 and high == 9), + 'foo[0].b == 9') + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 3.14) < 1, + 'foo[0].c == 3.14') + self.assertTrue(error.Success()) + offset += 4 + self.assert_data(data.GetUnsignedInt32, offset, 8) + offset += 4 + self.assert_data(data.GetUnsignedInt32, offset, 5) + offset += 4 + + self.runCmd("n") + + offset = 16 + + self.assert_data(data.GetUnsignedInt32, offset, 5) + + data = foobar.GetPointeeData(1, 1) + + offset = 0 + + self.assert_data(data.GetSignedInt32, offset, 8) + offset += 4 + self.assert_data(data.GetSignedInt32, offset, 7) + offset += 8 + self.assertTrue( + data.GetUnsignedInt32( + error, + offset) == 0, + 'do not read beyond end') + self.assertTrue(not error.Success()) + error.Clear() # clear the error for the next test + + star_foobar = foobar.Dereference() + self.assertTrue(star_foobar.IsValid()) + + data = star_foobar.GetData() + + offset = 0 + self.assert_data(data.GetUnsignedInt32, offset, 1) + offset += 4 + self.assert_data(data.GetUnsignedInt32, offset, 9) + + foobar_addr = star_foobar.GetLoadAddress() + foobar_addr += 12 + + # http://llvm.org/bugs/show_bug.cgi?id=11579 + # lldb::SBValue::CreateValueFromAddress does not verify SBType::GetPointerType succeeds + # This should not crash LLDB. + nothing = foobar.CreateValueFromAddress( + "nothing", foobar_addr, star_foobar.GetType().GetBasicType( + lldb.eBasicTypeInvalid)) + + new_foobar = foobar.CreateValueFromAddress( + "f00", foobar_addr, star_foobar.GetType()) + self.assertTrue(new_foobar.IsValid()) + data = new_foobar.GetData() + + self.assertTrue(data.uint32[0] == 8, 'then foo[1].a == 8') + self.assertTrue(data.uint32[1] == 7, 'then foo[1].b == 7') + # exploiting that sizeof(uint32) == sizeof(float) + self.assertTrue(fabs(data.float[2] - 3.14) < 1, 'foo[1].c == 3.14') + + self.runCmd("n") + + offset = 0 + self.assert_data(data.GetUnsignedInt32, offset, 8) + offset += 4 + self.assert_data(data.GetUnsignedInt32, offset, 7) + offset += 4 + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 3.14) < 1, + 'foo[1].c == 3.14') + self.assertTrue(error.Success()) + + data = new_foobar.GetData() + + offset = 0 + self.assert_data(data.GetUnsignedInt32, offset, 8) + offset += 4 + self.assert_data(data.GetUnsignedInt32, offset, 7) + offset += 4 + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 6.28) < 1, + 'foo[1].c == 6.28') + self.assertTrue(error.Success()) + + self.runCmd("n") + + barfoo = frame.FindVariable('barfoo') + + data = barfoo.GetData() + offset = 0 + self.assert_data(data.GetUnsignedInt32, offset, 1) + offset += 4 + self.assert_data(data.GetUnsignedInt32, offset, 2) + offset += 4 + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 3) < 1, + 'barfoo[0].c == 3') + self.assertTrue(error.Success()) + offset += 4 + self.assert_data(data.GetUnsignedInt32, offset, 4) + offset += 4 + self.assert_data(data.GetUnsignedInt32, offset, 5) + offset += 4 + self.assertTrue( + fabs( + data.GetFloat( + error, + offset) - + 6) < 1, + 'barfoo[1].c == 6') + self.assertTrue(error.Success()) + + new_object = barfoo.CreateValueFromData( + "new_object", data, barfoo.GetType().GetBasicType( + lldb.eBasicTypeInt)) + self.assertTrue(new_object.GetValue() == "1", 'new_object == 1') + + if data.GetByteOrder() == lldb.eByteOrderBig: + data.SetData( + error, + '\0\0\0A', + data.GetByteOrder(), + data.GetAddressByteSize()) + else: + data.SetData( + error, + 'A\0\0\0', + data.GetByteOrder(), + data.GetAddressByteSize()) + self.assertTrue(error.Success()) + + data2 = lldb.SBData() + data2.SetData( + error, + 'BCD', + data.GetByteOrder(), + data.GetAddressByteSize()) + self.assertTrue(error.Success()) + + data.Append(data2) + + # this breaks on EBCDIC + offset = 0 + self.assert_data(data.GetUnsignedInt32, offset, 65) + offset += 4 + self.assert_data(data.GetUnsignedInt8, offset, 66) + offset += 1 + self.assert_data(data.GetUnsignedInt8, offset, 67) + offset += 1 + self.assert_data(data.GetUnsignedInt8, offset, 68) + offset += 1 + + # check the new API calls introduced per LLVM llvm.org/prenhancement request + # 11619 (Allow creating SBData values from arrays or primitives in + # Python) + + hello_str = "hello!" + data2 = lldb.SBData.CreateDataFromCString( + process.GetByteOrder(), process.GetAddressByteSize(), hello_str) + self.assertTrue(len(data2.uint8) == len(hello_str)) + self.assertTrue(data2.uint8[0] == 104, 'h == 104') + self.assertTrue(data2.uint8[1] == 101, 'e == 101') + self.assertTrue(data2.uint8[2] == 108, 'l == 108') + self.assert_data(data2.GetUnsignedInt8, 3, 108) # l + self.assertTrue(data2.uint8[4] == 111, 'o == 111') + self.assert_data(data2.GetUnsignedInt8, 5, 33) # ! + + uint_lists = [[1, 2, 3, 4, 5], [int(i) for i in [1, 2, 3, 4, 5]]] + int_lists = [[2, -2], [int(i) for i in [2, -2]]] + + for l in uint_lists: + data2 = lldb.SBData.CreateDataFromUInt64Array( + process.GetByteOrder(), process.GetAddressByteSize(), l) + self.assert_data(data2.GetUnsignedInt64, 0, 1) + self.assert_data(data2.GetUnsignedInt64, 8, 2) + self.assert_data(data2.GetUnsignedInt64, 16, 3) + self.assert_data(data2.GetUnsignedInt64, 24, 4) + self.assert_data(data2.GetUnsignedInt64, 32, 5) + + self.assertTrue( + data2.uint64s == [ + 1, + 2, + 3, + 4, + 5], + 'read_data_helper failure: data2 == [1,2,3,4,5]') + + for l in int_lists: + data2 = lldb.SBData.CreateDataFromSInt32Array( + process.GetByteOrder(), process.GetAddressByteSize(), l) + self.assertTrue( + data2.sint32[ + 0:2] == [ + 2, -2], 'signed32 data2 = [2,-2]') + + data2.Append( + lldb.SBData.CreateDataFromSInt64Array( + process.GetByteOrder(), + process.GetAddressByteSize(), + int_lists[0])) + self.assert_data(data2.GetSignedInt32, 0, 2) + self.assert_data(data2.GetSignedInt32, 4, -2) + self.assertTrue( + data2.sint64[ + 1:3] == [ + 2, -2], 'signed64 data2 = [2,-2]') + + for l in int_lists: + data2 = lldb.SBData.CreateDataFromSInt64Array( + process.GetByteOrder(), process.GetAddressByteSize(), l) + self.assert_data(data2.GetSignedInt64, 0, 2) + self.assert_data(data2.GetSignedInt64, 8, -2) + self.assertTrue( + data2.sint64[ + 0:2] == [ + 2, -2], 'signed64 data2 = [2,-2]') + + for l in uint_lists: + data2 = lldb.SBData.CreateDataFromUInt32Array( + process.GetByteOrder(), process.GetAddressByteSize(), l) + self.assert_data(data2.GetUnsignedInt32, 0, 1) + self.assert_data(data2.GetUnsignedInt32, 4, 2) + self.assert_data(data2.GetUnsignedInt32, 8, 3) + self.assert_data(data2.GetUnsignedInt32, 12, 4) + self.assert_data(data2.GetUnsignedInt32, 16, 5) + + bool_list = [True, True, False, False, True, False] + + data2 = lldb.SBData.CreateDataFromSInt32Array( + process.GetByteOrder(), process.GetAddressByteSize(), bool_list) + self.assertTrue( + data2.sint32[ + 0:6] == [ + 1, + 1, + 0, + 0, + 1, + 0], + 'signed32 data2 = [1, 1, 0, 0, 1, 0]') + + data2 = lldb.SBData.CreateDataFromUInt32Array( + process.GetByteOrder(), process.GetAddressByteSize(), bool_list) + self.assertTrue( + data2.uint32[ + 0:6] == [ + 1, + 1, + 0, + 0, + 1, + 0], + 'unsigned32 data2 = [1, 1, 0, 0, 1, 0]') + + data2 = lldb.SBData.CreateDataFromSInt64Array( + process.GetByteOrder(), process.GetAddressByteSize(), bool_list) + self.assertTrue( + data2.sint64[ + 0:6] == [ + 1, + 1, + 0, + 0, + 1, + 0], + 'signed64 data2 = [1, 1, 0, 0, 1, 0]') + + data2 = lldb.SBData.CreateDataFromUInt64Array( + process.GetByteOrder(), process.GetAddressByteSize(), bool_list) + self.assertTrue( + data2.uint64[ + 0:6] == [ + 1, + 1, + 0, + 0, + 1, + 0], + 'signed64 data2 = [1, 1, 0, 0, 1, 0]') + + data2 = lldb.SBData.CreateDataFromDoubleArray( + process.GetByteOrder(), process.GetAddressByteSize(), [ + 3.14, 6.28, 2.71]) + self.assertTrue( + fabs( + data2.GetDouble( + error, + 0) - + 3.14) < 0.5, + 'double data2[0] = 3.14') + self.assertTrue(error.Success()) + self.assertTrue( + fabs( + data2.GetDouble( + error, + 8) - + 6.28) < 0.5, + 'double data2[1] = 6.28') + self.assertTrue(error.Success()) + self.assertTrue( + fabs( + data2.GetDouble( + error, + 16) - + 2.71) < 0.5, + 'double data2[2] = 2.71') + self.assertTrue(error.Success()) + + data2 = lldb.SBData() + + data2.SetDataFromCString(hello_str) + self.assertTrue(len(data2.uint8) == len(hello_str)) + self.assert_data(data2.GetUnsignedInt8, 0, 104) + self.assert_data(data2.GetUnsignedInt8, 1, 101) + self.assert_data(data2.GetUnsignedInt8, 2, 108) + self.assert_data(data2.GetUnsignedInt8, 3, 108) + self.assert_data(data2.GetUnsignedInt8, 4, 111) + self.assert_data(data2.GetUnsignedInt8, 5, 33) + + data2.SetDataFromUInt64Array([1, 2, 3, 4, 5]) + self.assert_data(data2.GetUnsignedInt64, 0, 1) + self.assert_data(data2.GetUnsignedInt64, 8, 2) + self.assert_data(data2.GetUnsignedInt64, 16, 3) + self.assert_data(data2.GetUnsignedInt64, 24, 4) + self.assert_data(data2.GetUnsignedInt64, 32, 5) + + self.assertTrue( + data2.uint64[0] == 1, + 'read_data_helper failure: set data2[0] = 1') + self.assertTrue( + data2.uint64[1] == 2, + 'read_data_helper failure: set data2[1] = 2') + self.assertTrue( + data2.uint64[2] == 3, + 'read_data_helper failure: set data2[2] = 3') + self.assertTrue( + data2.uint64[3] == 4, + 'read_data_helper failure: set data2[3] = 4') + self.assertTrue( + data2.uint64[4] == 5, + 'read_data_helper failure: set data2[4] = 5') + + self.assertTrue( + data2.uint64[ + 0:2] == [ + 1, + 2], + 'read_data_helper failure: set data2[0:2] = [1,2]') + + data2.SetDataFromSInt32Array([2, -2]) + self.assert_data(data2.GetSignedInt32, 0, 2) + self.assert_data(data2.GetSignedInt32, 4, -2) + + data2.SetDataFromSInt64Array([2, -2]) + self.assert_data(data2.GetSignedInt64, 0, 2) + self.assert_data(data2.GetSignedInt64, 8, -2) + + data2.SetDataFromUInt32Array([1, 2, 3, 4, 5]) + self.assert_data(data2.GetUnsignedInt32, 0, 1) + self.assert_data(data2.GetUnsignedInt32, 4, 2) + self.assert_data(data2.GetUnsignedInt32, 8, 3) + self.assert_data(data2.GetUnsignedInt32, 12, 4) + self.assert_data(data2.GetUnsignedInt32, 16, 5) + + self.assertTrue( + data2.uint32[0] == 1, + 'read_data_helper failure: set 32-bit data2[0] = 1') + self.assertTrue( + data2.uint32[1] == 2, + 'read_data_helper failure: set 32-bit data2[1] = 2') + self.assertTrue( + data2.uint32[2] == 3, + 'read_data_helper failure: set 32-bit data2[2] = 3') + self.assertTrue( + data2.uint32[3] == 4, + 'read_data_helper failure: set 32-bit data2[3] = 4') + self.assertTrue( + data2.uint32[4] == 5, + 'read_data_helper failure: set 32-bit data2[4] = 5') + + data2.SetDataFromDoubleArray([3.14, 6.28, 2.71]) + self.assertTrue(fabs(data2.GetDouble(error, 0) - 3.14) + < 0.5, 'set double data2[0] = 3.14') + self.assertTrue(fabs(data2.GetDouble(error, 8) - 6.28) + < 0.5, 'set double data2[1] = 6.28') + self.assertTrue(fabs(data2.GetDouble(error, 16) - 2.71) + < 0.5, 'set double data2[2] = 2.71') + + self.assertTrue( + fabs( + data2.double[0] - + 3.14) < 0.5, + 'read_data_helper failure: set double data2[0] = 3.14') + self.assertTrue( + fabs( + data2.double[1] - + 6.28) < 0.5, + 'read_data_helper failure: set double data2[1] = 6.28') + self.assertTrue( + fabs( + data2.double[2] - + 2.71) < 0.5, + 'read_data_helper failure: set double data2[2] = 2.71') + + def assert_data(self, func, arg, expected): + """ Asserts func(SBError error, arg) == expected. """ + error = lldb.SBError() + result = func(error, arg) + if not error.Success(): + stream = lldb.SBStream() + error.GetDescription(stream) + self.assertTrue( + error.Success(), "%s(error, %s) did not succeed: %s" % + (func.__name__, arg, stream.GetData())) + self.assertTrue( + expected == result, "%s(error, %s) == %s != %s" % + (func.__name__, arg, result, expected)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbdata/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbdata/main.cpp new file mode 100644 index 00000000000..78e071c931e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbdata/main.cpp @@ -0,0 +1,42 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdint.h> + +struct foo +{ + uint32_t a; + uint32_t b; + float c; + foo() : a(0), b(1), c(3.14) {} + foo(uint32_t A, uint32_t B, float C) : + a(A), + b(B), + c(C) + {} +}; + +int main (int argc, char const *argv[]) +{ + foo* foobar = new foo[2]; + + foobar[0].a = 1; + foobar[0].b = 9; + + foobar[1].a = 8; + foobar[1].b = 5; + + foobar[1].b = 7; // set breakpoint here + + foobar[1].c = 6.28; + + foo barfoo[] = {foo(1,2,3), foo(4,5,6)}; + + delete[] foobar; + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sblaunchinfo/TestSBLaunchInfo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sblaunchinfo/TestSBLaunchInfo.py new file mode 100644 index 00000000000..44a6362ce92 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sblaunchinfo/TestSBLaunchInfo.py @@ -0,0 +1,30 @@ +""" +Test SBLaunchInfo +""" + + + +from lldbsuite.test.lldbtest import * + + +def lookup(info, key): + for i in range(info.GetNumEnvironmentEntries()): + KeyEqValue = info.GetEnvironmentEntryAtIndex(i) + Key, Value = KeyEqValue.split("=") + if Key == key: + return Value + return "" + +class TestSBLaunchInfo(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test_environment_getset(self): + info = lldb.SBLaunchInfo(None) + info.SetEnvironmentEntries(["FOO=BAR"], False) + self.assertEquals(1, info.GetNumEnvironmentEntries()) + info.SetEnvironmentEntries(["BAR=BAZ"], True) + self.assertEquals(2, info.GetNumEnvironmentEntries()) + self.assertEquals("BAR", lookup(info, "FOO")) + self.assertEquals("BAZ", lookup(info, "BAR")) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbstructureddata/TestStructuredDataAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbstructureddata/TestStructuredDataAPI.py new file mode 100644 index 00000000000..f5efdfa8b37 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbstructureddata/TestStructuredDataAPI.py @@ -0,0 +1,199 @@ +""" +Test some SBStructuredData API. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestStructuredDataAPI(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def test(self): + self.structured_data_api_test() + + @add_test_categories(['pyapi']) + def structured_data_api_test(self): + error = lldb.SBError() + s = lldb.SBStream() + s.Print( + "{\"key_dict\":{\"key_string\":\"STRING\",\"key_int\":3,\"key_float\":2.99,\"key_bool\":true,\"key_array\":[\"23\",\"arr\"]}}") + example = lldb.SBStructuredData() + + # Check SetFromJSON API for dictionaries, integers, floating point + # values, strings and arrays + error = example.SetFromJSON(s) + if not error.Success(): + self.fail("FAILED: " + error.GetCString()) + + # Tests for invalid data type + self.invalid_struct_test(example) + + dict_struct = lldb.SBStructuredData() + dict_struct = example.GetValueForKey("key_dict") + + # Tests for dictionary data type + self.dictionary_struct_test(example) + + # Tests for string data type + self.string_struct_test(dict_struct) + + # Tests for integer data type + self.int_struct_test(dict_struct) + + # Tests for floating point data type + self.double_struct_test(dict_struct) + + # Tests for boolean data type + self.bool_struct_test(dict_struct) + + # Tests for array data type + self.array_struct_test(dict_struct) + + def invalid_struct_test(self, example): + invalid_struct = lldb.SBStructuredData() + invalid_struct = example.GetValueForKey("invalid_key") + if invalid_struct.IsValid(): + self.fail("An invalid object should have been returned") + + # Check Type API + if not invalid_struct.GetType() == lldb.eStructuredDataTypeInvalid: + self.fail("Wrong type returned: " + str(invalid_struct.GetType())) + + def dictionary_struct_test(self, example): + # Check API returning a valid SBStructuredData of 'dictionary' type + dict_struct = lldb.SBStructuredData() + dict_struct = example.GetValueForKey("key_dict") + if not dict_struct.IsValid(): + self.fail("A valid object should have been returned") + + # Check Type API + if not dict_struct.GetType() == lldb.eStructuredDataTypeDictionary: + self.fail("Wrong type returned: " + str(dict_struct.GetType())) + + # Check Size API for 'dictionary' type + if not dict_struct.GetSize() == 5: + self.fail("Wrong no of elements returned: " + + str(dict_struct.GetSize())) + + def string_struct_test(self, dict_struct): + string_struct = lldb.SBStructuredData() + string_struct = dict_struct.GetValueForKey("key_string") + if not string_struct.IsValid(): + self.fail("A valid object should have been returned") + + # Check Type API + if not string_struct.GetType() == lldb.eStructuredDataTypeString: + self.fail("Wrong type returned: " + str(string_struct.GetType())) + + # Check API returning 'string' value + output = string_struct.GetStringValue(25) + if not "STRING" in output: + self.fail("wrong output: " + output) + + # Calling wrong API on a SBStructuredData + # (e.g. getting an integer from a string type structure) + output = string_struct.GetIntegerValue() + if output: + self.fail( + "Valid integer value " + + str(output) + + " returned for a string object") + + def int_struct_test(self, dict_struct): + # Check a valid SBStructuredData containing an 'integer' by + int_struct = lldb.SBStructuredData() + int_struct = dict_struct.GetValueForKey("key_int") + if not int_struct.IsValid(): + self.fail("A valid object should have been returned") + + # Check Type API + if not int_struct.GetType() == lldb.eStructuredDataTypeInteger: + self.fail("Wrong type returned: " + str(int_struct.GetType())) + + # Check API returning 'integer' value + output = int_struct.GetIntegerValue() + if not output == 3: + self.fail("wrong output: " + str(output)) + + # Calling wrong API on a SBStructuredData + # (e.g. getting a string value from an integer type structure) + output = int_struct.GetStringValue(25) + if output: + self.fail( + "Valid string " + + output + + " returned for an integer object") + + def double_struct_test(self, dict_struct): + floating_point_struct = lldb.SBStructuredData() + floating_point_struct = dict_struct.GetValueForKey("key_float") + if not floating_point_struct.IsValid(): + self.fail("A valid object should have been returned") + + # Check Type API + if not floating_point_struct.GetType() == lldb.eStructuredDataTypeFloat: + self.fail("Wrong type returned: " + + str(floating_point_struct.GetType())) + + # Check API returning 'double' value + output = floating_point_struct.GetFloatValue() + if not output == 2.99: + self.fail("wrong output: " + str(output)) + + def bool_struct_test(self, dict_struct): + bool_struct = lldb.SBStructuredData() + bool_struct = dict_struct.GetValueForKey("key_bool") + if not bool_struct.IsValid(): + self.fail("A valid object should have been returned") + + # Check Type API + if not bool_struct.GetType() == lldb.eStructuredDataTypeBoolean: + self.fail("Wrong type returned: " + str(bool_struct.GetType())) + + # Check API returning 'bool' value + output = bool_struct.GetBooleanValue() + if not output: + self.fail("wrong output: " + str(output)) + + def array_struct_test(self, dict_struct): + # Check API returning a valid SBStructuredData of 'array' type + array_struct = lldb.SBStructuredData() + array_struct = dict_struct.GetValueForKey("key_array") + if not array_struct.IsValid(): + self.fail("A valid object should have been returned") + + # Check Type API + if not array_struct.GetType() == lldb.eStructuredDataTypeArray: + self.fail("Wrong type returned: " + str(array_struct.GetType())) + + # Check Size API for 'array' type + if not array_struct.GetSize() == 2: + self.fail("Wrong no of elements returned: " + + str(array_struct.GetSize())) + + # Check API returning a valid SBStructuredData for different 'array' + # indices + string_struct = array_struct.GetItemAtIndex(0) + if not string_struct.IsValid(): + self.fail("A valid object should have been returned") + if not string_struct.GetType() == lldb.eStructuredDataTypeString: + self.fail("Wrong type returned: " + str(string_struct.GetType())) + output = string_struct.GetStringValue(5) + if not output == "23": + self.fail("wrong output: " + str(output)) + + string_struct = array_struct.GetItemAtIndex(1) + if not string_struct.IsValid(): + self.fail("A valid object should have been returned") + if not string_struct.GetType() == lldb.eStructuredDataTypeString: + self.fail("Wrong type returned: " + str(string_struct.GetType())) + output = string_struct.GetStringValue(5) + if not output == "arr": + self.fail("wrong output: " + str(output)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py new file mode 100644 index 00000000000..a06dd7a1424 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py @@ -0,0 +1,10 @@ +from lldbsuite.test import decorators +from lldbsuite.test import lldbinline + +lldbinline.MakeInlineTest( + __file__, globals(), [ + decorators.skipIfFreeBSD, decorators.skipIfLinux, + decorators.skipIfWindows, decorators.skipIfNetBSD, + decorators.expectedFailureAll( + oslist=['macosx'], archs=['i386'], + bugnumber='rdar://28656677')]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/main.m b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/main.m new file mode 100644 index 00000000000..8e9601e42eb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/main.m @@ -0,0 +1,33 @@ +//===-- main.m --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#import <Foundation/Foundation.h> + +@interface ThisClassTestsThings : NSObject +@end + +@implementation ThisClassTestsThings +- (int)doSomething { + + id s = self; + NSLog(@"%@",s); //% s = self.frame().FindVariable("s"); s.SetPreferDynamicValue(lldb.eDynamicCanRunTarget) + //% s_type = s.GetType() + //% typeClass = s_type.GetTypeClass() + //% condition = (typeClass == lldb.eTypeClassClass) or (typeClass ==lldb.eTypeClassObjCObject) or (typeClass == lldb.eTypeClassObjCInterface) or (typeClass == lldb.eTypeClassObjCObjectPointer) or (typeClass == lldb.eTypeClassPointer) + //% self.assertTrue(condition, "s has the wrong TypeClass") + return 0; +} +- (id)init { + return (self = [super init]); +} +@end + + +int main (int argc, char const *argv[]) +{ + return [[[ThisClassTestsThings alloc] init] doSomething]; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/TestSBValueConstAddrOf.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/TestSBValueConstAddrOf.py new file mode 100644 index 00000000000..a3d43c1bdee --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/TestSBValueConstAddrOf.py @@ -0,0 +1,3 @@ +import lldbsuite.test.lldbinline as lldbinline + +lldbinline.MakeInlineTest(__file__, globals()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/main.cpp new file mode 100644 index 00000000000..318a45bc21a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/main.cpp @@ -0,0 +1,40 @@ +#include <stdio.h> +#include <stdint.h> + +struct RegisterContext +{ + uintptr_t r0; + uintptr_t r1; + uintptr_t r2; + uintptr_t r3; + uintptr_t r4; + uintptr_t pc; + uintptr_t fp; + uintptr_t sp; +}; + +struct ThreadInfo { + uint32_t tid; + const char *name; + RegisterContext regs; + ThreadInfo *next; +}; +int main (int argc, char const *argv[], char const *envp[]); + +ThreadInfo g_thread2 = { 0x2222, "thread2", { 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, (uintptr_t)&main, 0x2006, 0x2007 }, NULL }; +ThreadInfo g_thread1 = { 0x1111, "thread1", { 0x1000, 0x1001, 0x1002, 0x1003, 0x1004, (uintptr_t)&main, 0x1006, 0x1007 }, &g_thread2 }; +ThreadInfo *g_thread_list_ptr = &g_thread1; + +int main (int argc, char const *argv[], char const *envp[]) +{ + printf ("g_thread_list is %p\n", g_thread_list_ptr); + return 0; //% v = self.dbg.GetSelectedTarget().FindFirstGlobalVariable('g_thread_list_ptr') + //% v_gla = v.GetChildMemberWithName('regs').GetLoadAddress() + //% v_aof = v.GetChildMemberWithName('regs').AddressOf().GetValueAsUnsigned(lldb.LLDB_INVALID_ADDRESS) + //% expr = '(%s)0x%x' % (v.GetType().GetName(), v.GetValueAsUnsigned(0)) + //% e = v.CreateValueFromExpression('e', expr) + //% e_gla = e.GetChildMemberWithName('regs').GetLoadAddress() + //% e_aof = e.GetChildMemberWithName('regs').AddressOf().GetValueAsUnsigned(lldb.LLDB_INVALID_ADDRESS) + //% self.assertTrue(v_gla == e_gla, "GetLoadAddress() differs") + //% self.assertTrue(v_aof == e_aof, "AddressOf() differs") +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/Makefile new file mode 100644 index 00000000000..b5256564c2f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/Makefile @@ -0,0 +1,6 @@ +CXX_SOURCES := main.cpp + +# Clean renamed executable on 'make clean' +clean: OBJECTS+=no_synth + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py new file mode 100644 index 00000000000..1662f69312d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py @@ -0,0 +1,82 @@ +"""Test SBValue::Persist""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SBValuePersistTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24772") + def test(self): + """Test SBValue::Persist""" + self.build() + self.setTearDownCleanup() + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_source_regexp(self, "break here") + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + # This is the function to remove the custom formats in order to have a + # clean slate for the next test case. + def cleanup(): + self.runCmd('type format clear', check=False) + self.runCmd('type summary clear', check=False) + self.runCmd('type filter clear', check=False) + self.runCmd('type synthetic clear', check=False) + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + foo = self.frame().FindVariable("foo") + bar = self.frame().FindVariable("bar") + baz = self.frame().FindVariable("baz") + + self.assertTrue(foo.IsValid(), "foo is not valid") + self.assertTrue(bar.IsValid(), "bar is not valid") + self.assertTrue(baz.IsValid(), "baz is not valid") + + fooPersist = foo.Persist() + barPersist = bar.Persist() + bazPersist = baz.Persist() + + self.assertTrue(fooPersist.IsValid(), "fooPersist is not valid") + self.assertTrue(barPersist.IsValid(), "barPersist is not valid") + self.assertTrue(bazPersist.IsValid(), "bazPersist is not valid") + + self.assertTrue( + fooPersist.GetValueAsUnsigned(0) == 10, + "fooPersist != 10") + self.assertTrue( + barPersist.GetPointeeData().sint32[0] == 4, + "barPersist != 4") + self.assertTrue(bazPersist.GetSummary() == '"85"', "bazPersist != 85") + + self.runCmd("continue") + + self.assertTrue(fooPersist.IsValid(), "fooPersist is not valid") + self.assertTrue(barPersist.IsValid(), "barPersist is not valid") + self.assertTrue(bazPersist.IsValid(), "bazPersist is not valid") + + self.assertTrue( + fooPersist.GetValueAsUnsigned(0) == 10, + "fooPersist != 10") + self.assertTrue( + barPersist.GetPointeeData().sint32[0] == 4, + "barPersist != 4") + self.assertTrue(bazPersist.GetSummary() == '"85"', "bazPersist != 85") + + self.expect("expr *(%s)" % (barPersist.GetName()), substrs=['= 4']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/main.cpp new file mode 100644 index 00000000000..c54339f3bba --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/sbvalue_persist/main.cpp @@ -0,0 +1,14 @@ +#include <vector> +#include <string> + +void f() {} + +int main() { + int foo = 10; + int *bar = new int(4); + std::string baz = "85"; + + f(); // break here + f(); // break here + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/section/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/section/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/section/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py new file mode 100644 index 00000000000..1513b98b772 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py @@ -0,0 +1,42 @@ +""" +Test SBSection APIs. +""" + + + +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SectionAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + def test_get_target_byte_size(self): + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + exe = self.getBuildArtifact('b.out') + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # find the .data section of the main module + mod = target.GetModuleAtIndex(0) + data_section = None + for s in mod.sections: + sect_type = s.GetSectionType() + if sect_type == lldb.eSectionTypeData: + data_section = s + break + elif sect_type == lldb.eSectionTypeContainer: + for i in range(s.GetNumSubSections()): + ss = s.GetSubSectionAtIndex(i) + sect_type = ss.GetSectionType() + if sect_type == lldb.eSectionTypeData: + data_section = ss + break + + self.assertIsNotNone(data_section) + self.assertEqual(data_section.target_byte_size, 1) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/section/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/section/main.c new file mode 100644 index 00000000000..f12ef5afb7a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/section/main.c @@ -0,0 +1,27 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <string.h> + +// This simple program is to test the lldb Python API SBSection. It includes +// somes global data, and so the build process produces a DATA section, which +// the test code can use to query for the target byte size + +char my_global_var_of_char_type = 'X'; + +int main (int argc, char const *argv[]) +{ + // this code just "does something" with the global so that it is not + // optimised away + if (argc > 1 && strlen(argv[1])) + { + my_global_var_of_char_type += argv[1][0]; + } + + return my_global_var_of_char_type; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/signals/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/signals/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/signals/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py new file mode 100644 index 00000000000..602fee457c2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py @@ -0,0 +1,56 @@ +""" +Test SBProcess APIs, including ReadMemory(), WriteMemory(), and others. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +from lldbsuite.test.lldbutil import get_stopped_thread, state_type_to_str + + +class SignalsAPITestCase(TestBase): + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + @add_test_categories(['pyapi']) + @skipIfWindows # Windows doesn't have signals + def test_ignore_signal(self): + """Test Python SBUnixSignals.Suppress/Stop/Notify() API.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + line = line_number( + "main.cpp", + "// Set break point at this line and setup signal ignores.") + breakpoint = target.BreakpointCreateByLocation("main.cpp", line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + + unix_signals = process.GetUnixSignals() + sigint = unix_signals.GetSignalNumberFromName("SIGINT") + unix_signals.SetShouldSuppress(sigint, True) + unix_signals.SetShouldStop(sigint, False) + unix_signals.SetShouldNotify(sigint, False) + + process.Continue() + self.assertTrue( + process.state == lldb.eStateExited, + "The process should have exited") + self.assertTrue( + process.GetExitStatus() == 0, + "The process should have returned 0") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/signals/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/signals/main.cpp new file mode 100644 index 00000000000..c4c5a00dd09 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/signals/main.cpp @@ -0,0 +1,27 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <sys/types.h> +#if defined(_WIN32) +#include <windows.h> +#else +#include <unistd.h> +#include <signal.h> +#endif + +// This simple program is to test the lldb Python API related to process. + +int main (int argc, char const *argv[]) +{ +#if defined(_WIN32) + ::ExitProcess(1); +#else + kill(getpid(), SIGINT); // Set break point at this line and setup signal ignores. +#endif + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py new file mode 100644 index 00000000000..0c1ad83c84d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py @@ -0,0 +1,107 @@ +""" +Test SBSymbolContext APIs. +""" + +from __future__ import print_function + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SymbolContextAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + 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.') + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test(self): + """Exercise SBSymbolContext API extensively.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c by name 'c'. + breakpoint = target.BreakpointCreateByName('c', 'a.out') + #print("breakpoint:", breakpoint) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.line. + from lldbsuite.test.lldbutil import get_stopped_thread + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + frame0 = thread.GetFrameAtIndex(0) + self.assertTrue(frame0.GetLineEntry().GetLine() == self.line) + + # Now get the SBSymbolContext from this frame. We want everything. :-) + context = frame0.GetSymbolContext(lldb.eSymbolContextEverything) + self.assertTrue(context) + + # Get the description of this module. + module = context.GetModule() + desc = lldbutil.get_description(module) + self.expect(desc, "The module should match", exe=False, + substrs=[self.getBuildArtifact("a.out")]) + + compileUnit = context.GetCompileUnit() + self.expect( + str(compileUnit), + "The compile unit should match", + exe=False, + substrs=[self.getSourcePath('main.c')]) + + function = context.GetFunction() + self.assertTrue(function) + #print("function:", function) + + block = context.GetBlock() + self.assertTrue(block) + #print("block:", block) + + lineEntry = context.GetLineEntry() + #print("line entry:", lineEntry) + self.expect( + lineEntry.GetFileSpec().GetDirectory(), + "The line entry should have the correct directory", + exe=False, + substrs=[self.mydir]) + self.expect( + lineEntry.GetFileSpec().GetFilename(), + "The line entry should have the correct filename", + exe=False, + substrs=['main.c']) + self.assertTrue(lineEntry.GetLine() == self.line, + "The line entry's line number should match ") + + symbol = context.GetSymbol() + self.assertTrue( + function.GetName() == symbol.GetName() and symbol.GetName() == 'c', + "The symbol name should be 'c'") + + sc_list = lldb.SBSymbolContextList() + sc_list.Append(context) + self.assertEqual(len(sc_list), 1) + for sc in sc_list: + self.assertEqual(lineEntry, sc.GetLineEntry()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/main.c new file mode 100644 index 00000000000..4e68fb764b8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/main.c @@ -0,0 +1,50 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to test the lldb Python API SBSymbolContext. +// When stopped on a frame, we can get the symbol context using the SBFrame API +// SBFrame.GetSymbolContext(). + +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; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/Makefile new file mode 100644 index 00000000000..ccaa0edcf5f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := file1.cpp file2.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/TestSymbolContextTwoFiles.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/TestSymbolContextTwoFiles.py new file mode 100644 index 00000000000..27d1b60a507 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/TestSymbolContextTwoFiles.py @@ -0,0 +1,79 @@ +""" +Test SBSymbolContext APIs. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SymbolContextTwoFilesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"]) + def test_lookup_by_address(self): + """Test lookup by address in a module with multiple compilation units""" + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + module = target.GetModuleAtIndex(0) + self.assertTrue(module.IsValid()) + for symbol_name in ["struct1::f()", "struct2::f()"]: + sc_list = module.FindFunctions(symbol_name, lldb.eSymbolTypeCode) + self.assertTrue(1, sc_list.GetSize()) + symbol_address = sc_list.GetContextAtIndex( + 0).GetSymbol().GetStartAddress() + self.assertTrue(symbol_address.IsValid()) + sc_by_address = module.ResolveSymbolContextForAddress( + symbol_address, lldb.eSymbolContextFunction) + self.assertEqual(symbol_name, + sc_by_address.GetFunction().GetName()) + + @add_test_categories(['pyapi']) + def test_ranges_in_multiple_compile_unit(self): + """This test verifies that we correctly handle the case when multiple + compile unit contains DW_AT_ranges and DW_AT_ranges_base attributes.""" + self.build() + exe = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + source1 = "file1.cpp" + line1 = line_number(source1, '// Break1') + breakpoint1 = target.BreakpointCreateByLocation(source1, line1) + self.assertIsNotNone(breakpoint1) + self.assertTrue(breakpoint1.IsValid()) + + source2 = "file2.cpp" + line2 = line_number(source2, '// Break2') + breakpoint2 = target.BreakpointCreateByLocation(source2, line2) + self.assertIsNotNone(breakpoint2) + self.assertTrue(breakpoint2.IsValid()) + + process = target.LaunchSimple(None, None, self.get_process_working_directory()) + self.assertIsNotNone(process, PROCESS_IS_VALID) + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint2) + self.assertEqual(len(threads), 1) + frame = threads[0].GetFrameAtIndex(0) + value = frame.FindVariable("x") + self.assertTrue(value.IsValid()) + + process.Continue() + + threads = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint1) + self.assertEqual(len(threads), 1) + frame = threads[0].GetFrameAtIndex(0) + value = frame.FindVariable("x") + self.assertTrue(value.IsValid()) + + process.Continue() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/decls.h b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/decls.h new file mode 100644 index 00000000000..7c804584206 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/decls.h @@ -0,0 +1,11 @@ +struct struct1 { + ~struct1(); + static void f(); +}; + +struct struct2 { + ~struct2(); + static void f(); +}; + +int g(); diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/file1.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/file1.cpp new file mode 100644 index 00000000000..327d0fb7718 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/file1.cpp @@ -0,0 +1,21 @@ +#include "decls.h" + +int g() { + return 1; +} + +struct1::~struct1() { + int x = g(); // Break1 +} + +void struct1::f() {} + +int main() { + struct1::f(); + struct2::f(); + + struct1 s1; + struct2 s2; + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/file2.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/file2.cpp new file mode 100644 index 00000000000..109e01572ed --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/symbol-context/two-files/file2.cpp @@ -0,0 +1,7 @@ +#include "decls.h" + +struct2::~struct2() { + int x = g(); // Break2 +} + +void struct2::f() {} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/target/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/target/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/target/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py new file mode 100644 index 00000000000..6e5be6e8f17 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py @@ -0,0 +1,426 @@ +""" +Test SBTarget APIs. +""" + +from __future__ import print_function + + +import unittest2 +import os +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TargetAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to of function 'c'. + self.line1 = line_number( + 'main.c', '// Find the line number for breakpoint 1 here.') + self.line2 = line_number( + 'main.c', '// Find the line number for breakpoint 2 here.') + self.line_main = line_number( + "main.c", "// Set a break at entry to main.") + + # rdar://problem/9700873 + # Find global variable value fails for dwarf if inferior not started + # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94) + # + # It does not segfaults now. But for dwarf, the variable value is None if + # the inferior process does not exist yet. The radar has been updated. + #@unittest232.skip("segmentation fault -- skipping") + @add_test_categories(['pyapi']) + def test_find_global_variables(self): + """Exercise SBTarget.FindGlobalVariables() API.""" + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.find_global_variables('b.out') + + @add_test_categories(['pyapi']) + def test_find_compile_units(self): + """Exercise SBTarget.FindCompileUnits() API.""" + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.find_compile_units(self.getBuildArtifact('b.out')) + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778") + def test_find_functions(self): + """Exercise SBTarget.FindFunctions() API.""" + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.find_functions('b.out') + + @add_test_categories(['pyapi']) + def test_get_description(self): + """Exercise SBTarget.GetDescription() API.""" + self.build() + self.get_description() + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=["windows"], bugnumber='llvm.org/pr21765') + def test_resolve_symbol_context_with_address(self): + """Exercise SBTarget.ResolveSymbolContextForAddress() API.""" + self.build() + self.resolve_symbol_context_with_address() + + @add_test_categories(['pyapi']) + def test_get_platform(self): + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + target = self.create_simple_target('b.out') + platform = target.platform + self.assertTrue(platform, VALID_PLATFORM) + + @add_test_categories(['pyapi']) + def test_get_data_byte_size(self): + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + target = self.create_simple_target('b.out') + self.assertEqual(target.data_byte_size, 1) + + @add_test_categories(['pyapi']) + def test_get_code_byte_size(self): + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + target = self.create_simple_target('b.out') + self.assertEqual(target.code_byte_size, 1) + + @add_test_categories(['pyapi']) + def test_resolve_file_address(self): + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + target = self.create_simple_target('b.out') + + # find the file address in the .data section of the main + # module + data_section = self.find_data_section(target) + data_section_addr = data_section.file_addr + + # resolve the above address, and compare the address produced + # by the resolution against the original address/section + res_file_addr = target.ResolveFileAddress(data_section_addr) + self.assertTrue(res_file_addr.IsValid()) + + self.assertEqual(data_section_addr, res_file_addr.file_addr) + + data_section2 = res_file_addr.section + self.assertIsNotNone(data_section2) + self.assertEqual(data_section.name, data_section2.name) + + @add_test_categories(['pyapi']) + def test_read_memory(self): + d = {'EXE': 'b.out'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + target = self.create_simple_target('b.out') + + breakpoint = target.BreakpointCreateByLocation( + "main.c", self.line_main) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Put debugger into synchronous mode so when we target.LaunchSimple returns + # it will guaranteed to be at the breakpoint + self.dbg.SetAsync(False) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # find the file address in the .data section of the main + # module + data_section = self.find_data_section(target) + sb_addr = lldb.SBAddress(data_section, 0) + error = lldb.SBError() + content = target.ReadMemory(sb_addr, 1, error) + self.assertTrue(error.Success(), "Make sure memory read succeeded") + self.assertEqual(len(content), 1) + + def create_simple_target(self, fn): + exe = self.getBuildArtifact(fn) + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + return target + + def find_data_section(self, target): + mod = target.GetModuleAtIndex(0) + data_section = None + for s in mod.sections: + sect_type = s.GetSectionType() + if sect_type == lldb.eSectionTypeData: + data_section = s + break + elif sect_type == lldb.eSectionTypeContainer: + for i in range(s.GetNumSubSections()): + ss = s.GetSubSectionAtIndex(i) + sect_type = ss.GetSectionType() + if sect_type == lldb.eSectionTypeData: + data_section = ss + break + + self.assertIsNotNone(data_section) + return data_section + + def find_global_variables(self, exe_name): + """Exercise SBTaget.FindGlobalVariables() API.""" + exe = self.getBuildArtifact(exe_name) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # rdar://problem/9700873 + # Find global variable value fails for dwarf if inferior not started + # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94) + # + # Remove the lines to create a breakpoint and to start the inferior + # which are workarounds for the dwarf case. + + breakpoint = target.BreakpointCreateByLocation('main.c', self.line1) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + # Make sure we hit our breakpoint: + thread_list = lldbutil.get_threads_stopped_at_breakpoint( + process, breakpoint) + self.assertTrue(len(thread_list) == 1) + + value_list = target.FindGlobalVariables( + 'my_global_var_of_char_type', 3) + self.assertTrue(value_list.GetSize() == 1) + my_global_var = value_list.GetValueAtIndex(0) + self.DebugSBValue(my_global_var) + self.assertTrue(my_global_var) + self.expect(my_global_var.GetName(), exe=False, + startstr="my_global_var_of_char_type") + self.expect(my_global_var.GetTypeName(), exe=False, + startstr="char") + self.expect(my_global_var.GetValue(), exe=False, + startstr="'X'") + + # While we are at it, let's also exercise the similar + # SBModule.FindGlobalVariables() API. + for m in target.module_iter(): + if os.path.normpath(m.GetFileSpec().GetDirectory()) == self.getBuildDir() and m.GetFileSpec().GetFilename() == exe_name: + value_list = m.FindGlobalVariables( + target, 'my_global_var_of_char_type', 3) + self.assertTrue(value_list.GetSize() == 1) + self.assertTrue( + value_list.GetValueAtIndex(0).GetValue() == "'X'") + break + + def find_compile_units(self, exe): + """Exercise SBTarget.FindCompileUnits() API.""" + source_name = "main.c" + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + list = target.FindCompileUnits(lldb.SBFileSpec(source_name, False)) + # Executable has been built just from one source file 'main.c', + # so we may check only the first element of list. + self.assertTrue( + list[0].GetCompileUnit().GetFileSpec().GetFilename() == source_name) + + def find_functions(self, exe_name): + """Exercise SBTaget.FindFunctions() API.""" + exe = self.getBuildArtifact(exe_name) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + list = target.FindFunctions('c', lldb.eFunctionNameTypeAuto) + self.assertTrue(list.GetSize() == 1) + + for sc in list: + self.assertTrue( + sc.GetModule().GetFileSpec().GetFilename() == exe_name) + self.assertTrue(sc.GetSymbol().GetName() == 'c') + + def get_description(self): + """Exercise SBTaget.GetDescription() API.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + from lldbsuite.test.lldbutil import get_description + + # get_description() allows no option to mean + # lldb.eDescriptionLevelBrief. + desc = get_description(target) + #desc = get_description(target, option=lldb.eDescriptionLevelBrief) + if not desc: + self.fail("SBTarget.GetDescription() failed") + self.expect(desc, exe=False, + substrs=['a.out']) + self.expect(desc, exe=False, matching=False, + substrs=['Target', 'Module', 'Breakpoint']) + + desc = get_description(target, option=lldb.eDescriptionLevelFull) + if not desc: + self.fail("SBTarget.GetDescription() failed") + self.expect(desc, exe=False, + substrs=['a.out', 'Target', 'Module', 'Breakpoint']) + + @not_remote_testsuite_ready + @add_test_categories(['pyapi']) + @no_debug_info_test + def test_launch_new_process_and_redirect_stdout(self): + """Exercise SBTaget.Launch() API with redirected stdout.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Add an extra twist of stopping the inferior in a breakpoint, and then continue till it's done. + # We should still see the entire stdout redirected once the process is + # finished. + line = line_number('main.c', '// a(3) -> c(3)') + breakpoint = target.BreakpointCreateByLocation('main.c', line) + + # Now launch the process, do not stop at entry point, and redirect stdout to "stdout.txt" file. + # The inferior should run to completion after "process.Continue()" + # call. + local_path = self.getBuildArtifact("stdout.txt") + if os.path.exists(local_path): + os.remove(local_path) + + if lldb.remote_platform: + stdout_path = lldbutil.append_to_process_working_directory(self, + "lldb-stdout-redirect.txt") + else: + stdout_path = local_path + error = lldb.SBError() + process = target.Launch( + self.dbg.GetListener(), + None, + None, + None, + stdout_path, + None, + None, + 0, + False, + error) + process.Continue() + #self.runCmd("process status") + if lldb.remote_platform: + # copy output file to host + lldb.remote_platform.Get( + lldb.SBFileSpec(stdout_path), + lldb.SBFileSpec(local_path)) + + # The 'stdout.txt' file should now exist. + self.assertTrue( + os.path.isfile(local_path), + "'stdout.txt' exists due to redirected stdout via SBTarget.Launch() API.") + + # Read the output file produced by running the program. + with open(local_path, 'r') as f: + output = f.read() + + self.expect(output, exe=False, + substrs=["a(1)", "b(2)", "a(3)"]) + + def resolve_symbol_context_with_address(self): + """Exercise SBTaget.ResolveSymbolContextForAddress() API.""" + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create the two breakpoints inside function 'a'. + breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1) + breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2) + #print("breakpoint1:", breakpoint1) + #print("breakpoint2:", breakpoint2) + self.assertTrue(breakpoint1 and + breakpoint1.GetNumLocations() == 1, + VALID_BREAKPOINT) + self.assertTrue(breakpoint2 and + breakpoint2.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.line1. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + #self.runCmd("process status") + frame0 = thread.GetFrameAtIndex(0) + lineEntry = frame0.GetLineEntry() + self.assertTrue(lineEntry.GetLine() == self.line1) + + address1 = lineEntry.GetStartAddress() + + # Continue the inferior, the breakpoint 2 should be hit. + process.Continue() + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + #self.runCmd("process status") + frame0 = thread.GetFrameAtIndex(0) + lineEntry = frame0.GetLineEntry() + self.assertTrue(lineEntry.GetLine() == self.line2) + + address2 = lineEntry.GetStartAddress() + + #print("address1:", address1) + #print("address2:", address2) + + # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses + # from our line entry. + context1 = target.ResolveSymbolContextForAddress( + address1, lldb.eSymbolContextEverything) + context2 = target.ResolveSymbolContextForAddress( + address2, lldb.eSymbolContextEverything) + + self.assertTrue(context1 and context2) + #print("context1:", context1) + #print("context2:", context2) + + # Verify that the context point to the same function 'a'. + symbol1 = context1.GetSymbol() + symbol2 = context2.GetSymbol() + self.assertTrue(symbol1 and symbol2) + #print("symbol1:", symbol1) + #print("symbol2:", symbol2) + + from lldbsuite.test.lldbutil import get_description + desc1 = get_description(symbol1) + desc2 = get_description(symbol2) + self.assertTrue(desc1 and desc2 and desc1 == desc2, + "The two addresses should resolve to the same symbol") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/target/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/target/main.c new file mode 100644 index 00000000000..d075f2cf2d3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/target/main.c @@ -0,0 +1,59 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to test the lldb Python API SBTarget. +// +// When stopped on breakppint 1, and then 2, we can get the line entries using +// SBFrame API SBFrame.GetLineEntry(). We'll get the start addresses for the +// two line entries; with the start address (of SBAddress type), we can then +// resolve the symbol context using the SBTarget API +// SBTarget.ResolveSymbolContextForAddress(). +// +// The two symbol context should point to the same symbol, i.e., 'a' function. + +char my_global_var_of_char_type = 'X'; // Test SBTarget.FindGlobalVariables(...). + +int a(int); +int b(int); +int c(int); + +int a(int val) +{ + if (val <= 1) // Find the line number for breakpoint 1 here. + val = b(val); + else if (val >= 3) + val = c(val); + + return val; // Find the line number for breakpoint 2 here. +} + +int b(int val) +{ + return c(val); +} + +int c(int val) +{ + return val + 3; +} + +int main (int argc, char const *argv[]) +{ + // Set a break at entry to main. + 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; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/Makefile new file mode 100644 index 00000000000..30749db9a67 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES ?= main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py new file mode 100644 index 00000000000..91241385293 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py @@ -0,0 +1,282 @@ +""" +Test SBThread APIs. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +from lldbsuite.test.lldbutil import get_stopped_thread, get_caller_symbol + + +class ThreadAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + def test_get_process(self): + """Test Python SBThread.GetProcess() API.""" + self.build() + self.get_process() + + @add_test_categories(['pyapi']) + def test_get_stop_description(self): + """Test Python SBThread.GetStopDescription() API.""" + self.build() + self.get_stop_description() + + @add_test_categories(['pyapi']) + def test_run_to_address(self): + """Test Python SBThread.RunToAddress() API.""" + # We build a different executable than the default build() does. + d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.run_to_address(self.exe_name) + + @add_test_categories(['pyapi']) + @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr20476') + @expectedFailureAll(oslist=["windows"]) + @expectedFailureNetBSD + def test_step_out_of_malloc_into_function_b(self): + """Test Python SBThread.StepOut() API to step out of a malloc call where the call site is at function b().""" + # We build a different executable than the default build() does. + d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.step_out_of_malloc_into_function_b(self.exe_name) + + @add_test_categories(['pyapi']) + def test_step_over_3_times(self): + """Test Python SBThread.StepOver() API.""" + # We build a different executable than the default build() does. + d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.step_over_3_times(self.exe_name) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number within main.cpp to break inside main(). + self.break_line = line_number( + "main.cpp", "// Set break point at this line and check variable 'my_char'.") + # Find the line numbers within main2.cpp for + # step_out_of_malloc_into_function_b() and step_over_3_times(). + self.step_out_of_malloc = line_number( + "main2.cpp", "// thread step-out of malloc into function b.") + self.after_3_step_overs = line_number( + "main2.cpp", "// we should reach here after 3 step-over's.") + + # We'll use the test method name as the exe_name for executable + # comppiled from main2.cpp. + self.exe_name = self.testMethodName + + def get_process(self): + """Test Python SBThread.GetProcess() API.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation( + "main.cpp", self.break_line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + self.runCmd("breakpoint list") + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + self.runCmd("process status") + + proc_of_thread = thread.GetProcess() + #print("proc_of_thread:", proc_of_thread) + self.assertTrue(proc_of_thread.GetProcessID() + == process.GetProcessID()) + + def get_stop_description(self): + """Test Python SBThread.GetStopDescription() API.""" + exe = self.getBuildArtifact("a.out") + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation( + "main.cpp", self.break_line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + #self.runCmd("breakpoint list") + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + + # Get the stop reason. GetStopDescription expects that we pass in the size of the description + # we expect plus an additional byte for the null terminator. + + # Test with a buffer that is exactly as large as the expected stop reason. + self.assertEqual("breakpoint 1.1", thread.GetStopDescription(len('breakpoint 1.1') + 1)) + + # Test some smaller buffer sizes. + self.assertEqual("breakpoint", thread.GetStopDescription(len('breakpoint') + 1)) + self.assertEqual("break", thread.GetStopDescription(len('break') + 1)) + self.assertEqual("b", thread.GetStopDescription(len('b') + 1)) + + # Test that we can pass in a much larger size and still get the right output. + self.assertEqual("breakpoint 1.1", thread.GetStopDescription(len('breakpoint 1.1') + 100)) + + def step_out_of_malloc_into_function_b(self, exe_name): + """Test Python SBThread.StepOut() API to step out of a malloc call where the call site is at function b().""" + exe = self.getBuildArtifact(exe_name) + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByName('malloc') + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + while True: + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint") + caller_symbol = get_caller_symbol(thread) + if not caller_symbol: + self.fail( + "Test failed: could not locate the caller symbol of malloc") + + # Our top frame may be an inlined function in malloc() (e.g., on + # FreeBSD). Apply a simple heuristic of stepping out until we find + # a non-malloc caller + while caller_symbol.startswith("malloc"): + thread.StepOut() + self.assertTrue(thread.IsValid(), + "Thread valid after stepping to outer malloc") + caller_symbol = get_caller_symbol(thread) + + if caller_symbol == "b(int)": + break + process.Continue() + + # On Linux malloc calls itself in some case. Remove the breakpoint because we don't want + # to hit it during step-out. + target.BreakpointDelete(breakpoint.GetID()) + + thread.StepOut() + self.runCmd("thread backtrace") + self.assertTrue( + thread.GetFrameAtIndex(0).GetLineEntry().GetLine() == self.step_out_of_malloc, + "step out of malloc into function b is successful") + + def step_over_3_times(self, exe_name): + """Test Python SBThread.StepOver() API.""" + exe = self.getBuildArtifact(exe_name) + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation( + 'main2.cpp', self.step_out_of_malloc) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + self.runCmd("breakpoint list") + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.step_out_of_malloc. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + self.runCmd("thread backtrace") + frame0 = thread.GetFrameAtIndex(0) + lineEntry = frame0.GetLineEntry() + self.assertTrue(lineEntry.GetLine() == self.step_out_of_malloc) + + thread.StepOver() + thread.StepOver() + thread.StepOver() + self.runCmd("thread backtrace") + + # Verify that we are stopped at the correct source line number in + # main2.cpp. + frame0 = thread.GetFrameAtIndex(0) + lineEntry = frame0.GetLineEntry() + self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) + # Expected failure with clang as the compiler. + # rdar://problem/9223880 + # + # Which has been fixed on the lldb by compensating for inaccurate line + # table information with r140416. + self.assertTrue(lineEntry.GetLine() == self.after_3_step_overs) + + def run_to_address(self, exe_name): + """Test Python SBThread.RunToAddress() API.""" + exe = self.getBuildArtifact(exe_name) + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + breakpoint = target.BreakpointCreateByLocation( + 'main2.cpp', self.step_out_of_malloc) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + self.runCmd("breakpoint list") + + # Launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + self.assertTrue(process, PROCESS_IS_VALID) + + # Frame #0 should be on self.step_out_of_malloc. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + self.runCmd("thread backtrace") + frame0 = thread.GetFrameAtIndex(0) + lineEntry = frame0.GetLineEntry() + self.assertTrue(lineEntry.GetLine() == self.step_out_of_malloc) + + # Get the start/end addresses for this line entry. + start_addr = lineEntry.GetStartAddress().GetLoadAddress(target) + end_addr = lineEntry.GetEndAddress().GetLoadAddress(target) + if self.TraceOn(): + print("start addr:", hex(start_addr)) + print("end addr:", hex(end_addr)) + + # Disable the breakpoint. + self.assertTrue(target.DisableAllBreakpoints()) + self.runCmd("breakpoint list") + + thread.StepOver() + thread.StepOver() + thread.StepOver() + self.runCmd("thread backtrace") + + # Now ask SBThread to run to the address 'start_addr' we got earlier, which + # corresponds to self.step_out_of_malloc line entry's start address. + thread.RunToAddress(start_addr) + self.runCmd("process status") + #self.runCmd("thread backtrace") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/main.cpp new file mode 100644 index 00000000000..01c8404a387 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/main.cpp @@ -0,0 +1,25 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +// This simple program is to test the lldb Python API related to thread. + +char my_char = 'u'; +int my_int = 0; + +int main (int argc, char const *argv[]) +{ + for (int i = 0; i < 3; ++i) { + printf("my_char='%c'\n", my_char); + ++my_char; + } + + printf("after the loop: my_char='%c'\n", my_char); // 'my_char' should print out as 'x'. + + return 0; // Set break point at this line and check variable 'my_char'. +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/main2.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/main2.cpp new file mode 100644 index 00000000000..57c485c08c6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/thread/main2.cpp @@ -0,0 +1,53 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdlib.h> + +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) +{ + int rc = c(val); + void *ptr = malloc(1024); // thread step-out of malloc into function b. + if (!ptr) + return -1; + else + printf("ptr=%p\n", ptr); + return rc; // we should reach here after 3 step-over's. +} + +int c(int val) +{ + return val + 3; +} + +int main (int argc, char const *argv[]) +{ + int A1 = a(1); + printf("a(1) returns %d\n", A1); + + int B2 = b(2); + printf("b(2) returns %d\n", B2); + + int A3 = a(3); + printf("a(3) returns %d\n", A3); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/type/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/type/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/type/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py new file mode 100644 index 00000000000..75a793a95b2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py @@ -0,0 +1,133 @@ +""" +Test SBType and SBTypeList API. +""" + +from __future__ import print_function + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TypeAndTypeListTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to break at. + self.source = 'main.cpp' + self.line = line_number(self.source, '// Break at this line') + + @add_test_categories(['pyapi']) + def test(self): + """Exercise SBType and SBTypeList API.""" + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + exe = self.getBuildArtifact(self.exe_name) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Get Frame #0. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + + # Get the type 'Task'. + type_list = target.FindTypes('Task') + if self.TraceOn(): + print( + "Size of type_list from target.FindTypes('Task') query: %d" % + type_list.GetSize()) + # a second Task make be scared up by the Objective-C runtime + self.assertTrue(len(type_list) >= 1) + for type in type_list: + self.assertTrue(type) + self.DebugSBType(type) + self.assertFalse(type.IsAnonymousType(), "Task is not anonymous") + for field in type.fields: + if field.name == "type": + for enum_member in field.type.enum_members: + self.assertTrue(enum_member) + self.DebugSBType(enum_member.type) + elif field.name == "my_type_is_nameless": + self.assertFalse( + field.type.IsAnonymousType(), + "my_type_is_nameless is not an anonymous type") + elif field.name == "my_type_is_named": + self.assertFalse( + field.type.IsAnonymousType(), + "my_type_is_named has a named type") + elif field.name == None: + self.assertTrue( + field.type.IsAnonymousType(), + "Nameless type is not anonymous") + + # Pass an empty string. LLDB should not crash. :-) + fuzz_types = target.FindTypes(None) + fuzz_type = target.FindFirstType(None) + + # Now use the SBTarget.FindFirstType() API to find 'Task'. + task_type = target.FindFirstType('Task') + self.assertTrue(task_type) + self.DebugSBType(task_type) + + # Get the reference type of 'Task', just for fun. + task_ref_type = task_type.GetReferenceType() + self.assertTrue(task_ref_type) + self.DebugSBType(task_ref_type) + + # Get the pointer type of 'Task', which is the same as task_head's + # type. + task_pointer_type = task_type.GetPointerType() + self.assertTrue(task_pointer_type) + self.DebugSBType(task_pointer_type) + + # Get variable 'task_head'. + task_head = frame0.FindVariable('task_head') + self.assertTrue(task_head, VALID_VARIABLE) + self.DebugSBValue(task_head) + task_head_type = task_head.GetType() + self.DebugSBType(task_head_type) + self.assertTrue(task_head_type.IsPointerType()) + + self.assertTrue(task_head_type == task_pointer_type) + + # Get the pointee type of 'task_head'. + task_head_pointee_type = task_head_type.GetPointeeType() + self.DebugSBType(task_head_pointee_type) + + self.assertTrue(task_type == task_head_pointee_type) + + # We'll now get the child member 'id' from 'task_head'. + id = task_head.GetChildMemberWithName('id') + self.DebugSBValue(id) + id_type = id.GetType() + self.DebugSBType(id_type) + + # SBType.GetBasicType() takes an enum 'BasicType' + # (lldb-enumerations.h). + int_type = id_type.GetBasicType(lldb.eBasicTypeInt) + self.assertTrue(id_type == int_type) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/type/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/type/main.cpp new file mode 100644 index 00000000000..b43b617b0f9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/type/main.cpp @@ -0,0 +1,67 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +class Task { +public: + int id; + Task *next; + enum { + TASK_TYPE_1, + TASK_TYPE_2 + } type; + // This struct is anonymous b/c it does not have a name + // and it is not unnamed class. + // Anonymous classes are a GNU extension. + struct { + int y; + }; + // This struct is an unnamed class see [class.pre]p1 + // http://eel.is/c++draft/class#pre-1.sentence-6 + struct { + int x; + } my_type_is_nameless; + struct name { + int x; + } my_type_is_named; + Task(int i, Task *n): + id(i), + next(n), + type(TASK_TYPE_1) + {} +}; + + +int main (int argc, char const *argv[]) +{ + Task *task_head = new Task(-1, NULL); + Task *task1 = new Task(1, NULL); + Task *task2 = new Task(2, NULL); + Task *task3 = new Task(3, NULL); // Orphaned. + Task *task4 = new Task(4, NULL); + Task *task5 = new Task(5, NULL); + + task_head->next = task1; + task1->next = task2; + task2->next = task4; + task4->next = task5; + + int total = 0; + Task *t = task_head; + while (t != NULL) { + if (t->id >= 0) + ++total; + t = t->next; + } + printf("We have a total number of %d tasks\n", total); + + // This corresponds to an empty task list. + Task *empty_task_head = new Task(-1, NULL); + + return 0; // Break at this line +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py new file mode 100644 index 00000000000..bf8cbe34320 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py @@ -0,0 +1,193 @@ +""" +Test some SBValue APIs. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ValueAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to of function 'c'. + self.line = line_number('main.c', '// Break at this line') + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24772") + @add_test_categories(['pyapi']) + def test(self): + """Exercise some SBValue APIs.""" + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + exe = self.getBuildArtifact(self.exe_name) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation('main.c', self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Get Frame #0. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + + # Get global variable 'days_of_week'. + list = target.FindGlobalVariables('days_of_week', 1) + days_of_week = list.GetValueAtIndex(0) + self.assertTrue(days_of_week, VALID_VARIABLE) + self.assertEqual(days_of_week.GetNumChildren(), 7, VALID_VARIABLE) + self.DebugSBValue(days_of_week) + + # Use this to test the "child" and "children" accessors: + children = days_of_week.children + self.assertEqual(len(children), 7, VALID_VARIABLE) + for i in range(0, len(children)): + day = days_of_week.child[i] + list_day = children[i] + self.assertNotEqual(day, None) + self.assertNotEqual(list_day, None) + self.assertEqual(day.GetSummary(), list_day.GetSummary(), VALID_VARIABLE) + + # Spot check the actual value: + first_day = days_of_week.child[1] + self.assertEqual(first_day.GetSummary(), '"Monday"', VALID_VARIABLE) + + # Get global variable 'weekdays'. + list = target.FindGlobalVariables('weekdays', 1) + weekdays = list.GetValueAtIndex(0) + self.assertTrue(weekdays, VALID_VARIABLE) + self.assertTrue(weekdays.GetNumChildren() == 5, VALID_VARIABLE) + self.DebugSBValue(weekdays) + + # Get global variable 'g_table'. + list = target.FindGlobalVariables('g_table', 1) + g_table = list.GetValueAtIndex(0) + self.assertTrue(g_table, VALID_VARIABLE) + self.assertTrue(g_table.GetNumChildren() == 2, VALID_VARIABLE) + self.DebugSBValue(g_table) + + fmt = lldbutil.BasicFormatter() + cvf = lldbutil.ChildVisitingFormatter(indent_child=2) + rdf = lldbutil.RecursiveDecentFormatter(indent_child=2) + if self.TraceOn(): + print(fmt.format(days_of_week)) + print(cvf.format(days_of_week)) + print(cvf.format(weekdays)) + print(rdf.format(g_table)) + + # Get variable 'my_int_ptr'. + value = frame0.FindVariable('my_int_ptr') + self.assertTrue(value, VALID_VARIABLE) + self.DebugSBValue(value) + + # Get what 'my_int_ptr' points to. + pointed = value.GetChildAtIndex(0) + self.assertTrue(pointed, VALID_VARIABLE) + self.DebugSBValue(pointed) + + # While we are at it, verify that 'my_int_ptr' points to 'g_my_int'. + symbol = target.ResolveLoadAddress( + int(pointed.GetLocation(), 0)).GetSymbol() + self.assertTrue(symbol) + self.expect(symbol.GetName(), exe=False, + startstr='g_my_int') + + # Get variable 'str_ptr'. + value = frame0.FindVariable('str_ptr') + self.assertTrue(value, VALID_VARIABLE) + self.DebugSBValue(value) + + # SBValue::TypeIsPointerType() should return true. + self.assertTrue(value.TypeIsPointerType()) + + # Verify the SBValue::GetByteSize() API is working correctly. + arch = self.getArchitecture() + if arch == 'i386': + self.assertTrue(value.GetByteSize() == 4) + elif arch == 'x86_64': + self.assertTrue(value.GetByteSize() == 8) + + # Get child at index 5 => 'Friday'. + child = value.GetChildAtIndex(5, lldb.eNoDynamicValues, True) + self.assertTrue(child, VALID_VARIABLE) + self.DebugSBValue(child) + + self.expect(child.GetSummary(), exe=False, + substrs=['Friday']) + + # Now try to get at the same variable using GetValueForExpressionPath(). + # These two SBValue objects should have the same value. + val2 = value.GetValueForExpressionPath('[5]') + self.assertTrue(val2, VALID_VARIABLE) + self.DebugSBValue(val2) + self.assertTrue(child.GetValue() == val2.GetValue() and + child.GetSummary() == val2.GetSummary()) + + val_i = target.EvaluateExpression('i') + val_s = target.EvaluateExpression('s') + val_a = target.EvaluateExpression('a') + self.assertTrue( + val_s.GetChildMemberWithName('a').GetAddress().IsValid(), + VALID_VARIABLE) + self.assertTrue( + val_s.GetChildMemberWithName('a').AddressOf(), + VALID_VARIABLE) + self.assertTrue( + val_a.Cast( + val_i.GetType()).AddressOf(), + VALID_VARIABLE) + + # Check that lldb.value implements truth testing. + self.assertFalse(lldb.value(frame0.FindVariable('bogus'))) + self.assertTrue(lldb.value(frame0.FindVariable('uinthex'))) + + self.assertTrue(int(lldb.value(frame0.FindVariable('uinthex'))) + == 3768803088, 'uinthex == 3768803088') + self.assertTrue(int(lldb.value(frame0.FindVariable('sinthex'))) + == -526164208, 'sinthex == -526164208') + + # Check value_iter works correctly. + for v in [ + lldb.value(frame0.FindVariable('uinthex')), + lldb.value(frame0.FindVariable('sinthex')) + ]: + self.assertTrue(v) + + self.assertTrue( + frame0.FindVariable('uinthex').GetValueAsUnsigned() == 3768803088, + 'unsigned uinthex == 3768803088') + self.assertTrue( + frame0.FindVariable('sinthex').GetValueAsUnsigned() == 3768803088, + 'unsigned sinthex == 3768803088') + + self.assertTrue( + frame0.FindVariable('uinthex').GetValueAsSigned() == - + 526164208, + 'signed uinthex == -526164208') + self.assertTrue( + frame0.FindVariable('sinthex').GetValueAsSigned() == - + 526164208, + 'signed sinthex == -526164208') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py new file mode 100644 index 00000000000..6f0dee21af6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py @@ -0,0 +1,181 @@ +""" +Test some SBValue APIs. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ChangeValueAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to of function 'c'. + self.line = line_number('main.c', '// Stop here and set values') + self.check_line = line_number( + 'main.c', '// Stop here and check values') + self.end_line = line_number( + 'main.c', '// Set a breakpoint here at the end') + + @add_test_categories(['pyapi']) + @expectedFlakeyLinux("llvm.org/pr25652") + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24772") + def test_change_value(self): + """Exercise the SBValue::SetValueFromCString API.""" + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + exe = self.getBuildArtifact(self.exe_name) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation('main.c', self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Create the breakpoint inside the function 'main' + check_breakpoint = target.BreakpointCreateByLocation( + 'main.c', self.check_line) + self.assertTrue(check_breakpoint, VALID_BREAKPOINT) + + # Create the breakpoint inside function 'main'. + end_breakpoint = target.BreakpointCreateByLocation( + 'main.c', self.end_line) + self.assertTrue(end_breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Get Frame #0. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + self.assertTrue(frame0.IsValid(), "Got a valid frame.") + + # Get the val variable and change it: + error = lldb.SBError() + + val_value = frame0.FindVariable("val") + self.assertTrue(val_value.IsValid(), "Got the SBValue for val") + actual_value = val_value.GetValueAsSigned(error, 0) + self.assertTrue(error.Success(), "Got a value from val") + self.assertTrue(actual_value == 100, "Got the right value from val") + + result = val_value.SetValueFromCString("12345") + self.assertTrue(result, "Setting val returned True.") + actual_value = val_value.GetValueAsSigned(error, 0) + self.assertTrue(error.Success(), "Got a changed value from val") + self.assertTrue( + actual_value == 12345, + "Got the right changed value from val") + + # Now check that we can set a structure element: + + mine_value = frame0.FindVariable("mine") + self.assertTrue(mine_value.IsValid(), "Got the SBValue for mine") + + mine_second_value = mine_value.GetChildMemberWithName("second_val") + self.assertTrue( + mine_second_value.IsValid(), + "Got second_val from mine") + actual_value = mine_second_value.GetValueAsUnsigned(error, 0) + self.assertTrue( + error.Success(), + "Got an unsigned value for second_val") + self.assertTrue(actual_value == 5555) + + result = mine_second_value.SetValueFromCString("98765") + self.assertTrue(result, "Success setting mine.second_value.") + actual_value = mine_second_value.GetValueAsSigned(error, 0) + self.assertTrue( + error.Success(), + "Got a changed value from mine.second_val") + self.assertTrue(actual_value == 98765, + "Got the right changed value from mine.second_val") + + # Next do the same thing with the pointer version. + ptr_value = frame0.FindVariable("ptr") + self.assertTrue(ptr_value.IsValid(), "Got the SBValue for ptr") + + ptr_second_value = ptr_value.GetChildMemberWithName("second_val") + self.assertTrue(ptr_second_value.IsValid(), "Got second_val from ptr") + actual_value = ptr_second_value.GetValueAsUnsigned(error, 0) + self.assertTrue( + error.Success(), + "Got an unsigned value for ptr->second_val") + self.assertTrue(actual_value == 6666) + + result = ptr_second_value.SetValueFromCString("98765") + self.assertTrue(result, "Success setting ptr->second_value.") + actual_value = ptr_second_value.GetValueAsSigned(error, 0) + self.assertTrue( + error.Success(), + "Got a changed value from ptr->second_val") + self.assertTrue(actual_value == 98765, + "Got the right changed value from ptr->second_val") + + # gcc may set multiple locations for breakpoint + breakpoint.SetEnabled(False) + + # Now continue, grab the stdout and make sure we changed the real + # values as well... + process.Continue() + + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + + expected_value = "Val - 12345 Mine - 55, 98765, 55555555. Ptr - 66, 98765, 66666666" + stdout = process.GetSTDOUT(1000) + self.assertTrue( + expected_value in stdout, + "STDOUT showed changed values.") + + # Finally, change the stack pointer to 0, and we should not make it to + # our end breakpoint. + frame0 = thread.GetFrameAtIndex(0) + self.assertTrue(frame0.IsValid(), "Second time: got a valid frame.") + sp_value = frame0.FindValue("sp", lldb.eValueTypeRegister) + self.assertTrue(sp_value.IsValid(), "Got a stack pointer value") + result = sp_value.SetValueFromCString("1") + self.assertTrue(result, "Setting sp returned true.") + actual_value = sp_value.GetValueAsUnsigned(error, 0) + self.assertTrue(error.Success(), "Got a changed value for sp") + self.assertTrue( + actual_value == 1, + "Got the right changed value for sp.") + + # Boundary condition test the SBValue.CreateValueFromExpression() API. + # LLDB should not crash! + nosuchval = mine_value.CreateValueFromExpression(None, None) + + process.Continue() + + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread is None, + "We should not have managed to hit our second breakpoint with sp == 1") + + process.Kill() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/main.c new file mode 100644 index 00000000000..01455c01964 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/change_values/main.c @@ -0,0 +1,29 @@ +#include <stdio.h> +#include <stdint.h> +#include <stdlib.h> + +struct foo +{ + uint8_t first_val; + uint32_t second_val; + uint64_t third_val; +}; + +int main () +{ + int val = 100; + struct foo mine = {55, 5555, 55555555}; + struct foo *ptr = (struct foo *) malloc (sizeof (struct foo)); + ptr->first_val = 66; + ptr->second_val = 6666; + ptr->third_val = 66666666; + + // Stop here and set values + printf ("Val - %d Mine - %d, %d, %llu. Ptr - %d, %d, %llu\n", val, + mine.first_val, mine.second_val, mine.third_val, + ptr->first_val, ptr->second_val, ptr->third_val); + + // Stop here and check values + printf ("This is just another call which we won't make it over %d.", val); + return 0; // Set a breakpoint here at the end +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/empty_class/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/empty_class/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/empty_class/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/empty_class/TestValueAPIEmptyClass.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/empty_class/TestValueAPIEmptyClass.py new file mode 100644 index 00000000000..c7197e51c23 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/empty_class/TestValueAPIEmptyClass.py @@ -0,0 +1,56 @@ + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class ValueAPIEmptyClassTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + def test(self): + self.build() + exe = self.getBuildArtifact("a.out") + line = line_number('main.cpp', '// Break at this line') + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation('main.cpp', line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Get Frame #0. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + + # Verify that we can access to a frame variable with an empty class type + e = frame0.FindVariable('e') + self.assertTrue(e.IsValid(), VALID_VARIABLE) + self.DebugSBValue(e) + self.assertEqual(e.GetNumChildren(), 0) + + # Verify that we can acces to a frame variable what is a pointer to an + # empty class + ep = frame0.FindVariable('ep') + self.assertTrue(ep.IsValid(), VALID_VARIABLE) + self.DebugSBValue(ep) + + # Verify that we can dereference a pointer to an empty class + epd = ep.Dereference() + self.assertTrue(epd.IsValid(), VALID_VARIABLE) + self.DebugSBValue(epd) + self.assertEqual(epd.GetNumChildren(), 0) + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/empty_class/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/empty_class/main.cpp new file mode 100644 index 00000000000..483a57ee5c0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/empty_class/main.cpp @@ -0,0 +1,15 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +class Empty {}; + +int main (int argc, char const *argv[]) { + Empty e; + Empty* ep = new Empty; + return 0; // Break at this line +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py new file mode 100644 index 00000000000..b45186a3150 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py @@ -0,0 +1,142 @@ +""" +Test SBValue API linked_list_iter which treats the SBValue as a linked list and +supports iteration till the end of list is reached. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ValueAsLinkedListTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + self.exe_name = self.testMethodName + # Find the line number to break at. + self.line = line_number('main.cpp', '// Break at this line') + + # Py3 asserts due to a bug in SWIG. A fix for this was upstreamed into + # SWIG 3.0.8. + @skipIf(py_version=['>=', (3, 0)], swig_version=['<', (3, 0, 8)]) + @add_test_categories(['pyapi']) + def test(self): + """Exercise SBValue API linked_list_iter.""" + d = {'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + exe = self.getBuildArtifact(self.exe_name) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create the breakpoint inside function 'main'. + breakpoint = target.BreakpointCreateByLocation('main.cpp', self.line) + self.assertTrue(breakpoint, VALID_BREAKPOINT) + + # Now launch the process, and do not stop at entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + self.assertTrue(process, PROCESS_IS_VALID) + + # Get Frame #0. + self.assertTrue(process.GetState() == lldb.eStateStopped) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + self.assertTrue( + thread.IsValid(), + "There should be a thread stopped due to breakpoint condition") + frame0 = thread.GetFrameAtIndex(0) + + # Get variable 'task_head'. + task_head = frame0.FindVariable('task_head') + self.assertTrue(task_head, VALID_VARIABLE) + self.DebugSBValue(task_head) + + # By design (see main.cpp), the visited id's are: [1, 2, 4, 5]. + visitedIDs = [1, 2, 4, 5] + list = [] + + cvf = lldbutil.ChildVisitingFormatter(indent_child=2) + for t in task_head.linked_list_iter('next'): + self.assertTrue(t, VALID_VARIABLE) + # Make sure that 'next' corresponds to an SBValue with pointer + # type. + self.assertTrue(t.TypeIsPointerType()) + if self.TraceOn(): + print(cvf.format(t)) + list.append(int(t.GetChildMemberWithName("id").GetValue())) + + # Sanity checks that the we visited all the items (no more, no less). + if self.TraceOn(): + print("visited IDs:", list) + self.assertTrue(visitedIDs == list) + + # Let's exercise the linked_list_iter() API again, this time supplying + # our end of list test function. + def eol(val): + """Test function to determine end of list.""" + # End of list is reached if either the value object is invalid + # or it corresponds to a null pointer. + if not val or int(val.GetValue(), 16) == 0: + return True + # Also check the "id" for correct semantics. If id <= 0, the item + # is corrupted, let's return True to signify end of list. + if int(val.GetChildMemberWithName("id").GetValue(), 0) <= 0: + return True + + # Otherwise, return False. + return False + + list = [] + for t in task_head.linked_list_iter('next', eol): + self.assertTrue(t, VALID_VARIABLE) + # Make sure that 'next' corresponds to an SBValue with pointer + # type. + self.assertTrue(t.TypeIsPointerType()) + if self.TraceOn(): + print(cvf.format(t)) + list.append(int(t.GetChildMemberWithName("id").GetValue())) + + # Sanity checks that the we visited all the items (no more, no less). + if self.TraceOn(): + print("visited IDs:", list) + self.assertTrue(visitedIDs == list) + + # Get variable 'empty_task_head'. + empty_task_head = frame0.FindVariable('empty_task_head') + self.assertTrue(empty_task_head, VALID_VARIABLE) + self.DebugSBValue(empty_task_head) + + list = [] + # There is no iterable item from empty_task_head.linked_list_iter(). + for t in empty_task_head.linked_list_iter('next', eol): + if self.TraceOn(): + print(cvf.format(t)) + list.append(int(t.GetChildMemberWithName("id").GetValue())) + + self.assertTrue(len(list) == 0) + + # Get variable 'task_evil'. + task_evil = frame0.FindVariable('task_evil') + self.assertTrue(task_evil, VALID_VARIABLE) + self.DebugSBValue(task_evil) + + list = [] + # There 3 iterable items from task_evil.linked_list_iter(). :-) + for t in task_evil.linked_list_iter('next'): + if self.TraceOn(): + print(cvf.format(t)) + list.append(int(t.GetChildMemberWithName("id").GetValue())) + + self.assertTrue(len(list) == 3) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/main.cpp new file mode 100644 index 00000000000..edd175ae266 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/linked_list/main.cpp @@ -0,0 +1,55 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> + +class Task { +public: + int id; + Task *next; + Task(int i, Task *n): + id(i), + next(n) + {} +}; + + +int main (int argc, char const *argv[]) +{ + Task *task_head = NULL; + Task *task1 = new Task(1, NULL); + Task *task2 = new Task(2, NULL); + Task *task3 = new Task(3, NULL); // Orphaned. + Task *task4 = new Task(4, NULL); + Task *task5 = new Task(5, NULL); + + task_head = task1; + task1->next = task2; + task2->next = task4; + task4->next = task5; + + int total = 0; + Task *t = task_head; + while (t != NULL) { + if (t->id >= 0) + ++total; + t = t->next; + } + printf("We have a total number of %d tasks\n", total); + + // This corresponds to an empty task list. + Task *empty_task_head = NULL; + + Task *task_evil = new Task(1, NULL); + Task *task_2 = new Task(2, NULL); + Task *task_3 = new Task(3, NULL); + task_evil->next = task_2; + task_2->next = task_3; + task_3->next = task_evil; // In order to cause inifinite loop. :-) + + return 0; // Break at this line +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/main.c new file mode 100644 index 00000000000..68b3c12cce4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value/main.c @@ -0,0 +1,55 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +// This simple program is to test the lldb Python API SBValue.GetChildAtIndex(). + +int g_my_int = 100; + +const char *days_of_week[7] = { "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" }; + +const char *weekdays[5] = { "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday" }; + +const char **g_table[2] = { days_of_week, weekdays }; + +typedef int MyInt; + +struct MyStruct +{ + int a; + int b; +}; + +int main (int argc, char const *argv[]) +{ + uint32_t uinthex = 0xE0A35F10; + int32_t sinthex = 0xE0A35F10; + + int i; + MyInt a = 12345; + struct MyStruct s = { 11, 22 }; + int *my_int_ptr = &g_my_int; + printf("my_int_ptr points to location %p\n", my_int_ptr); + const char **str_ptr = days_of_week; + for (i = 0; i < 7; ++i) + printf("%s\n", str_ptr[i]); // Break at this line + // and do str_ptr_val.GetChildAtIndex(5, lldb.eNoDynamicValues, True). + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/Makefile new file mode 100644 index 00000000000..3716c6e29e9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/Makefile @@ -0,0 +1,6 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 +# See TestHelloWorld.py, which specifies the executable name with a dictionary. +EXE := hello_world + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py new file mode 100644 index 00000000000..b425cef6e1e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py @@ -0,0 +1,62 @@ +"""Test SBValue::GetValueDidChange""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class ValueVarUpdateTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @add_test_categories(['pyapi']) + def test_with_process_launch_api(self): + """Test SBValue::GetValueDidChange""" + # Get the full path to our executable to be attached/debugged. + exe = self.getBuildArtifact(self.testMethodName) + d = {'EXE': exe} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + target = self.dbg.CreateTarget(exe) + + breakpoint = target.BreakpointCreateBySourceRegex( + "break here", lldb.SBFileSpec("main.c")) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'stop reason = breakpoint']) + + i = self.frame().FindVariable("i") + i_val = i.GetValueAsUnsigned(0) + c = self.frame().FindVariable("c") + + # Update any values from the SBValue objects so we can ask them if they + # changed after a continue + i.GetValueDidChange() + c.GetChildAtIndex(1).GetValueDidChange() + c.GetChildAtIndex(0).GetChildAtIndex(0).GetValueDidChange() + + if self.TraceOn(): + self.runCmd("frame variable") + + self.runCmd("continue") + + if self.TraceOn(): + self.runCmd("frame variable") + + self.assertTrue( + i_val != i.GetValueAsUnsigned(0), + "GetValue() is saying a lie") + self.assertTrue( + i.GetValueDidChange(), + "GetValueDidChange() is saying a lie") + + # Check complex type + self.assertTrue(c.GetChildAtIndex(0).GetChildAtIndex(0).GetValueDidChange( + ) and not c.GetChildAtIndex(1).GetValueDidChange(), "GetValueDidChange() is saying a lie") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/main.c new file mode 100644 index 00000000000..9ffca5cbb9f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/value_var_update/main.c @@ -0,0 +1,15 @@ +struct complex_type { + struct { long l; } inner; + struct complex_type *complex_ptr; +}; + +int main() { + int i = 0; + struct complex_type c = { { 1L }, &c }; + for (int j = 3; j < 20; j++) + { + c.inner.l += (i += j); + i = i - 1; // break here + } + return i; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/.categories new file mode 100644 index 00000000000..50c1613cda7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/.categories @@ -0,0 +1 @@ +watchpoint diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py new file mode 100644 index 00000000000..a34806d1657 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py @@ -0,0 +1,106 @@ +""" +Use lldb Python SBValue API to create a watchpoint for read_write of 'globl' var. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SetWatchpointAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.c' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + + @add_test_categories(['pyapi']) + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_watch_val(self): + """Exercise SBValue.Watch() API to set a watchpoint.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # We should be stopped due to the breakpoint. Get frame #0. + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + frame0 = thread.GetFrameAtIndex(0) + + # Watch 'global' for read and write. + value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) + error = lldb.SBError() + watchpoint = value.Watch(True, True, True, error) + self.assertTrue(value and watchpoint, + "Successfully found the variable and set a watchpoint") + self.DebugSBValue(value) + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + print(watchpoint) + + # Continue. Expect the program to stop due to the variable being + # written to. + process.Continue() + + if (self.TraceOn()): + lldbutil.print_stacktraces(process) + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) + self.assertTrue(thread, "The thread stopped due to watchpoint") + self.DebugSBValue(value) + + # Continue. Expect the program to stop due to the variable being read + # from. + process.Continue() + + if (self.TraceOn()): + lldbutil.print_stacktraces(process) + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) + self.assertTrue(thread, "The thread stopped due to watchpoint") + self.DebugSBValue(value) + + # Continue the process. We don't expect the program to be stopped + # again. + process.Continue() + + # At this point, the inferior process should have exited. + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) + + self.dbg.DeleteTarget(target) + self.assertFalse(watchpoint.IsValid()) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py new file mode 100644 index 00000000000..83a11d42346 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py @@ -0,0 +1,92 @@ +""" +Use lldb Python SBWatchpoint API to set the ignore count. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointIgnoreCountTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.c' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + + @add_test_categories(['pyapi']) + # Read-write watchpoints not supported on SystemZ + @expectedFailureAll(archs=['s390x']) + def test_set_watch_ignore_count(self): + """Test SBWatchpoint.SetIgnoreCount() API.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create a breakpoint on main.c in order to set our watchpoint later. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # We should be stopped due to the breakpoint. Get frame #0. + process = target.GetProcess() + self.assertEqual(process.GetState(), lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + frame0 = thread.GetFrameAtIndex(0) + + # Watch 'global' for read and write. + value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) + error = lldb.SBError() + watchpoint = value.Watch(True, True, True, error) + self.assertTrue(value and watchpoint, + "Successfully found the variable and set a watchpoint") + self.DebugSBValue(value) + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + # There should be only 1 watchpoint location under the target. + self.assertEqual(target.GetNumWatchpoints(), 1) + watchpoint = target.GetWatchpointAtIndex(0) + self.assertTrue(watchpoint.IsEnabled()) + self.assertEqual(watchpoint.GetIgnoreCount(), 0) + watch_id = watchpoint.GetID() + self.assertNotEqual(watch_id, 0) + print(watchpoint) + + # Now immediately set the ignore count to 2. When we continue, expect the + # inferior to run to its completion without stopping due to watchpoint. + watchpoint.SetIgnoreCount(2) + print(watchpoint) + process.Continue() + + # At this point, the inferior process should have exited. + self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED) + + # Verify some vital statistics. + self.assertTrue(watchpoint) + self.assertEqual(watchpoint.GetWatchSize(), 4) + self.assertEqual(watchpoint.GetHitCount(), 2) + print(watchpoint) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py new file mode 100644 index 00000000000..44df96bae5e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py @@ -0,0 +1,125 @@ +""" +Use lldb Python SBTarget API to iterate on the watchpoint(s) for the target. +""" + +from __future__ import print_function + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointIteratorTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + # hardware watchpoints are not reported with a hardware index # on armv7 on ios devices + def affected_by_radar_34564183(self): + return (self.getArchitecture() in ['armv7', 'armv7k', 'arm64_32']) and self.platformIsDarwin() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.c' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + + @add_test_categories(['pyapi']) + def test_watch_iter(self): + """Exercise SBTarget.watchpoint_iter() API to iterate on the available watchpoints.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Create a breakpoint on main.c in order to set our watchpoint later. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # We should be stopped due to the breakpoint. Get frame #0. + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + frame0 = thread.GetFrameAtIndex(0) + + # Watch 'global' for read and write. + value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) + error = lldb.SBError() + watchpoint = value.Watch(True, False, True, error) + self.assertTrue(value and watchpoint, + "Successfully found the variable and set a watchpoint") + self.DebugSBValue(value) + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + # There should be only 1 watchpoint location under the target. + self.assertTrue(target.GetNumWatchpoints() == 1) + self.assertTrue(watchpoint.IsEnabled()) + watch_id = watchpoint.GetID() + self.assertTrue(watch_id != 0) + + # Continue. Expect the program to stop due to the variable being + # written to. + process.Continue() + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + # Print the stack traces. + lldbutil.print_stacktraces(process) + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) + self.assertTrue(thread, "The thread stopped due to watchpoint") + self.DebugSBValue(value) + + # We currently only support hardware watchpoint. Verify that we have a + # meaningful hardware index at this point. Exercise the printed repr of + # SBWatchpointLocation. + print(watchpoint) + if not self.affected_by_radar_34564183(): + self.assertTrue(watchpoint.GetHardwareIndex() != -1) + + # SBWatchpoint.GetDescription() takes a description level arg. + print(lldbutil.get_description(watchpoint, lldb.eDescriptionLevelFull)) + + # Now disable the 'rw' watchpoint. The program won't stop when it reads + # 'global' next. + watchpoint.SetEnabled(False) + self.assertTrue(watchpoint.GetHardwareIndex() == -1) + self.assertFalse(watchpoint.IsEnabled()) + + # Continue. The program does not stop again when the variable is being + # read from because the watchpoint location has been disabled. + process.Continue() + + # At this point, the inferior process should have exited. + self.assertTrue( + process.GetState() == lldb.eStateExited, + PROCESS_EXITED) + + # Verify some vital statistics and exercise the iterator API. + for watchpoint in target.watchpoint_iter(): + self.assertTrue(watchpoint) + self.assertTrue(watchpoint.GetWatchSize() == 4) + self.assertTrue(watchpoint.GetHitCount() == 1) + print(watchpoint) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py new file mode 100644 index 00000000000..733473411ac --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py @@ -0,0 +1,95 @@ +""" +Test watchpoint condition API. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class WatchpointConditionAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.cpp' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + # And the watchpoint variable declaration line number. + self.decl = line_number(self.source, + '// Watchpoint variable declaration.') + # Build dictionary to have unique executable names for each test + # method. + self.exe_name = self.testMethodName + self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name} + + def test_watchpoint_cond_api(self): + """Test watchpoint condition API.""" + self.build(dictionary=self.d) + self.setTearDownCleanup(dictionary=self.d) + exe = self.getBuildArtifact(self.exe_name) + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # We should be stopped due to the breakpoint. Get frame #0. + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + frame0 = thread.GetFrameAtIndex(0) + + # Watch 'global' for write. + value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal) + error = lldb.SBError() + watchpoint = value.Watch(True, False, True, error) + self.assertTrue(value and watchpoint, + "Successfully found the variable and set a watchpoint") + self.DebugSBValue(value) + + # Now set the condition as "global==5". + watchpoint.SetCondition('global==5') + self.expect(watchpoint.GetCondition(), exe=False, + startstr='global==5') + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + print(watchpoint) + + # Continue. Expect the program to stop due to the variable being + # written to. + process.Continue() + + if (self.TraceOn()): + lldbutil.print_stacktraces(process) + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) + self.assertTrue(thread, "The thread stopped due to watchpoint") + self.DebugSBValue(value) + + # Verify that the condition is met. + self.assertTrue(value.GetValueAsUnsigned() == 5) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/main.cpp new file mode 100644 index 00000000000..3f7c5f5be96 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/condition/main.cpp @@ -0,0 +1,27 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +int32_t global = 0; // Watchpoint variable declaration. + +static void modify(int32_t &var) { + ++var; +} + +int main(int argc, char** argv) { + int local = 0; + printf("&global=%p\n", &global); + printf("about to write to 'global'...\n"); // Set break point at this line. + // When stopped, watch 'global', + // for the condition "global == 5". + for (int i = 0; i < 10; ++i) + modify(global); + + printf("global=%d\n", global); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/main.c new file mode 100644 index 00000000000..6cda6d7c886 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/main.c @@ -0,0 +1,23 @@ +//===-- main.c --------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#include <stdio.h> +#include <stdint.h> + +int32_t global = 10; // Watchpoint variable declaration. + +int main(int argc, char** argv) { + int local = 0; + printf("&global=%p\n", &global); + printf("about to write to 'global'...\n"); // Set break point at this line. + // When stopped, watch 'global' for read&write. + global = 20; + local += argc; + ++local; + printf("local: %d\n", local); + printf("global=%d\n", global); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/Makefile new file mode 100644 index 00000000000..de4ec12b13c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/Makefile @@ -0,0 +1,4 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py new file mode 100644 index 00000000000..9cbc396e7a5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py @@ -0,0 +1,100 @@ +""" +Use lldb Python SBValue.WatchPointee() API to create a watchpoint for write of '*g_char_ptr'. +""" + +from __future__ import print_function + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class SetWatchlocationAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.cpp' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + # This is for verifying that watch location works. + self.violating_func = "do_bad_thing_with_location" + + @add_test_categories(['pyapi']) + def test_watch_location(self): + """Exercise SBValue.WatchPointee() API to set a watchpoint.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # We should be stopped due to the breakpoint. Get frame #0. + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + frame0 = thread.GetFrameAtIndex(0) + + value = frame0.FindValue('g_char_ptr', + lldb.eValueTypeVariableGlobal) + pointee = value.CreateValueFromAddress( + "pointee", + value.GetValueAsUnsigned(0), + value.GetType().GetPointeeType()) + # Watch for write to *g_char_ptr. + error = lldb.SBError() + watchpoint = value.WatchPointee(True, False, True, error) + self.assertTrue(value and watchpoint, + "Successfully found the pointer and set a watchpoint") + self.DebugSBValue(value) + self.DebugSBValue(pointee) + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + print(watchpoint) + + # Continue. Expect the program to stop due to the variable being + # written to. + process.Continue() + + if (self.TraceOn()): + lldbutil.print_stacktraces(process) + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) + self.assertTrue(thread, "The thread stopped due to watchpoint") + self.DebugSBValue(value) + self.DebugSBValue(pointee) + + self.expect( + lldbutil.print_stacktrace( + thread, + string_buffer=True), + exe=False, + substrs=[ + self.violating_func]) + + # This finishes our test. diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py new file mode 100644 index 00000000000..53e794db03f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py @@ -0,0 +1,145 @@ +""" +Use lldb Python SBtarget.WatchAddress() API to create a watchpoint for write of '*g_char_ptr'. +""" + +from __future__ import print_function + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TargetWatchAddressAPITestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Our simple source filename. + self.source = 'main.cpp' + # Find the line number to break inside main(). + self.line = line_number( + self.source, '// Set break point at this line.') + # This is for verifying that watch location works. + self.violating_func = "do_bad_thing_with_location" + + @add_test_categories(['pyapi']) + def test_watch_address(self): + """Exercise SBTarget.WatchAddress() API to set a watchpoint.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # We should be stopped due to the breakpoint. Get frame #0. + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + frame0 = thread.GetFrameAtIndex(0) + + value = frame0.FindValue('g_char_ptr', + lldb.eValueTypeVariableGlobal) + pointee = value.CreateValueFromAddress( + "pointee", + value.GetValueAsUnsigned(0), + value.GetType().GetPointeeType()) + # Watch for write to *g_char_ptr. + error = lldb.SBError() + watchpoint = target.WatchAddress( + value.GetValueAsUnsigned(), 1, False, True, error) + self.assertTrue(value and watchpoint, + "Successfully found the pointer and set a watchpoint") + self.DebugSBValue(value) + self.DebugSBValue(pointee) + + # Hide stdout if not running with '-t' option. + if not self.TraceOn(): + self.HideStdout() + + print(watchpoint) + + # Continue. Expect the program to stop due to the variable being + # written to. + process.Continue() + + if (self.TraceOn()): + lldbutil.print_stacktraces(process) + + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonWatchpoint) + self.assertTrue(thread, "The thread stopped due to watchpoint") + self.DebugSBValue(value) + self.DebugSBValue(pointee) + + self.expect( + lldbutil.print_stacktrace( + thread, + string_buffer=True), + exe=False, + substrs=[ + self.violating_func]) + + # This finishes our test. + + @add_test_categories(['pyapi']) + # No size constraint on MIPS for watches + @skipIf(archs=['mips', 'mipsel', 'mips64', 'mips64el']) + @skipIf(archs=['s390x']) # Likewise on SystemZ + def test_watch_address_with_invalid_watch_size(self): + """Exercise SBTarget.WatchAddress() API but pass an invalid watch_size.""" + self.build() + exe = self.getBuildArtifact("a.out") + + # Create a target by the debugger. + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Now create a breakpoint on main.c. + breakpoint = target.BreakpointCreateByLocation(self.source, self.line) + self.assertTrue(breakpoint and + breakpoint.GetNumLocations() == 1, + VALID_BREAKPOINT) + + # Now launch the process, and do not stop at the entry point. + process = target.LaunchSimple( + None, None, self.get_process_working_directory()) + + # We should be stopped due to the breakpoint. Get frame #0. + process = target.GetProcess() + self.assertTrue(process.GetState() == lldb.eStateStopped, + PROCESS_STOPPED) + thread = lldbutil.get_stopped_thread( + process, lldb.eStopReasonBreakpoint) + frame0 = thread.GetFrameAtIndex(0) + + value = frame0.FindValue('g_char_ptr', + lldb.eValueTypeVariableGlobal) + pointee = value.CreateValueFromAddress( + "pointee", + value.GetValueAsUnsigned(0), + value.GetType().GetPointeeType()) + # Watch for write to *g_char_ptr. + error = lldb.SBError() + watchpoint = target.WatchAddress( + value.GetValueAsUnsigned(), 365, False, True, error) + self.assertFalse(watchpoint) + self.expect(error.GetCString(), exe=False, + substrs=['watch size of %d is not supported' % 365]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/main.cpp new file mode 100644 index 00000000000..e455331bc16 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/main.cpp @@ -0,0 +1,103 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <chrono> +#include <condition_variable> +#include <cstdio> +#include <random> +#include <thread> + +std::default_random_engine g_random_engine{std::random_device{}()}; +std::uniform_int_distribution<> g_distribution{0, 3000000}; +std::condition_variable g_condition_variable; +std::mutex g_mutex; +int g_count; + +char *g_char_ptr = nullptr; + +void +barrier_wait() +{ + std::unique_lock<std::mutex> lock{g_mutex}; + if (--g_count > 0) + g_condition_variable.wait(lock); + else + g_condition_variable.notify_all(); +} + +void +do_bad_thing_with_location(char *char_ptr, char new_val) +{ + *char_ptr = new_val; +} + +uint32_t +access_pool (bool flag = false) +{ + static std::mutex g_access_mutex; + if (!flag) + g_access_mutex.lock(); + + char old_val = *g_char_ptr; + if (flag) + do_bad_thing_with_location(g_char_ptr, old_val + 1); + + if (!flag) + g_access_mutex.unlock(); + return *g_char_ptr; +} + +void +thread_func (uint32_t thread_index) +{ + printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index); + + barrier_wait(); + + uint32_t count = 0; + uint32_t val; + while (count++ < 15) + { + // random micro second sleep from zero to 3 seconds + int usec = g_distribution(g_random_engine); + printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec); + std::this_thread::sleep_for(std::chrono::microseconds{usec}); + + if (count < 7) + val = access_pool (); + else + val = access_pool (true); + + printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count); + } + printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index); +} + + +int main (int argc, char const *argv[]) +{ + g_count = 4; + std::thread threads[3]; + + g_char_ptr = new char{}; + + // Create 3 threads + for (auto &thread : threads) + thread = std::thread{thread_func, std::distance(threads, &thread)}; + + printf ("Before turning all three threads loose...\n"); // Set break point at this line. + barrier_wait(); + + // Join all of our threads + for (auto &thread : threads) + thread.join(); + + delete g_char_ptr; + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/redo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/redo.py new file mode 100644 index 00000000000..03052c3a08c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/redo.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python + +""" +A simple utility to redo the failed/errored tests. + +You need to specify the session directory in order for this script to locate the +tests which need to be re-run. + +See also dotest.py, the test driver running the test suite. + +Type: + +./dotest.py -h + +for help. +""" + +from __future__ import print_function + +import os +import sys +import datetime +import re + +# If True, redo with no '-t' option for the test driver. +no_trace = False + +# To be filled with the filterspecs found in the session logs. +redo_specs = [] + +# The filename components to match for. Only files with the contained component names +# will be considered for re-run. Examples: ['X86_64', 'clang']. +filename_components = [] + +do_delay = False + +# There is a known bug with respect to comp_specs and arch_specs, in that if we +# encountered "-C clang" and "-C gcc" when visiting the session files, both +# compilers will end up in the invocation of the test driver when rerunning. +# That is: ./dotest -v -C clang^gcc ... -f ...". Ditto for "-A" flags. + +# The "-C compiler" for comp_specs. +comp_specs = set() +# The "-A arch" for arch_specs. +arch_specs = set() + + +def usage(): + print("""\ +Usage: redo.py [-F filename_component] [-n] [session_dir] [-d] +where options: +-F : only consider the test for re-run if the session filename contains the filename component + for example: -F x86_64 +-n : when running the tests, do not turn on trace mode, i.e, no '-t' option + is passed to the test driver (this will run the tests faster) +-d : pass -d down to the test driver (introduces a delay so you can attach with a debugger) + +and session_dir specifies the session directory which contains previously +recorded session infos for all the test cases which either failed or errored. + +If sessin_dir is left unspecified, this script uses the heuristic to find the +possible session directories with names starting with %Y-%m-%d- (for example, +2012-01-23-) and employs the one with the latest timestamp.""") + sys.exit(0) + + +def where(session_dir, test_dir): + """Returns the full path to the session directory; None if non-existent.""" + abspath = os.path.abspath(session_dir) + if os.path.isdir(abspath): + return abspath + + session_dir_path = os.path.join(test_dir, session_dir) + if os.path.isdir(session_dir_path): + return session_dir_path + + return None + +# This is the pattern for the line from the log file to redo a test. +# We want the filter spec. +filter_pattern = re.compile("^\./dotest\.py.*-f (.*)$") +comp_pattern = re.compile(" -C ([^ ]+) ") +arch_pattern = re.compile(" -A ([^ ]+) ") + + +def redo(suffix, dir, names): + """Visitor function for os.path.walk(path, visit, arg).""" + global redo_specs + global comp_specs + global arch_specs + global filter_pattern + global comp_pattern + global arch_pattern + global filename_components + global do_delay + + for name in names: + if name.endswith(suffix): + #print("Find a log file:", name) + if name.startswith("Error") or name.startswith("Failure"): + if filename_components: + if not all([comp in name for comp in filename_components]): + continue + with open(os.path.join(dir, name), 'r') as log: + content = log.read() + for line in content.splitlines(): + match = filter_pattern.match(line) + if match: + filterspec = match.group(1) + print("adding filterspec:", filterspec) + redo_specs.append(filterspec) + comp = comp_pattern.search(line) + if comp: + comp_specs.add(comp.group(1)) + arch = arch_pattern.search(line) + if arch: + arch_specs.add(arch.group(1)) + else: + continue + + +def main(): + """Read the session directory and run the failed test cases one by one.""" + global no_trace + global redo_specs + global filename_components + global do_delay + + test_dir = sys.path[0] + if not test_dir: + test_dir = os.getcwd() + if not test_dir.endswith('test'): + print("This script expects to reside in lldb's test directory.") + sys.exit(-1) + + index = 1 + while index < len(sys.argv): + if sys.argv[index].startswith( + '-h') or sys.argv[index].startswith('--help'): + usage() + + if sys.argv[index].startswith('-'): + # We should continue processing... + pass + else: + # End of option processing. + break + + if sys.argv[index] == '-F': + # Increment by 1 to fetch the filename component spec. + index += 1 + if index >= len(sys.argv) or sys.argv[index].startswith('-'): + usage() + filename_components.append(sys.argv[index]) + elif sys.argv[index] == '-n': + no_trace = True + elif sys.argv[index] == '-d': + do_delay = True + + index += 1 + + if index < len(sys.argv): + # Get the specified session directory. + session_dir = sys.argv[index] + else: + # Use heuristic to find the latest session directory. + name = datetime.datetime.now().strftime("%Y-%m-%d-") + dirs = [d for d in os.listdir(os.getcwd()) if d.startswith(name)] + if len(dirs) == 0: + print("No default session directory found, please specify it explicitly.") + usage() + session_dir = max(dirs, key=os.path.getmtime) + if not session_dir or not os.path.exists(session_dir): + print("No default session directory found, please specify it explicitly.") + usage() + + #print("The test directory:", test_dir) + session_dir_path = where(session_dir, test_dir) + + print("Using session dir path:", session_dir_path) + os.chdir(test_dir) + os.path.walk(session_dir_path, redo, ".log") + + if not redo_specs: + print("No failures/errors recorded within the session directory, please specify a different session directory.\n") + usage() + + filters = " -f ".join(redo_specs) + compilers = '' + for comp in comp_specs: + compilers += " -C %s" % (comp) + archs = '' + for arch in arch_specs: + archs += "--arch %s " % (arch) + + command = "./dotest.py %s %s -v %s %s -f " % ( + compilers, archs, "" if no_trace else "-t", "-d" if do_delay else "") + + print("Running %s" % (command + filters)) + os.system(command + filters) + +if __name__ == '__main__': + main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/Makefile new file mode 100644 index 00000000000..695335e068c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/Makefile @@ -0,0 +1,4 @@ +C_SOURCES := main.c +CFLAGS_EXTRAS := -std=c99 + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/TestSampleInlineTest.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/TestSampleInlineTest.py new file mode 100644 index 00000000000..29fad79de81 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/TestSampleInlineTest.py @@ -0,0 +1,10 @@ +""" +Describe the purpose of the test here. +""" + +from __future__ import absolute_import + +from lldbsuite.test import lldbinline + +lldbinline.MakeInlineTest( + __file__, globals(), None) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/TestSampleTest.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/TestSampleTest.py new file mode 100644 index 00000000000..9c5b3ea3303 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/TestSampleTest.py @@ -0,0 +1,48 @@ +""" +Describe the purpose of the test class here. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class RenameThisSampleTestTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + # If your test case doesn't stress debug info, the + # set this to true. That way it won't be run once for + # each debug info format. + NO_DEBUG_INFO_TESTCASE = True + + def test_sample_rename_this(self): + """There can be many tests in a test case - describe this test here.""" + self.build() + self.main_source_file = lldb.SBFileSpec("main.c") + self.sample_test() + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Set up your test case here. If your test doesn't need any set up then + # remove this method from your TestCase class. + + def sample_test(self): + """You might use the test implementation in several ways, say so here.""" + + # This function starts a process, "a.out" by default, sets a source + # breakpoint, runs to it, and returns the thread, process & target. + # It optionally takes an SBLaunchOption argument if you want to pass + # arguments or environment variables. + (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self, + "Set a breakpoint here", self.main_source_file) + + frame = thread.GetFrameAtIndex(0) + test_var = frame.FindVariable("test_var") + self.assertTrue(test_var.GetError().Success(), "Failed to fetch test_var") + test_value = test_var.GetValueAsUnsigned() + self.assertEqual(test_value, 10, "Got the right value for test_var") + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/main.c new file mode 100644 index 00000000000..0164d7155b0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sample_test/main.c @@ -0,0 +1,13 @@ +#include <stdio.h> + +int +main() +{ + int test_var = 10; + printf ("Set a breakpoint here: %d.\n", test_var); + //% test_var = self.frame().FindVariable("test_var") + //% test_value = test_var.GetValueAsUnsigned() + //% self.assertTrue(test_var.GetError().Success(), "Failed to fetch test_var") + //% self.assertEqual(test_value, 10, "Failed to get the right value for test_var") + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/sanity/TestModuleCacheSanity.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sanity/TestModuleCacheSanity.py new file mode 100644 index 00000000000..3d9f171caba --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/sanity/TestModuleCacheSanity.py @@ -0,0 +1,21 @@ +""" +This is a sanity check that verifies that the module cache path is set +correctly and points inside the default test build directory. +""" + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class ModuleCacheSanityTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def test(self): + self.expect( + 'settings show symbols.clang-modules-cache-path', + substrs=['lldb-test-build.noindex', 'module-cache-lldb']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/Makefile new file mode 100644 index 00000000000..a78dc11e071 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/Makefile @@ -0,0 +1,11 @@ +C_SOURCES := main-copy.c + +include Makefile.rules + +# Copy file into the build folder to enable the test to modify it. +main-copy.c: main.c + cp -f $< $@ + + +clean:: + $(RM) main-copy.c diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py new file mode 100644 index 00000000000..f91d0760277 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py @@ -0,0 +1,264 @@ +""" +Test lldb core component: SourceManager. + +Test cases: + +o test_display_source_python: + Test display of source using the SBSourceManager API. +o test_modify_source_file_while_debugging: + Test the caching mechanism of the source manager. +""" + +from __future__ import print_function + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +def ansi_underline_surround_regex(inner_regex_text): + # return re.compile(r"\[4m%s\[0m" % inner_regex_text) + return "4.+\033\\[4m%s\033\\[0m" % inner_regex_text + +def ansi_color_surround_regex(inner_regex_text): + return "\033\\[3[0-7]m%s\033\\[0m" % inner_regex_text + +class SourceManagerTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + NO_DEBUG_INFO_TESTCASE = True + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # Find the line number to break inside main(). + self.file = self.getBuildArtifact("main-copy.c") + self.line = line_number("main.c", '// Set break point at this line.') + + def get_expected_stop_column_number(self): + """Return the 1-based column number of the first non-whitespace + character in the breakpoint source line.""" + stop_line = get_line(self.file, self.line) + # The number of spaces that must be skipped to get to the first non- + # whitespace character --- where we expect the debugger breakpoint + # column to be --- is equal to the number of characters that get + # stripped off the front when we lstrip it, plus one to specify + # the character column after the initial whitespace. + return len(stop_line) - len(stop_line.lstrip()) + 1 + + def do_display_source_python_api(self, use_color, needle_regex, highlight_source=False): + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + target = self.dbg.CreateTarget(exe) + self.assertTrue(target, VALID_TARGET) + + # Launch the process, and do not stop at the entry point. + args = None + envp = None + process = target.LaunchSimple( + args, envp, self.get_process_working_directory()) + self.assertIsNotNone(process) + + # + # Exercise Python APIs to display source lines. + # + + # Setup whether we should use ansi escape sequences, including color + # and styles such as underline. + self.dbg.SetUseColor(use_color) + # Disable syntax highlighting if needed. + + self.runCmd("settings set highlight-source " + str(highlight_source).lower()) + + filespec = lldb.SBFileSpec(self.file, False) + source_mgr = self.dbg.GetSourceManager() + # Use a string stream as the destination. + stream = lldb.SBStream() + column = self.get_expected_stop_column_number() + context_before = 2 + context_after = 2 + current_line_prefix = "=>" + source_mgr.DisplaySourceLinesWithLineNumbersAndColumn( + filespec, self.line, column, context_before, context_after, + current_line_prefix, stream) + + # 2 + # 3 int main(int argc, char const *argv[]) { + # => 4 printf("Hello world.\n"); // Set break point at this line. + # 5 return 0; + # 6 } + self.expect(stream.GetData(), "Source code displayed correctly:\n" + stream.GetData(), + exe=False, + patterns=['=> %d.*Hello world' % self.line, + needle_regex]) + + # Boundary condition testings for SBStream(). LLDB should not crash! + stream.Print(None) + stream.RedirectToFile(None, True) + + @add_test_categories(['pyapi']) + def test_display_source_python_dumb_terminal(self): + """Test display of source using the SBSourceManager API, using a + dumb terminal and thus no color support (the default).""" + use_color = False + self.do_display_source_python_api(use_color, r"\s+\^") + + @add_test_categories(['pyapi']) + def test_display_source_python_ansi_terminal(self): + """Test display of source using the SBSourceManager API, using a + dumb terminal and thus no color support (the default).""" + use_color = True + underline_regex = ansi_underline_surround_regex(r"printf") + self.do_display_source_python_api(use_color, underline_regex) + + @add_test_categories(['pyapi']) + def test_display_source_python_ansi_terminal_syntax_highlighting(self): + """Test display of source using the SBSourceManager API and check for + the syntax highlighted output""" + use_color = True + syntax_highlighting = True; + + # Just pick 'int' as something that should be colored. + color_regex = ansi_color_surround_regex("int") + self.do_display_source_python_api(use_color, color_regex, syntax_highlighting) + + # Same for 'char'. + color_regex = ansi_color_surround_regex("char") + self.do_display_source_python_api(use_color, color_regex, syntax_highlighting) + + # Test that we didn't color unrelated identifiers. + self.do_display_source_python_api(use_color, r" main\(", syntax_highlighting) + self.do_display_source_python_api(use_color, r"\);", syntax_highlighting) + + def test_move_and_then_display_source(self): + """Test that target.source-map settings work by moving main.c to hidden/main.c.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + # Move main.c to hidden/main.c. + hidden = self.getBuildArtifact("hidden") + lldbutil.mkdir_p(hidden) + main_c_hidden = os.path.join(hidden, "main-copy.c") + os.rename(self.file, main_c_hidden) + + if self.TraceOn(): + system([["ls"]]) + system([["ls", "hidden"]]) + + # Set source remapping with invalid replace path and verify we get an + # error + self.expect( + "settings set target.source-map /a/b/c/d/e /q/r/s/t/u", + error=True, + substrs=['''error: the replacement path doesn't exist: "/q/r/s/t/u"''']) + + # 'make -C' has resolved current directory to its realpath form. + builddir_real = os.path.realpath(self.getBuildDir()) + hidden_real = os.path.realpath(hidden) + # Set target.source-map settings. + self.runCmd("settings set target.source-map %s %s" % + (builddir_real, hidden_real)) + # And verify that the settings work. + self.expect("settings show target.source-map", + substrs=[builddir_real, hidden_real]) + + # Display main() and verify that the source mapping has been kicked in. + self.expect("source list -n main", SOURCE_DISPLAYED_CORRECTLY, + substrs=['Hello world']) + + @skipIf(oslist=["windows"], bugnumber="llvm.org/pr44431") + def test_modify_source_file_while_debugging(self): + """Modify a source file while debugging the executable.""" + self.build() + exe = self.getBuildArtifact("a.out") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, "main-copy.c", self.line, num_expected_locations=1, loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'main-copy.c:%d' % self.line, + 'stop reason = breakpoint']) + + # Display some source code. + self.expect( + "source list -f main-copy.c -l %d" % + self.line, + SOURCE_DISPLAYED_CORRECTLY, + substrs=['Hello world']) + + # The '-b' option shows the line table locations from the debug information + # that indicates valid places to set source level breakpoints. + + # The file to display is implicit in this case. + self.runCmd("source list -l %d -c 3 -b" % self.line) + output = self.res.GetOutput().splitlines()[0] + + # If the breakpoint set command succeeded, we should expect a positive number + # of breakpoints for the current line, i.e., self.line. + import re + m = re.search('^\[(\d+)\].*// Set break point at this line.', output) + if not m: + self.fail("Fail to display source level breakpoints") + self.assertTrue(int(m.group(1)) > 0) + + # Read the main.c file content. + with io.open(self.file, 'r', newline='\n') as f: + original_content = f.read() + if self.TraceOn(): + print("original content:", original_content) + + # Modify the in-memory copy of the original source code. + new_content = original_content.replace('Hello world', 'Hello lldb', 1) + + # Modify the source code file. + with io.open(self.file, 'w', newline='\n') as f: + time.sleep(1) + f.write(new_content) + if self.TraceOn(): + print("new content:", new_content) + print( + "os.path.getmtime() after writing new content:", + os.path.getmtime(self.file)) + + # Display the source code again. We should see the updated line. + self.expect( + "source list -f main-copy.c -l %d" % + self.line, + SOURCE_DISPLAYED_CORRECTLY, + substrs=['Hello lldb']) + + @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr44432") + def test_set_breakpoint_with_absolute_path(self): + self.build() + hidden = self.getBuildArtifact("hidden") + lldbutil.mkdir_p(hidden) + # 'make -C' has resolved current directory to its realpath form. + builddir_real = os.path.realpath(self.getBuildDir()) + hidden_real = os.path.realpath(hidden) + self.runCmd("settings set target.source-map %s %s" % + (builddir_real, hidden_real)) + + exe = self.getBuildArtifact("a.out") + main = os.path.join(builddir_real, "hidden", "main-copy.c") + self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, main, self.line, num_expected_locations=1, loc_exact=False) + + self.runCmd("run", RUN_SUCCEEDED) + + # The stop reason of the thread should be breakpoint. + self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT, + substrs=['stopped', + 'main-copy.c:%d' % self.line, + 'stop reason = breakpoint']) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/hidden/.keep b/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/hidden/.keep new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/hidden/.keep diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/main.c new file mode 100644 index 00000000000..9f62166357c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/source-manager/main.c @@ -0,0 +1,6 @@ +#include <stdio.h> + +int main(int argc, char const *argv[]) { + printf("Hello world.\n"); // Set break point at this line. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/terminal/TestEditline.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/terminal/TestEditline.py new file mode 100644 index 00000000000..8e1652a5041 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/terminal/TestEditline.py @@ -0,0 +1,47 @@ +""" +Test that the lldb editline handling is configured correctly. +""" + + + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +from lldbsuite.test.lldbpexpect import PExpectTest + + +class EditlineTest(PExpectTest): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfAsan + @skipIfEditlineSupportMissing + def test_left_right_arrow(self): + """Test that ctrl+left/right arrow navigates words correctly. + + Note: just sending escape characters to pexpect and checking the buffer + doesn't work well, so we run real commands. We want to type + "help command" while exercising word-navigation, so type it as below, + where [] indicates cursor position. + + 1. Send "el rint" -> "el rint[]" + 2. Ctrl+left once -> "el []rint" + 3. Send "p" -> "el p[]rint" + 4. Ctrl+left twice -> "[]el print" + 5. Send "h" -> "h[]el print" + 6. Ctrl+right -> "hel[] print" + 7. Send "p" -> "help print" + """ + self.launch() + + escape_pairs = [ + ("\x1b[1;5D", "\x1b[1;5C"), + ("\x1b[5D", "\x1b[5C"), + ("\x1b\x1b[D", "\x1b\x1b[C"), + ] + for (l_escape, r_escape) in escape_pairs: + self.expect("el rint{L}p{L}{L}h{R}p".format( + L=l_escape, R=r_escape), substrs=["Syntax: print"]) + + self.quit() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py new file mode 100644 index 00000000000..e994508911b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py @@ -0,0 +1,114 @@ +""" +Test that 'stty -a' displays the same output before and after running the lldb command. +""" + +from __future__ import print_function + + +import lldb +import six +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestSTTYBeforeAndAfter(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + @classmethod + def classCleanup(cls): + """Cleanup the test byproducts.""" + cls.RemoveTempFile("child_send1.txt") + cls.RemoveTempFile("child_read1.txt") + cls.RemoveTempFile("child_send2.txt") + cls.RemoveTempFile("child_read2.txt") + + @expectedFailureAll( + hostoslist=["windows"], + bugnumber="llvm.org/pr22274: need a pexpect replacement for windows") + @no_debug_info_test + def test_stty_dash_a_before_and_afetr_invoking_lldb_command(self): + """Test that 'stty -a' displays the same output before and after running the lldb command.""" + import pexpect + if not which('expect'): + self.skipTest( + "The 'expect' program cannot be located, skip the test") + + # The expect prompt. + expect_prompt = "expect[0-9.]+> " + # The default lldb prompt. + lldb_prompt = "(lldb) " + + # So that the child gets torn down after the test. + import sys + if sys.version_info.major == 3: + self.child = pexpect.spawnu('expect') + else: + self.child = pexpect.spawn('expect') + child = self.child + + child.expect(expect_prompt) + child.setecho(True) + if self.TraceOn(): + child.logfile = sys.stdout + + if self.platformIsDarwin(): + child.sendline('set env(TERM) xterm') + else: + child.sendline('set env(TERM) vt100') + child.expect(expect_prompt) + child.sendline('puts $env(TERM)') + child.expect(expect_prompt) + + # Turn on loggings for input/output to/from the child. + child.logfile_send = child_send1 = six.StringIO() + child.logfile_read = child_read1 = six.StringIO() + child.sendline('stty -a') + child.expect(expect_prompt) + + # Now that the stage1 logging is done, restore logfile to None to + # stop further logging. + child.logfile_send = None + child.logfile_read = None + + # Invoke the lldb command. + child.sendline(lldbtest_config.lldbExec) + child.expect_exact(lldb_prompt) + + # Immediately quit. + child.sendline('quit') + child.expect(expect_prompt) + + child.logfile_send = child_send2 = six.StringIO() + child.logfile_read = child_read2 = six.StringIO() + child.sendline('stty -a') + child.expect(expect_prompt) + + child.sendline('exit') + + # Now that the stage2 logging is done, restore logfile to None to + # stop further logging. + child.logfile_send = None + child.logfile_read = None + + if self.TraceOn(): + print("\n\nContents of child_send1:") + print(child_send1.getvalue()) + print("\n\nContents of child_read1:") + print(child_read1.getvalue()) + print("\n\nContents of child_send2:") + print(child_send2.getvalue()) + print("\n\nContents of child_read2:") + print(child_read2.getvalue()) + + stty_output1_lines = child_read1.getvalue().splitlines() + stty_output2_lines = child_read2.getvalue().splitlines() + zipped = list(zip(stty_output1_lines, stty_output2_lines)) + for tuple in zipped: + if self.TraceOn(): + print("tuple->%s" % str(tuple)) + # Every line should compare equal until the first blank line. + if len(tuple[0]) == 0: + break + self.assertTrue(tuple[0] == tuple[1]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_categories.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_categories.py new file mode 100644 index 00000000000..05ce2a15d84 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_categories.py @@ -0,0 +1,90 @@ +""" +Provides definitions for various lldb test categories +""" + +from __future__ import absolute_import +from __future__ import print_function + +# System modules +import sys + +# Third-party modules + +# LLDB modules +from lldbsuite.support import gmodules + + +debug_info_categories = [ + 'dwarf', 'dwo', 'dsym', 'gmodules' +] + +all_categories = { + 'dataformatters': 'Tests related to the type command and the data formatters subsystem', + 'dwarf': 'Tests that can be run with DWARF debug information', + 'dwo': 'Tests that can be run with DWO debug information', + 'dsym': 'Tests that can be run with DSYM debug information', + 'gmodules': 'Tests that can be run with -gmodules debug information', + 'expression': 'Tests related to the expression parser', + 'libc++': 'Test for libc++ data formatters', + 'libstdcxx': 'Test for libstdcxx data formatters', + 'objc': 'Tests related to the Objective-C programming language support', + 'pyapi': 'Tests related to the Python API', + 'basic_process': 'Basic process execution sniff tests.', + 'cmdline': 'Tests related to the LLDB command-line interface', + 'dyntype': 'Tests related to dynamic type support', + 'stresstest': 'Tests related to stressing lldb limits', + 'flakey': 'Flakey test cases, i.e. tests that do not reliably pass at each execution', + 'darwin-log': 'Darwin log tests', + 'watchpoint': 'Watchpoint-related tests', + 'lldb-vscode': 'Visual Studio Code debug adaptor tests', +} + + +def unique_string_match(yourentry, list): + candidate = None + for item in list: + if not item.startswith(yourentry): + continue + if candidate: + return None + candidate = item + return candidate + + +def is_supported_on_platform(category, platform, compiler_path): + if category == "dwo": + # -gsplit-dwarf is not implemented by clang on Windows. + return platform in ["linux", "freebsd"] + elif category == "dsym": + return platform in ["darwin", "macosx", "ios", "watchos", "tvos", "bridgeos"] + elif category == "gmodules": + # First, check to see if the platform can even support gmodules. + if platform not in ["freebsd", "darwin", "macosx", "ios", "watchos", "tvos", "bridgeos"]: + return False + return gmodules.is_compiler_clang_with_gmodules(compiler_path) + return True + + +def validate(categories, exact_match): + """ + For each category in categories, ensure that it's a valid category (if exact_match is false, + unique prefixes are also accepted). If a category is invalid, print a message and quit. + If all categories are valid, return the list of categories. Prefixes are expanded in the + returned list. + """ + result = [] + for category in categories: + origCategory = category + if category not in all_categories and not exact_match: + category = unique_string_match(category, all_categories) + if (category not in all_categories) or category is None: + print( + "fatal error: category '" + + origCategory + + "' is not a valid category") + print("if you have added a new category, please edit test_categories.py, adding your new category to all_categories") + print("else, please specify one or more of the following: " + + str(list(all_categories.keys()))) + sys.exit(1) + result.append(category) + return result diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_result.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_result.py new file mode 100644 index 00000000000..7e13e09d9bf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_result.py @@ -0,0 +1,320 @@ +""" +Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +See https://llvm.org/LICENSE.txt for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +Provides the LLDBTestResult class, which holds information about progress +and results of a single test run. +""" + +# System modules +import os + +# Third-party modules +import unittest2 + +# LLDB Modules +from . import configuration +from lldbsuite.test_event.event_builder import EventBuilder +from lldbsuite.test_event import build_exception + + +class LLDBTestResult(unittest2.TextTestResult): + """ + Enforce a singleton pattern to allow introspection of test progress. + + Overwrite addError(), addFailure(), and addExpectedFailure() methods + to enable each test instance to track its failure/error status. It + is used in the LLDB test framework to emit detailed trace messages + to a log file for easier human inspection of test failures/errors. + """ + __singleton__ = None + __ignore_singleton__ = False + + @staticmethod + def getTerminalSize(): + import os + env = os.environ + + def ioctl_GWINSZ(fd): + try: + import fcntl + import termios + import struct + cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, + '1234')) + except: + return + return cr + cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) + if not cr: + try: + fd = os.open(os.ctermid(), os.O_RDONLY) + cr = ioctl_GWINSZ(fd) + os.close(fd) + except: + pass + if not cr: + cr = (env.get('LINES', 25), env.get('COLUMNS', 80)) + return int(cr[1]), int(cr[0]) + + def __init__(self, *args): + if not LLDBTestResult.__ignore_singleton__ and LLDBTestResult.__singleton__: + raise Exception("LLDBTestResult instantiated more than once") + super(LLDBTestResult, self).__init__(*args) + LLDBTestResult.__singleton__ = self + # Now put this singleton into the lldb module namespace. + configuration.test_result = self + # Computes the format string for displaying the counter. + counterWidth = len(str(configuration.suite.countTestCases())) + self.fmt = "%" + str(counterWidth) + "d: " + self.indentation = ' ' * (counterWidth + 2) + # This counts from 1 .. suite.countTestCases(). + self.counter = 0 + (width, height) = LLDBTestResult.getTerminalSize() + self.results_formatter = configuration.results_formatter_object + + def _config_string(self, test): + compiler = getattr(test, "getCompiler", None) + arch = getattr(test, "getArchitecture", None) + return "%s-%s" % (compiler() if compiler else "", + arch() if arch else "") + + def _exc_info_to_string(self, err, test): + """Overrides superclass TestResult's method in order to append + our test config info string to the exception info string.""" + if hasattr(test, "getArchitecture") and hasattr(test, "getCompiler"): + return '%sConfig=%s-%s' % (super(LLDBTestResult, + self)._exc_info_to_string(err, + test), + test.getArchitecture(), + test.getCompiler()) + else: + return super(LLDBTestResult, self)._exc_info_to_string(err, test) + + def getDescription(self, test): + doc_first_line = test.shortDescription() + if self.descriptions and doc_first_line: + return '\n'.join((str(test), self.indentation + doc_first_line)) + else: + return str(test) + + def _getTestPath(self, test): + # Use test.test_filename if the test was created with + # lldbinline.MakeInlineTest(). + if test is None: + return "" + elif hasattr(test, "test_filename"): + return test.test_filename + else: + import inspect + return inspect.getsourcefile(test.__class__) + + def _getFileBasedCategories(self, test): + """ + Returns the list of categories to which this test case belongs by + collecting values of ".categories" files. We start at the folder the test is in + and traverse the hierarchy upwards until the test-suite root directory. + """ + start_path = self._getTestPath(test) + + import os.path + folder = os.path.dirname(start_path) + + from lldbsuite import lldb_test_root as test_root + if test_root != os.path.commonprefix([folder, test_root]): + raise Exception("The test file %s is outside the test root directory" % start_path) + + categories = set() + while not os.path.samefile(folder, test_root): + categories_file_name = os.path.join(folder, ".categories") + if os.path.exists(categories_file_name): + categories_file = open(categories_file_name, 'r') + categories_str = categories_file.readline().strip() + categories_file.close() + categories.update(categories_str.split(',')) + folder = os.path.dirname(folder) + + return list(categories) + + def getCategoriesForTest(self, test): + """ + Gets all the categories for the currently running test method in test case + """ + test_categories = [] + test_method = getattr(test, test._testMethodName) + if test_method is not None and hasattr(test_method, "categories"): + test_categories.extend(test_method.categories) + + test_categories.extend(self._getFileBasedCategories(test)) + + return test_categories + + def hardMarkAsSkipped(self, test): + getattr(test, test._testMethodName).__func__.__unittest_skip__ = True + getattr( + test, + test._testMethodName).__func__.__unittest_skip_why__ = "test case does not fall in any category of interest for this run" + + def checkExclusion(self, exclusion_list, name): + if exclusion_list: + import re + for item in exclusion_list: + if re.search(item, name): + return True + return False + + def checkCategoryExclusion(self, exclusion_list, test): + return not set(exclusion_list).isdisjoint( + self.getCategoriesForTest(test)) + + def startTest(self, test): + if configuration.shouldSkipBecauseOfCategories( + self.getCategoriesForTest(test)): + self.hardMarkAsSkipped(test) + if self.checkExclusion( + configuration.skip_tests, test.id()): + self.hardMarkAsSkipped(test) + + self.counter += 1 + test.test_number = self.counter + if self.showAll: + self.stream.write(self.fmt % self.counter) + super(LLDBTestResult, self).startTest(test) + if self.results_formatter: + self.results_formatter.handle_event( + EventBuilder.event_for_start(test)) + + def addSuccess(self, test): + if (self.checkExclusion( + configuration.xfail_tests, test.id()) or + self.checkCategoryExclusion( + configuration.xfail_categories, test)): + self.addUnexpectedSuccess(test, None) + return + + super(LLDBTestResult, self).addSuccess(test) + self.stream.write( + "PASS: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) + if self.results_formatter: + self.results_formatter.handle_event( + EventBuilder.event_for_success(test)) + + def _isBuildError(self, err_tuple): + exception = err_tuple[1] + return isinstance(exception, build_exception.BuildError) + + def _saveBuildErrorTuple(self, test, err): + # Adjust the error description so it prints the build command and build error + # rather than an uninformative Python backtrace. + build_error = err[1] + error_description = "{}\nTest Directory:\n{}".format( + str(build_error), + os.path.dirname(self._getTestPath(test))) + self.errors.append((test, error_description)) + self._mirrorOutput = True + + def addError(self, test, err): + configuration.sdir_has_content = True + if self._isBuildError(err): + self._saveBuildErrorTuple(test, err) + else: + super(LLDBTestResult, self).addError(test, err) + + method = getattr(test, "markError", None) + if method: + method() + self.stream.write( + "FAIL: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) + if self.results_formatter: + # Handle build errors as a separate event type + if self._isBuildError(err): + error_event = EventBuilder.event_for_build_error(test, err) + else: + error_event = EventBuilder.event_for_error(test, err) + self.results_formatter.handle_event(error_event) + + def addCleanupError(self, test, err): + configuration.sdir_has_content = True + super(LLDBTestResult, self).addCleanupError(test, err) + method = getattr(test, "markCleanupError", None) + if method: + method() + self.stream.write( + "CLEANUP ERROR: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) + if self.results_formatter: + self.results_formatter.handle_event( + EventBuilder.event_for_cleanup_error( + test, err)) + + def addFailure(self, test, err): + if (self.checkExclusion( + configuration.xfail_tests, test.id()) or + self.checkCategoryExclusion( + configuration.xfail_categories, test)): + self.addExpectedFailure(test, err, None) + return + + configuration.sdir_has_content = True + super(LLDBTestResult, self).addFailure(test, err) + method = getattr(test, "markFailure", None) + if method: + method() + self.stream.write( + "FAIL: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) + if configuration.use_categories: + test_categories = self.getCategoriesForTest(test) + for category in test_categories: + if category in configuration.failures_per_category: + configuration.failures_per_category[ + category] = configuration.failures_per_category[category] + 1 + else: + configuration.failures_per_category[category] = 1 + if self.results_formatter: + self.results_formatter.handle_event( + EventBuilder.event_for_failure(test, err)) + + def addExpectedFailure(self, test, err, bugnumber): + configuration.sdir_has_content = True + super(LLDBTestResult, self).addExpectedFailure(test, err, bugnumber) + method = getattr(test, "markExpectedFailure", None) + if method: + method(err, bugnumber) + self.stream.write( + "XFAIL: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) + if self.results_formatter: + self.results_formatter.handle_event( + EventBuilder.event_for_expected_failure( + test, err, bugnumber)) + + def addSkip(self, test, reason): + configuration.sdir_has_content = True + super(LLDBTestResult, self).addSkip(test, reason) + method = getattr(test, "markSkippedTest", None) + if method: + method() + self.stream.write( + "UNSUPPORTED: LLDB (%s) :: %s (%s) \n" % + (self._config_string(test), str(test), reason)) + if self.results_formatter: + self.results_formatter.handle_event( + EventBuilder.event_for_skip(test, reason)) + + def addUnexpectedSuccess(self, test, bugnumber): + configuration.sdir_has_content = True + super(LLDBTestResult, self).addUnexpectedSuccess(test, bugnumber) + method = getattr(test, "markUnexpectedSuccess", None) + if method: + method(bugnumber) + self.stream.write( + "XPASS: LLDB (%s) :: %s\n" % + (self._config_string(test), str(test))) + if self.results_formatter: + self.results_formatter.handle_event( + EventBuilder.event_for_unexpected_success( + test, bugnumber)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/README.txt b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/README.txt new file mode 100644 index 00000000000..bb40870e796 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/README.txt @@ -0,0 +1,5 @@ +This directory contains source and tests for the lldb test runner +architecture. This directory is not for lldb python tests. It +is the test runner. The tests under this diretory are test-runner +tests (i.e. tests that verify the test runner itself runs properly). + diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/__init__.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/__init__.py new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/__init__.py diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py new file mode 100644 index 00000000000..687f1058a11 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/process_control.py @@ -0,0 +1,737 @@ +""" +Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +See https://llvm.org/LICENSE.txt for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +Provides classes used by the test results reporting infrastructure +within the LLDB test suite. + + +This module provides process-management support for the LLDB test +running infrastructure. +""" + +# System imports +import os +import re +import signal +import subprocess +import sys +import threading + + +class CommunicatorThread(threading.Thread): + """Provides a thread class that communicates with a subprocess.""" + + def __init__(self, process, event, output_file): + super(CommunicatorThread, self).__init__() + # Don't let this thread prevent shutdown. + self.daemon = True + self.process = process + self.pid = process.pid + self.event = event + self.output_file = output_file + self.output = None + + def run(self): + try: + # Communicate with the child process. + # This will not complete until the child process terminates. + self.output = self.process.communicate() + except Exception as exception: # pylint: disable=broad-except + if self.output_file: + self.output_file.write( + "exception while using communicate() for pid: {}\n".format( + exception)) + finally: + # Signal that the thread's run is complete. + self.event.set() + + +# Provides a regular expression for matching gtimeout-based durations. +TIMEOUT_REGEX = re.compile(r"(^\d+)([smhd])?$") + + +def timeout_to_seconds(timeout): + """Converts timeout/gtimeout timeout values into seconds. + + @param timeout a timeout in the form of xm representing x minutes. + + @return None if timeout is None, or the number of seconds as a float + if a valid timeout format was specified. + """ + if timeout is None: + return None + else: + match = TIMEOUT_REGEX.match(timeout) + if match: + value = float(match.group(1)) + units = match.group(2) + if units is None: + # default is seconds. No conversion necessary. + return value + elif units == 's': + # Seconds. No conversion necessary. + return value + elif units == 'm': + # Value is in minutes. + return 60.0 * value + elif units == 'h': + # Value is in hours. + return (60.0 * 60.0) * value + elif units == 'd': + # Value is in days. + return 24 * (60.0 * 60.0) * value + else: + raise Exception("unexpected units value '{}'".format(units)) + else: + raise Exception("could not parse TIMEOUT spec '{}'".format( + timeout)) + + +class ProcessHelper(object): + """Provides an interface for accessing process-related functionality. + + This class provides a factory method that gives the caller a + platform-specific implementation instance of the class. + + Clients of the class should stick to the methods provided in this + base class. + + \see ProcessHelper.process_helper() + """ + + def __init__(self): + super(ProcessHelper, self).__init__() + + @classmethod + def process_helper(cls): + """Returns a platform-specific ProcessHelper instance. + @return a ProcessHelper instance that does the right thing for + the current platform. + """ + + # If you add a new platform, create an instance here and + # return it. + if os.name == "nt": + return WindowsProcessHelper() + else: + # For all POSIX-like systems. + return UnixProcessHelper() + + def create_piped_process(self, command, new_process_group=True): + # pylint: disable=no-self-use,unused-argument + # As expected. We want derived classes to implement this. + """Creates a subprocess.Popen-based class with I/O piped to the parent. + + @param command the command line list as would be passed to + subprocess.Popen(). Use the list form rather than the string form. + + @param new_process_group indicates if the caller wants the + process to be created in its own process group. Each OS handles + this concept differently. It provides a level of isolation and + can simplify or enable terminating the process tree properly. + + @return a subprocess.Popen-like object. + """ + raise Exception("derived class must implement") + + def supports_soft_terminate(self): + # pylint: disable=no-self-use + # As expected. We want derived classes to implement this. + """Indicates if the platform supports soft termination. + + Soft termination is the concept of a terminate mechanism that + allows the target process to shut down nicely, but with the + catch that the process might choose to ignore it. + + Platform supporter note: only mark soft terminate as supported + if the target process has some way to evade the soft terminate + request; otherwise, just support the hard terminate method. + + @return True if the platform supports a soft terminate mechanism. + """ + # By default, we do not support a soft terminate mechanism. + return False + + def soft_terminate(self, popen_process, log_file=None, want_core=True): + # pylint: disable=no-self-use,unused-argument + # As expected. We want derived classes to implement this. + """Attempts to terminate the process in a polite way. + + This terminate method is intended to give the child process a + chance to clean up and exit on its own, possibly with a request + to drop a core file or equivalent (i.e. [mini-]crashdump, crashlog, + etc.) If new_process_group was set in the process creation method + and the platform supports it, this terminate call will attempt to + kill the whole process tree rooted in this child process. + + @param popen_process the subprocess.Popen-like object returned + by one of the process-creation methods of this class. + + @param log_file file-like object used to emit error-related + logging info. May be None if no error-related info is desired. + + @param want_core True if the caller would like to get a core + dump (or the analogous crash report) from the terminated process. + """ + popen_process.terminate() + + def hard_terminate(self, popen_process, log_file=None): + # pylint: disable=no-self-use,unused-argument + # As expected. We want derived classes to implement this. + """Attempts to terminate the process immediately. + + This terminate method is intended to kill child process in + a manner in which the child process has no ability to block, + and also has no ability to clean up properly. If new_process_group + was specified when creating the process, and if the platform + implementation supports it, this will attempt to kill the + whole process tree rooted in the child process. + + @param popen_process the subprocess.Popen-like object returned + by one of the process-creation methods of this class. + + @param log_file file-like object used to emit error-related + logging info. May be None if no error-related info is desired. + """ + popen_process.kill() + + def was_soft_terminate(self, returncode, with_core): + # pylint: disable=no-self-use,unused-argument + # As expected. We want derived classes to implement this. + """Returns if Popen-like object returncode matches soft terminate. + + @param returncode the returncode from the Popen-like object that + terminated with a given return code. + + @param with_core indicates whether the returncode should match + a core-generating return signal. + + @return True when the returncode represents what the system would + issue when a soft_terminate() with the given with_core arg occurred; + False otherwise. + """ + if not self.supports_soft_terminate(): + # If we don't support soft termination on this platform, + # then this should always be False. + return False + else: + # Once a platform claims to support soft terminate, it + # needs to be able to identify it by overriding this method. + raise Exception("platform needs to implement") + + def was_hard_terminate(self, returncode): + # pylint: disable=no-self-use,unused-argument + # As expected. We want derived classes to implement this. + """Returns if Popen-like object returncode matches that of a hard + terminate attempt. + + @param returncode the returncode from the Popen-like object that + terminated with a given return code. + + @return True when the returncode represents what the system would + issue when a hard_terminate() occurred; False + otherwise. + """ + raise Exception("platform needs to implement") + + def soft_terminate_signals(self): + # pylint: disable=no-self-use + """Retrieve signal numbers that can be sent to soft terminate. + @return a list of signal numbers that can be sent to soft terminate + a process, or None if not applicable. + """ + return None + + def is_exceptional_exit(self, popen_status): + """Returns whether the program exit status is exceptional. + + Returns whether the return code from a Popen process is exceptional + (e.g. signals on POSIX systems). + + Derived classes should override this if they can detect exceptional + program exit. + + @return True if the given popen_status represents an exceptional + program exit; False otherwise. + """ + return False + + def exceptional_exit_details(self, popen_status): + """Returns the normalized exceptional exit code and a description. + + Given an exceptional exit code, returns the integral value of the + exception (e.g. signal number for POSIX) and a description (e.g. + signal name on POSIX) for the result. + + Derived classes should override this if they can detect exceptional + program exit. + + It is fine to not implement this so long as is_exceptional_exit() + always returns False. + + @return (normalized exception code, symbolic exception description) + """ + raise Exception("exception_exit_details() called on unsupported class") + + +class UnixProcessHelper(ProcessHelper): + """Provides a ProcessHelper for Unix-like operating systems. + + This implementation supports anything that looks Posix-y + (e.g. Darwin, Linux, *BSD, etc.) + """ + + def __init__(self): + super(UnixProcessHelper, self).__init__() + + @classmethod + def _create_new_process_group(cls): + """Creates a new process group for the calling process.""" + os.setpgid(os.getpid(), os.getpid()) + + def create_piped_process(self, command, new_process_group=True): + # Determine what to run after the fork but before the exec. + if new_process_group: + preexec_func = self._create_new_process_group + else: + preexec_func = None + + # Create the process. + process = subprocess.Popen( + command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, # Elicits automatic byte -> string decoding in Py3 + close_fds=True, + preexec_fn=preexec_func) + + # Remember whether we're using process groups for this + # process. + process.using_process_groups = new_process_group + return process + + def supports_soft_terminate(self): + # POSIX does support a soft terminate via: + # * SIGTERM (no core requested) + # * SIGQUIT (core requested if enabled, see ulimit -c) + return True + + @classmethod + def _validate_pre_terminate(cls, popen_process, log_file): + # Validate args. + if popen_process is None: + raise ValueError("popen_process is None") + + # Ensure we have something that looks like a valid process. + if popen_process.pid < 1: + if log_file: + log_file.write("skipping soft_terminate(): no process id") + return False + + # We only do the process liveness check if we're not using + # process groups. With process groups, checking if the main + # inferior process is dead and short circuiting here is no + # good - children of it in the process group could still be + # alive, and they should be killed during a timeout. + if not popen_process.using_process_groups: + # Don't kill if it's already dead. + popen_process.poll() + if popen_process.returncode is not None: + # It has a returncode. It has already stopped. + if log_file: + log_file.write( + "requested to terminate pid {} but it has already " + "terminated, returncode {}".format( + popen_process.pid, popen_process.returncode)) + # Move along... + return False + + # Good to go. + return True + + def _kill_with_signal(self, popen_process, log_file, signum): + # Validate we're ready to terminate this. + if not self._validate_pre_terminate(popen_process, log_file): + return + + # Choose kill mechanism based on whether we're targeting + # a process group or just a process. + try: + if popen_process.using_process_groups: + # if log_file: + # log_file.write( + # "sending signum {} to process group {} now\n".format( + # signum, popen_process.pid)) + os.killpg(popen_process.pid, signum) + else: + # if log_file: + # log_file.write( + # "sending signum {} to process {} now\n".format( + # signum, popen_process.pid)) + os.kill(popen_process.pid, signum) + except OSError as error: + import errno + if error.errno == errno.ESRCH: + # This is okay - failed to find the process. It may be that + # that the timeout pre-kill hook eliminated the process. We'll + # ignore. + pass + else: + raise + + def soft_terminate(self, popen_process, log_file=None, want_core=True): + # Choose signal based on desire for core file. + if want_core: + # SIGQUIT will generate core by default. Can be caught. + signum = signal.SIGQUIT + else: + # SIGTERM is the traditional nice way to kill a process. + # Can be caught, doesn't generate a core. + signum = signal.SIGTERM + + self._kill_with_signal(popen_process, log_file, signum) + + def hard_terminate(self, popen_process, log_file=None): + self._kill_with_signal(popen_process, log_file, signal.SIGKILL) + + def was_soft_terminate(self, returncode, with_core): + if with_core: + return returncode == -signal.SIGQUIT + else: + return returncode == -signal.SIGTERM + + def was_hard_terminate(self, returncode): + return returncode == -signal.SIGKILL + + def soft_terminate_signals(self): + return [signal.SIGQUIT, signal.SIGTERM] + + def is_exceptional_exit(self, popen_status): + return popen_status < 0 + + @classmethod + def _signal_names_by_number(cls): + return dict( + (k, v) for v, k in reversed(sorted(signal.__dict__.items())) + if v.startswith('SIG') and not v.startswith('SIG_')) + + def exceptional_exit_details(self, popen_status): + signo = -popen_status + signal_names_by_number = self._signal_names_by_number() + signal_name = signal_names_by_number.get(signo, "") + return (signo, signal_name) + + +class WindowsProcessHelper(ProcessHelper): + """Provides a Windows implementation of the ProcessHelper class.""" + + def __init__(self): + super(WindowsProcessHelper, self).__init__() + + def create_piped_process(self, command, new_process_group=True): + if new_process_group: + # We need this flag if we want os.kill() to work on the subprocess. + creation_flags = subprocess.CREATE_NEW_PROCESS_GROUP + else: + creation_flags = 0 + + return subprocess.Popen( + command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, # Elicits automatic byte -> string decoding in Py3 + creationflags=creation_flags) + + def was_hard_terminate(self, returncode): + return returncode != 0 + + +class ProcessDriver(object): + """Drives a child process, notifies on important events, and can timeout. + + Clients are expected to derive from this class and override the + on_process_started and on_process_exited methods if they want to + hook either of those. + + This class supports timing out the child process in a platform-agnostic + way. The on_process_exited method is informed if the exit was natural + or if it was due to a timeout. + """ + + def __init__(self, soft_terminate_timeout=10.0): + super(ProcessDriver, self).__init__() + self.process_helper = ProcessHelper.process_helper() + self.pid = None + # Create the synchronization event for notifying when the + # inferior dotest process is complete. + self.done_event = threading.Event() + self.io_thread = None + self.process = None + # Number of seconds to wait for the soft terminate to + # wrap up, before moving to more drastic measures. + # Might want this longer if core dumps are generated and + # take a long time to write out. + self.soft_terminate_timeout = soft_terminate_timeout + # Number of seconds to wait for the hard terminate to + # wrap up, before giving up on the io thread. This should + # be fast. + self.hard_terminate_timeout = 5.0 + self.returncode = None + + # ============================================= + # Methods for subclasses to override if desired. + # ============================================= + + def on_process_started(self): + pass + + def on_process_exited(self, command, output, was_timeout, exit_status): + pass + + def on_timeout_pre_kill(self): + """Called after the timeout interval elapses but before killing it. + + This method is added to enable derived classes the ability to do + something to the process prior to it being killed. For example, + this would be a good spot to run a program that samples the process + to see what it was doing (or not doing). + + Do not attempt to reap the process (i.e. use wait()) in this method. + That will interfere with the kill mechanism and return code processing. + """ + + def write(self, content): + # pylint: disable=no-self-use + # Intended - we want derived classes to be able to override + # this and use any self state they may contain. + sys.stdout.write(content) + + # ============================================================== + # Operations used to drive processes. Clients will want to call + # one of these. + # ============================================================== + + def run_command(self, command): + # Start up the child process and the thread that does the + # communication pump. + self._start_process_and_io_thread(command) + + # Wait indefinitely for the child process to finish + # communicating. This indicates it has closed stdout/stderr + # pipes and is done. + self.io_thread.join() + self.returncode = self.process.wait() + if self.returncode is None: + raise Exception( + "no exit status available for pid {} after the " + " inferior dotest.py should have completed".format( + self.process.pid)) + + # Notify of non-timeout exit. + self.on_process_exited( + command, + self.io_thread.output, + False, + self.returncode) + + def run_command_with_timeout(self, command, timeout, want_core): + # Figure out how many seconds our timeout description is requesting. + timeout_seconds = timeout_to_seconds(timeout) + + # Start up the child process and the thread that does the + # communication pump. + self._start_process_and_io_thread(command) + + self._wait_with_timeout(timeout_seconds, command, want_core) + + # ================ + # Internal details. + # ================ + + def _start_process_and_io_thread(self, command): + # Create the process. + self.process = self.process_helper.create_piped_process(command) + self.pid = self.process.pid + self.on_process_started() + + # Ensure the event is cleared that is used for signaling + # from the communication() thread when communication is + # complete (i.e. the inferior process has finished). + self.done_event.clear() + + self.io_thread = CommunicatorThread( + self.process, self.done_event, self.write) + self.io_thread.start() + + def _attempt_soft_kill(self, want_core): + # The inferior dotest timed out. Attempt to clean it + # with a non-drastic method (so it can clean up properly + # and/or generate a core dump). Often the OS can't guarantee + # that the process will really terminate after this. + self.process_helper.soft_terminate( + self.process, + want_core=want_core, + log_file=self) + + # Now wait up to a certain timeout period for the io thread + # to say that the communication ended. If that wraps up + # within our soft terminate timeout, we're all done here. + self.io_thread.join(self.soft_terminate_timeout) + if not self.io_thread.is_alive(): + # stdout/stderr were closed on the child process side. We + # should be able to wait and reap the child process here. + self.returncode = self.process.wait() + # We terminated, and the done_trying result is n/a + terminated = True + done_trying = None + else: + self.write("soft kill attempt of process {} timed out " + "after {} seconds\n".format( + self.process.pid, self.soft_terminate_timeout)) + terminated = False + done_trying = False + return terminated, done_trying + + def _attempt_hard_kill(self): + # Instruct the process to terminate and really force it to + # happen. Don't give the process a chance to ignore. + self.process_helper.hard_terminate( + self.process, + log_file=self) + + # Reap the child process. This should not hang as the + # hard_kill() mechanism is supposed to really kill it. + # Improvement option: + # If this does ever hang, convert to a self.process.poll() + # loop checking on self.process.returncode until it is not + # None or the timeout occurs. + self.returncode = self.process.wait() + + # Wait a few moments for the io thread to finish... + self.io_thread.join(self.hard_terminate_timeout) + if self.io_thread.is_alive(): + # ... but this is not critical if it doesn't end for some + # reason. + self.write( + "hard kill of process {} timed out after {} seconds waiting " + "for the io thread (ignoring)\n".format( + self.process.pid, self.hard_terminate_timeout)) + + # Set if it terminated. (Set up for optional improvement above). + terminated = self.returncode is not None + # Nothing else to try. + done_trying = True + + return terminated, done_trying + + def _attempt_termination(self, attempt_count, want_core): + if self.process_helper.supports_soft_terminate(): + # When soft termination is supported, we first try to stop + # the process with a soft terminate. Failing that, we try + # the hard terminate option. + if attempt_count == 1: + return self._attempt_soft_kill(want_core) + elif attempt_count == 2: + return self._attempt_hard_kill() + else: + # We don't have anything else to try. + terminated = self.returncode is not None + done_trying = True + return terminated, done_trying + else: + # We only try the hard terminate option when there + # is no soft terminate available. + if attempt_count == 1: + return self._attempt_hard_kill() + else: + # We don't have anything else to try. + terminated = self.returncode is not None + done_trying = True + return terminated, done_trying + + def _wait_with_timeout(self, timeout_seconds, command, want_core): + # Allow up to timeout seconds for the io thread to wrap up. + # If that completes, the child process should be done. + completed_normally = self.done_event.wait(timeout_seconds) + if completed_normally: + # Reap the child process here. + self.returncode = self.process.wait() + else: + + # Allow derived classes to do some work after we detected + # a timeout but before we touch the timed-out process. + self.on_timeout_pre_kill() + + # Prepare to stop the process + process_terminated = completed_normally + terminate_attempt_count = 0 + + # Try as many attempts as we support for trying to shut down + # the child process if it's not already shut down. + while not process_terminated: + terminate_attempt_count += 1 + # Attempt to terminate. + process_terminated, done_trying = self._attempt_termination( + terminate_attempt_count, want_core) + # Check if there's nothing more to try. + if done_trying: + # Break out of our termination attempt loop. + break + + # At this point, we're calling it good. The process + # finished gracefully, was shut down after one or more + # attempts, or we failed but gave it our best effort. + self.on_process_exited( + command, + self.io_thread.output, + not completed_normally, + self.returncode) + + +def patched_init(self, *args, **kwargs): + self.original_init(*args, **kwargs) + # Initialize our condition variable that protects wait()/poll(). + self.wait_condition = threading.Condition() + + +def patched_wait(self, *args, **kwargs): + self.wait_condition.acquire() + try: + result = self.original_wait(*args, **kwargs) + # The process finished. Signal the condition. + self.wait_condition.notify_all() + return result + finally: + self.wait_condition.release() + + +def patched_poll(self, *args, **kwargs): + self.wait_condition.acquire() + try: + result = self.original_poll(*args, **kwargs) + if self.returncode is not None: + # We did complete, and we have the return value. + # Signal the event to indicate we're done. + self.wait_condition.notify_all() + return result + finally: + self.wait_condition.release() + + +def patch_up_subprocess_popen(): + subprocess.Popen.original_init = subprocess.Popen.__init__ + subprocess.Popen.__init__ = patched_init + + subprocess.Popen.original_wait = subprocess.Popen.wait + subprocess.Popen.wait = patched_wait + + subprocess.Popen.original_poll = subprocess.Popen.poll + subprocess.Popen.poll = patched_poll + +# Replace key subprocess.Popen() threading-unprotected methods with +# threading-protected versions. +patch_up_subprocess_popen() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/test/__init__.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/test/__init__.py new file mode 100644 index 00000000000..e69de29bb2d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/test/__init__.py diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/test/inferior.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/test/inferior.py new file mode 100755 index 00000000000..4207bac300f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/test/inferior.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python +"""Inferior program used by process control tests.""" + +from __future__ import print_function + +import argparse +import datetime +import signal +import subprocess +import sys +import time + + +def parse_args(command_line): + """Parses the command line arguments given to it. + + @param command_line a list of command line arguments to be parsed. + + @return the argparse options dictionary. + """ + parser = argparse.ArgumentParser() + parser.add_argument( + "--ignore-signal", + "-i", + dest="ignore_signals", + metavar="SIGNUM", + action="append", + type=int, + default=[], + help="ignore the given signal number (if possible)") + parser.add_argument( + "--launch-child-share-handles", + action="store_true", + help=("launch a child inferior.py that shares stdout/stderr/stdio and " + "never returns")) + parser.add_argument( + "--never-return", + action="store_true", + help="run in an infinite loop, never return") + parser.add_argument( + "--return-code", + "-r", + type=int, + default=0, + help="specify the return code for the inferior upon exit") + parser.add_argument( + "--sleep", + "-s", + metavar="SECONDS", + dest="sleep_seconds", + type=float, + help="sleep for SECONDS seconds before returning") + parser.add_argument( + "--verbose", "-v", action="store_true", + help="log verbose operation details to stdout") + return parser.parse_args(command_line) + + +def handle_ignore_signals(options, signals): + """Ignores any signals provided to it. + + @param options the command line options parsed by the program. + General used to check flags for things like verbosity. + + @param signals the list of signals to ignore. Can be None or zero-length. + Entries should be type int. + """ + if signals is None: + return + + for signum in signals: + if options.verbose: + print("disabling signum {}".format(signum)) + signal.signal(signum, signal.SIG_IGN) + + +def handle_sleep(options, sleep_seconds): + """Sleeps the number of seconds specified, restarting as needed. + + @param options the command line options parsed by the program. + General used to check flags for things like verbosity. + + @param sleep_seconds the number of seconds to sleep. If None + or <= 0, no sleeping will occur. + """ + if sleep_seconds is None: + return + + if sleep_seconds <= 0: + return + + end_time = datetime.datetime.now() + datetime.timedelta(0, sleep_seconds) + if options.verbose: + print("sleep end time: {}".format(end_time)) + + # Do sleep in a loop: signals can interrupt. + while datetime.datetime.now() < end_time: + # We'll wrap this in a try/catch so we don't encounter + # a race if a signal (ignored) knocks us out of this + # loop and causes us to return. + try: + sleep_interval = end_time - datetime.datetime.now() + sleep_seconds = sleep_interval.total_seconds() + if sleep_seconds > 0: + time.sleep(sleep_seconds) + except: # pylint: disable=bare-except + pass + + +def handle_launch_children(options): + if options.launch_child_share_handles: + # Launch the child, share our file handles. + # We won't bother reaping it since it will likely outlive us. + subprocess.Popen([sys.executable, __file__, "--never-return"]) + + +def handle_never_return(options): + if not options.never_return: + return + + # Loop forever. + while True: + try: + time.sleep(10) + except: # pylint: disable=bare-except + # Ignore + pass + + +def main(command_line): + """Drives the main operation of the inferior test program. + + @param command_line the command line options to process. + + @return the exit value (program return code) for the process. + """ + options = parse_args(command_line) + handle_ignore_signals(options, options.ignore_signals) + handle_launch_children(options) + handle_sleep(options, options.sleep_seconds) + handle_never_return(options) + + return options.return_code + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/test/test_process_control.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/test/test_process_control.py new file mode 100755 index 00000000000..b3b5aee68f0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/test_runner/test/test_process_control.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python +""" +Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +See https://llvm.org/LICENSE.txt for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +Provides classes used by the test results reporting infrastructure +within the LLDB test suite. + + +Tests the process_control module. +""" + + +# System imports. +import os +import os.path +import unittest +import sys +import threading + +# Our imports. +from test_runner import process_control + + +class TestInferiorDriver(process_control.ProcessDriver): + + def __init__(self, soft_terminate_timeout=None): + super(TestInferiorDriver, self).__init__( + soft_terminate_timeout=soft_terminate_timeout) + self.started_event = threading.Event() + self.started_event.clear() + + self.completed_event = threading.Event() + self.completed_event.clear() + + self.was_timeout = False + self.returncode = None + self.output = None + + def write(self, content): + # We'll swallow this to keep tests non-noisy. + # Uncomment the following line if you want to see it. + # sys.stdout.write(content) + pass + + def on_process_started(self): + self.started_event.set() + + def on_process_exited(self, command, output, was_timeout, exit_status): + self.returncode = exit_status + self.was_timeout = was_timeout + self.output = output + self.returncode = exit_status + self.completed_event.set() + + +class ProcessControlTests(unittest.TestCase): + + @classmethod + def _suppress_soft_terminate(cls, command): + # Do the right thing for your platform here. + # Right now only POSIX-y systems are reporting + # soft terminate support, so this is set up for + # those. + helper = process_control.ProcessHelper.process_helper() + signals = helper.soft_terminate_signals() + if signals is not None: + for signum in helper.soft_terminate_signals(): + command.extend(["--ignore-signal", str(signum)]) + + @classmethod + def inferior_command( + cls, + ignore_soft_terminate=False, + options=None): + + # Base command. + script_name = "{}/inferior.py".format(os.path.dirname(__file__)) + if not os.path.exists(script_name): + raise Exception( + "test inferior python script not found: {}".format(script_name)) + command = ([sys.executable, script_name]) + + if ignore_soft_terminate: + cls._suppress_soft_terminate(command) + + # Handle options as string or list. + if isinstance(options, str): + command.extend(options.split()) + elif isinstance(options, list): + command.extend(options) + + # Return full command. + return command + + +class ProcessControlNoTimeoutTests(ProcessControlTests): + """Tests the process_control module.""" + + def test_run_completes(self): + """Test that running completes and gets expected stdout/stderr.""" + driver = TestInferiorDriver() + driver.run_command(self.inferior_command()) + self.assertTrue( + driver.completed_event.wait(5), "process failed to complete") + self.assertEqual(driver.returncode, 0, "return code does not match") + + def test_run_completes_with_code(self): + """Test that running completes and gets expected stdout/stderr.""" + driver = TestInferiorDriver() + driver.run_command(self.inferior_command(options="-r10")) + self.assertTrue( + driver.completed_event.wait(5), "process failed to complete") + self.assertEqual(driver.returncode, 10, "return code does not match") + + +class ProcessControlTimeoutTests(ProcessControlTests): + + def test_run_completes(self): + """Test that running completes and gets expected return code.""" + driver = TestInferiorDriver() + timeout_seconds = 5 + driver.run_command_with_timeout( + self.inferior_command(), + "{}s".format(timeout_seconds), + False) + self.assertTrue( + driver.completed_event.wait(2 * timeout_seconds), + "process failed to complete") + self.assertEqual(driver.returncode, 0) + + def _soft_terminate_works(self, with_core): + # Skip this test if the platform doesn't support soft ti + helper = process_control.ProcessHelper.process_helper() + if not helper.supports_soft_terminate(): + self.skipTest("soft terminate not supported by platform") + + driver = TestInferiorDriver() + timeout_seconds = 5 + + driver.run_command_with_timeout( + # Sleep twice as long as the timeout interval. This + # should force a timeout. + self.inferior_command( + options="--sleep {}".format(timeout_seconds * 2)), + "{}s".format(timeout_seconds), + with_core) + + # We should complete, albeit with a timeout. + self.assertTrue( + driver.completed_event.wait(2 * timeout_seconds), + "process failed to complete") + + # Ensure we received a timeout. + self.assertTrue(driver.was_timeout, "expected to end with a timeout") + + self.assertTrue( + helper.was_soft_terminate(driver.returncode, with_core), + ("timeout didn't return expected returncode " + "for soft terminate with core: {}").format(driver.returncode)) + + def test_soft_terminate_works_core(self): + """Driver uses soft terminate (with core request) when process times out. + """ + self._soft_terminate_works(True) + + def test_soft_terminate_works_no_core(self): + """Driver uses soft terminate (no core request) when process times out. + """ + self._soft_terminate_works(False) + + def test_hard_terminate_works(self): + """Driver falls back to hard terminate when soft terminate is ignored. + """ + + driver = TestInferiorDriver(soft_terminate_timeout=2.0) + timeout_seconds = 1 + + driver.run_command_with_timeout( + # Sleep much longer than the timeout interval,forcing a + # timeout. Do whatever is needed to have the inferior + # ignore soft terminate calls. + self.inferior_command( + ignore_soft_terminate=True, + options="--never-return"), + "{}s".format(timeout_seconds), + True) + + # We should complete, albeit with a timeout. + self.assertTrue( + driver.completed_event.wait(60), + "process failed to complete") + + # Ensure we received a timeout. + self.assertTrue(driver.was_timeout, "expected to end with a timeout") + + helper = process_control.ProcessHelper.process_helper() + self.assertTrue( + helper.was_hard_terminate(driver.returncode), + ("timeout didn't return expected returncode " + "for hard teriminate: {} ({})").format( + driver.returncode, + driver.output)) + + def test_inferior_exits_with_live_child_shared_handles(self): + """inferior exit detected when inferior children are live with shared + stdout/stderr handles. + """ + # Requires review D13362 or equivalent to be implemented. + self.skipTest("http://reviews.llvm.org/D13362") + + driver = TestInferiorDriver() + + # Create the inferior (I1), and instruct it to create a child (C1) + # that shares the stdout/stderr handles with the inferior. + # C1 will then loop forever. + driver.run_command_with_timeout( + self.inferior_command( + options="--launch-child-share-handles --return-code 3"), + "5s", + False) + + # We should complete without a timetout. I1 should end + # immediately after launching C1. + self.assertTrue( + driver.completed_event.wait(5), + "process failed to complete") + + # Ensure we didn't receive a timeout. + self.assertFalse( + driver.was_timeout, "inferior should have completed normally") + + self.assertEqual( + driver.returncode, 3, + "expected inferior process to end with expected returncode") + + +if __name__ == "__main__": + unittest.main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/.clang-format b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/.clang-format new file mode 100644 index 00000000000..9b3aa8b7213 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/.clang-format @@ -0,0 +1 @@ +BasedOnStyle: LLVM diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/Makefile new file mode 100644 index 00000000000..0c441eda98b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/Makefile @@ -0,0 +1,6 @@ +CFLAGS_EXTRAS := -D__STDC_LIMIT_MACROS -D__STDC_FORMAT_MACROS +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp +MAKE_DSYM :=NO + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestAppleSimulatorOSType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestAppleSimulatorOSType.py new file mode 100644 index 00000000000..5ea55c3f644 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestAppleSimulatorOSType.py @@ -0,0 +1,122 @@ + + +import gdbremote_testcase +import lldbgdbserverutils +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +import json + +class TestAppleSimulatorOSType(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def check_simulator_ostype(self, sdk, platform, arch='x86_64'): + sim_devices_str = subprocess.check_output(['xcrun', 'simctl', 'list', + '-j', 'devices']).decode("utf-8") + sim_devices = json.loads(sim_devices_str)['devices'] + # Find an available simulator for the requested platform + deviceUDID = None + for simulator in sim_devices: + if isinstance(simulator,dict): + runtime = simulator['name'] + devices = simulator['devices'] + else: + runtime = simulator + devices = sim_devices[simulator] + if not platform in runtime.lower(): + continue + for device in devices: + if 'availability' in device and device['availability'] != '(available)': + continue + if 'isAvailable' in device and device['isAvailable'] != True: + continue + deviceUDID = device['udid'] + break + if deviceUDID != None: + break + + # Launch the process using simctl + self.assertIsNotNone(deviceUDID) + exe_name = 'test_simulator_platform_{}'.format(platform) + sdkroot = subprocess.check_output(['xcrun', '--show-sdk-path', '--sdk', + sdk]).decode("utf-8") + self.build(dictionary={ 'EXE': exe_name, 'SDKROOT': sdkroot.strip(), + 'ARCH': arch }) + exe_path = self.getBuildArtifact(exe_name) + sim_launcher = subprocess.Popen(['xcrun', 'simctl', 'spawn', '-s', + deviceUDID, exe_path, + 'print-pid', 'sleep:10'], + stderr=subprocess.PIPE) + # Get the PID from the process output + pid = None + while not pid: + stderr = sim_launcher.stderr.readline().decode("utf-8") + if stderr == '': + continue + m = re.match(r"PID: (.*)", stderr) + self.assertIsNotNone(m) + pid = int(m.group(1)) + + # Launch debug monitor attaching to the simulated process + self.init_debugserver_test() + server = self.connect_to_debug_monitor(attach_pid=pid) + + # Setup packet sequences + self.add_no_ack_remote_stream() + self.add_process_info_collection_packets() + self.test_sequence.add_log_lines( + ["read packet: " + + "$jGetLoadedDynamicLibrariesInfos:{\"fetch_all_solibs\" : true}]#ce", + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "dylib_info_raw"}}], + True) + + # Run the stream + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather process info response + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + + # Check that ostype is correct + self.assertEquals(process_info['ostype'], platform) + + # Now for dylibs + dylib_info_raw = context.get("dylib_info_raw") + dylib_info = json.loads(self.decode_gdbremote_binary(dylib_info_raw)) + images = dylib_info['images'] + + image_info = None + for image in images: + if image['pathname'] != exe_path: + continue + image_info = image + break + + self.assertIsNotNone(image_info) + self.assertEquals(image['min_version_os_name'], platform) + + + @apple_simulator_test('iphone') + @debugserver_test + @skipIfRemote + def test_simulator_ostype_ios(self): + self.check_simulator_ostype(sdk='iphonesimulator', + platform='ios') + + @apple_simulator_test('appletv') + @debugserver_test + @skipIfRemote + def test_simulator_ostype_tvos(self): + self.check_simulator_ostype(sdk='appletvsimulator', + platform='tvos') + + @apple_simulator_test('watch') + @debugserver_test + @skipIfRemote + def test_simulator_ostype_watchos(self): + self.check_simulator_ostype(sdk='watchsimulator', + platform='watchos', arch='i386') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py new file mode 100644 index 00000000000..dbb83d63480 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py @@ -0,0 +1,67 @@ + + +import gdbremote_testcase +import lldbgdbserverutils +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteAttach(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def attach_with_vAttach(self): + # Start the inferior, start the debug monitor, nothing is attached yet. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["sleep:60"]) + self.assertIsNotNone(procs) + + # Make sure the target process has been launched. + inferior = procs.get("inferior") + self.assertIsNotNone(inferior) + self.assertTrue(inferior.pid > 0) + self.assertTrue( + lldbgdbserverutils.process_is_running( + inferior.pid, True)) + + # Add attach packets. + self.test_sequence.add_log_lines([ + # Do the attach. + "read packet: $vAttach;{:x}#00".format(inferior.pid), + # Expect a stop notification from the attach. + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})[^#]*#[0-9a-fA-F]{2}$", + "capture": {1: "stop_signal_hex"}}, + ], True) + self.add_process_info_collection_packets() + + # Run the stream + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather process info response + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + + # Ensure the process id matches what we expected. + pid_text = process_info.get('pid', None) + self.assertIsNotNone(pid_text) + reported_pid = int(pid_text, base=16) + self.assertEqual(reported_pid, inferior.pid) + + @debugserver_test + def test_attach_with_vAttach_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_attach_manually() + self.attach_with_vAttach() + + @expectedFailureNetBSD + @llgs_test + def test_attach_with_vAttach_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_attach_manually() + self.attach_with_vAttach() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py new file mode 100644 index 00000000000..1a3a2b29365 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py @@ -0,0 +1,227 @@ +from __future__ import print_function + + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + AUXV_SUPPORT_FEATURE_NAME = "qXfer:auxv:read" + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def has_auxv_support(self): + inferior_args = ["message:main entered", "sleep:5"] + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) + + # Don't do anything until we match the launched inferior main entry output. + # Then immediately interrupt the process. + # This prevents auxv data being asked for before it's ready and leaves + # us in a stopped state. + self.test_sequence.add_log_lines([ + # Start the inferior... + "read packet: $c#63", + # ... match output.... + {"type": "output_match", "regex": self.maybe_strict_output_regex( + r"message:main entered\r\n")}, + ], True) + # ... then interrupt. + self.add_interrupt_packets() + self.add_qSupported_packets() + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + features = self.parse_qSupported_response(context) + return self.AUXV_SUPPORT_FEATURE_NAME in features and features[ + self.AUXV_SUPPORT_FEATURE_NAME] == "+" + + def get_raw_auxv_data(self): + # Start up llgs and inferior, and check for auxv support. + if not self.has_auxv_support(): + self.skipTest("auxv data not supported") + + # Grab pointer size for target. We'll assume that is equivalent to an unsigned long on the target. + # Auxv is specified in terms of pairs of unsigned longs. + self.reset_test_sequence() + self.add_process_info_collection_packets() + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + proc_info = self.parse_process_info_response(context) + self.assertIsNotNone(proc_info) + self.assertTrue("ptrsize" in proc_info) + word_size = int(proc_info["ptrsize"]) + + OFFSET = 0 + LENGTH = 0x400 + + # Grab the auxv data. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + "read packet: $qXfer:auxv:read::{:x},{:x}:#00".format( + OFFSET, + LENGTH), + { + "direction": "send", + "regex": re.compile( + r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", + re.MULTILINE | re.DOTALL), + "capture": { + 1: "response_type", + 2: "content_raw"}}], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Ensure we end up with all auxv data in one packet. + # FIXME don't assume it all comes back in one packet. + self.assertEqual(context.get("response_type"), "l") + + # Decode binary data. + content_raw = context.get("content_raw") + self.assertIsNotNone(content_raw) + return (word_size, self.decode_gdbremote_binary(content_raw)) + + def supports_auxv(self): + # When non-auxv platforms support llgs, skip the test on platforms + # that don't support auxv. + self.assertTrue(self.has_auxv_support()) + + # + # We skip the "supports_auxv" test on debugserver. The rest of the tests + # appropriately skip the auxv tests if the support flag is not present + # in the qSupported response, so the debugserver test bits are still there + # in case debugserver code one day does have auxv support and thus those + # tests don't get skipped. + # + + @skipIfWindows # no auxv support. + @llgs_test + def test_supports_auxv_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.supports_auxv() + + def auxv_data_is_correct_size(self): + (word_size, auxv_data) = self.get_raw_auxv_data() + self.assertIsNotNone(auxv_data) + + # Ensure auxv data is a multiple of 2*word_size (there should be two + # unsigned long fields per auxv entry). + self.assertEqual(len(auxv_data) % (2 * word_size), 0) + # print("auxv contains {} entries".format(len(auxv_data) / (2*word_size))) + + @debugserver_test + def test_auxv_data_is_correct_size_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.auxv_data_is_correct_size() + + @skipIfWindows + @expectedFailureNetBSD + @llgs_test + def test_auxv_data_is_correct_size_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.auxv_data_is_correct_size() + + def auxv_keys_look_valid(self): + (word_size, auxv_data) = self.get_raw_auxv_data() + self.assertIsNotNone(auxv_data) + + # Grab endian. + self.reset_test_sequence() + self.add_process_info_collection_packets() + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + endian = process_info.get("endian") + self.assertIsNotNone(endian) + + auxv_dict = self.build_auxv_dict(endian, word_size, auxv_data) + self.assertIsNotNone(auxv_dict) + + # Verify keys look reasonable. + for auxv_key in auxv_dict: + self.assertTrue(auxv_key >= 1) + self.assertTrue(auxv_key <= 1000) + # print("auxv dict: {}".format(auxv_dict)) + + @debugserver_test + def test_auxv_keys_look_valid_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.auxv_keys_look_valid() + + @skipIfWindows + @expectedFailureNetBSD + @llgs_test + def test_auxv_keys_look_valid_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.auxv_keys_look_valid() + + def auxv_chunked_reads_work(self): + # Verify that multiple smaller offset,length reads of auxv data + # return the same data as a single larger read. + + # Grab the auxv data with a single large read here. + (word_size, auxv_data) = self.get_raw_auxv_data() + self.assertIsNotNone(auxv_data) + + # Grab endian. + self.reset_test_sequence() + self.add_process_info_collection_packets() + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + endian = process_info.get("endian") + self.assertIsNotNone(endian) + + auxv_dict = self.build_auxv_dict(endian, word_size, auxv_data) + self.assertIsNotNone(auxv_dict) + + iterated_auxv_data = self.read_binary_data_in_chunks( + "qXfer:auxv:read::", 2 * word_size) + self.assertIsNotNone(iterated_auxv_data) + + auxv_dict_iterated = self.build_auxv_dict( + endian, word_size, iterated_auxv_data) + self.assertIsNotNone(auxv_dict_iterated) + + # Verify both types of data collection returned same content. + self.assertEqual(auxv_dict_iterated, auxv_dict) + + @debugserver_test + def test_auxv_chunked_reads_work_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.auxv_chunked_reads_work() + + @skipIfWindows + @expectedFailureNetBSD + @llgs_test + def test_auxv_chunked_reads_work_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.auxv_chunked_reads_work() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExitCode.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExitCode.py new file mode 100644 index 00000000000..24fb0d58b8f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExitCode.py @@ -0,0 +1,126 @@ + +# lldb test suite imports +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import TestBase + +# gdb-remote-specific imports +import lldbgdbserverutils +from gdbremote_testcase import GdbRemoteTestCaseBase + + +class TestGdbRemoteExitCode(GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + FAILED_LAUNCH_CODE = "E08" + + def get_launch_fail_reason(self): + self.reset_test_sequence() + self.test_sequence.add_log_lines( + ["read packet: $qLaunchSuccess#00"], + True) + self.test_sequence.add_log_lines( + [{"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "launch_result"}}], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + return context.get("launch_result")[1:] + + def start_inferior(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + self.add_no_ack_remote_stream() + self.test_sequence.add_log_lines( + ["read packet: %s" % lldbgdbserverutils.build_gdbremote_A_packet( + launch_args)], + True) + self.test_sequence.add_log_lines( + [{"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "A_result"}}], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + launch_result = context.get("A_result") + self.assertIsNotNone(launch_result) + if launch_result == self.FAILED_LAUNCH_CODE: + fail_reason = self.get_launch_fail_reason() + self.fail("failed to launch inferior: " + fail_reason) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_start_inferior_debugserver(self): + self.init_debugserver_test() + self.build() + self.start_inferior() + + @llgs_test + def test_start_inferior_llgs(self): + self.init_llgs_test() + self.build() + self.start_inferior() + + def inferior_exit_0(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.test_sequence.add_log_lines( + ["read packet: $vCont;c#a8", + "send packet: $W00#00"], + True) + + self.expect_gdbremote_sequence() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_inferior_exit_0_debugserver(self): + self.init_debugserver_test() + self.build() + self.inferior_exit_0() + + @llgs_test + def test_inferior_exit_0_llgs(self): + self.init_llgs_test() + self.build() + self.inferior_exit_0() + + def inferior_exit_42(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + RETVAL = 42 + + # build launch args + launch_args += ["retval:%d" % RETVAL] + + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.test_sequence.add_log_lines( + ["read packet: $vCont;c#a8", + "send packet: $W{0:02x}#00".format(RETVAL)], + True) + + self.expect_gdbremote_sequence() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_inferior_exit_42_debugserver(self): + self.init_debugserver_test() + self.build() + self.inferior_exit_42() + + @llgs_test + def test_inferior_exit_42_llgs(self): + self.init_llgs_test() + self.build() + self.inferior_exit_42() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py new file mode 100644 index 00000000000..7d8e28c745c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py @@ -0,0 +1,162 @@ +from __future__ import print_function + + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteExpeditedRegisters( + gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + + def gather_expedited_registers(self): + # Setup the stub and set the gdb remote command stream. + procs = self.prep_debug_monitor_and_inferior(inferior_args=["sleep:2"]) + self.test_sequence.add_log_lines([ + # Start up the inferior. + "read packet: $c#63", + # Immediately tell it to stop. We want to see what it reports. + "read packet: {}".format(chr(3)), + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": {1: "stop_result", + 2: "key_vals_text"}}, + ], True) + + # Run the gdb remote command stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Pull out expedited registers. + key_vals_text = context.get("key_vals_text") + self.assertIsNotNone(key_vals_text) + + expedited_registers = self.extract_registers_from_stop_notification( + key_vals_text) + self.assertIsNotNone(expedited_registers) + + return expedited_registers + + def stop_notification_contains_generic_register( + self, generic_register_name): + # Generate a stop reply, parse out expedited registers from stop + # notification. + expedited_registers = self.gather_expedited_registers() + self.assertIsNotNone(expedited_registers) + self.assertTrue(len(expedited_registers) > 0) + + # Gather target register infos. + reg_infos = self.gather_register_infos() + + # Find the generic register. + reg_info = self.find_generic_register_with_name( + reg_infos, generic_register_name) + self.assertIsNotNone(reg_info) + + # Ensure the expedited registers contained it. + self.assertTrue(reg_info["lldb_register_index"] in expedited_registers) + # print("{} reg_info:{}".format(generic_register_name, reg_info)) + + def stop_notification_contains_any_registers(self): + # Generate a stop reply, parse out expedited registers from stop + # notification. + expedited_registers = self.gather_expedited_registers() + # Verify we have at least one expedited register. + self.assertTrue(len(expedited_registers) > 0) + + @debugserver_test + def test_stop_notification_contains_any_registers_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_any_registers() + + @llgs_test + def test_stop_notification_contains_any_registers_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_any_registers() + + def stop_notification_contains_no_duplicate_registers(self): + # Generate a stop reply, parse out expedited registers from stop + # notification. + expedited_registers = self.gather_expedited_registers() + # Verify no expedited register was specified multiple times. + for (reg_num, value) in list(expedited_registers.items()): + if (isinstance(value, list)) and (len(value) > 0): + self.fail( + "expedited register number {} specified more than once ({} times)".format( + reg_num, len(value))) + + @debugserver_test + def test_stop_notification_contains_no_duplicate_registers_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_no_duplicate_registers() + + @llgs_test + def test_stop_notification_contains_no_duplicate_registers_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_no_duplicate_registers() + + def stop_notification_contains_pc_register(self): + self.stop_notification_contains_generic_register("pc") + + @debugserver_test + def test_stop_notification_contains_pc_register_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_pc_register() + + @llgs_test + def test_stop_notification_contains_pc_register_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_pc_register() + + # powerpc64 has no FP register + @skipIf(triple='^powerpc64') + def stop_notification_contains_fp_register(self): + self.stop_notification_contains_generic_register("fp") + + @debugserver_test + def test_stop_notification_contains_fp_register_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_fp_register() + + @llgs_test + def test_stop_notification_contains_fp_register_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_fp_register() + + def stop_notification_contains_sp_register(self): + self.stop_notification_contains_generic_register("sp") + + @debugserver_test + def test_stop_notification_contains_sp_register_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_sp_register() + + @llgs_test + def test_stop_notification_contains_sp_register_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.stop_notification_contains_sp_register() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteHostInfo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteHostInfo.py new file mode 100644 index 00000000000..832096a0ff5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteHostInfo.py @@ -0,0 +1,132 @@ +from __future__ import print_function + +# lldb test suite imports +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import TestBase + +# gdb-remote-specific imports +import lldbgdbserverutils +from gdbremote_testcase import GdbRemoteTestCaseBase + + +class TestGdbRemoteHostInfo(GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + KNOWN_HOST_INFO_KEYS = set([ + "arch", + "cputype", + "cpusubtype", + "distribution_id", + "endian", + "hostname", + "ostype", + "os_build", + "os_kernel", + "os_version", + "maccatalyst_version", + "ptrsize", + "triple", + "vendor", + "watchpoint_exceptions_received", + "default_packet_timeout", + ]) + + DARWIN_REQUIRED_HOST_INFO_KEYS = set([ + "cputype", + "cpusubtype", + "endian", + "ostype", + "ptrsize", + "vendor", + "watchpoint_exceptions_received" + ]) + + def add_host_info_collection_packets(self): + self.test_sequence.add_log_lines( + ["read packet: $qHostInfo#9b", + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "host_info_raw"}}], + True) + + def parse_host_info_response(self, context): + # Ensure we have a host info response. + self.assertIsNotNone(context) + host_info_raw = context.get("host_info_raw") + self.assertIsNotNone(host_info_raw) + + # Pull out key:value; pairs. + host_info_dict = {match.group(1): match.group(2) + for match in re.finditer(r"([^:]+):([^;]+);", + host_info_raw)} + + import pprint + print("\nqHostInfo response:") + pprint.pprint(host_info_dict) + + # Validate keys are known. + for (key, val) in list(host_info_dict.items()): + self.assertTrue(key in self.KNOWN_HOST_INFO_KEYS, + "unknown qHostInfo key: " + key) + self.assertIsNotNone(val) + + # Return the key:val pairs. + return host_info_dict + + def get_qHostInfo_response(self): + # Launch the debug monitor stub, attaching to the inferior. + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + self.add_no_ack_remote_stream() + + # Request qHostInfo and get response + self.add_host_info_collection_packets() + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Parse qHostInfo response. + host_info = self.parse_host_info_response(context) + self.assertIsNotNone(host_info) + self.assertGreater(len(host_info), 0, "qHostInfo should have returned " + "at least one key:val pair.") + return host_info + + def validate_darwin_minimum_host_info_keys(self, host_info_dict): + self.assertIsNotNone(host_info_dict) + missing_keys = [key for key in self.DARWIN_REQUIRED_HOST_INFO_KEYS + if key not in host_info_dict] + self.assertEquals(0, len(missing_keys), + "qHostInfo is missing the following required " + "keys: " + str(missing_keys)) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @debugserver_test + def test_qHostInfo_returns_at_least_one_key_val_pair_debugserver(self): + self.init_debugserver_test() + self.build() + self.get_qHostInfo_response() + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @llgs_test + def test_qHostInfo_returns_at_least_one_key_val_pair_llgs(self): + self.init_llgs_test() + self.build() + self.get_qHostInfo_response() + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @debugserver_test + def test_qHostInfo_contains_darwin_required_keys_debugserver(self): + self.init_debugserver_test() + self.build() + host_info_dict = self.get_qHostInfo_response() + self.validate_darwin_minimum_host_info_keys(host_info_dict) + + @skipUnlessDarwin + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @llgs_test + def test_qHostInfo_contains_darwin_required_keys_llgs(self): + self.init_llgs_test() + self.build() + host_info_dict = self.get_qHostInfo_response() + self.validate_darwin_minimum_host_info_keys(host_info_dict) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py new file mode 100644 index 00000000000..48f919aa94b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py @@ -0,0 +1,60 @@ + + +import gdbremote_testcase +import lldbgdbserverutils +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteKill(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + + def attach_commandline_kill_after_initial_stop(self): + reg_expr = r"^\$[XW][0-9a-fA-F]+([^#]*)#[0-9A-Fa-f]{2}" + procs = self.prep_debug_monitor_and_inferior() + self.test_sequence.add_log_lines([ + "read packet: $k#6b", + {"direction": "send", "regex": reg_expr}, + ], True) + + if self.stub_sends_two_stop_notifications_on_kill: + # Add an expectation for a second X result for stubs that send two + # of these. + self.test_sequence.add_log_lines([ + {"direction": "send", "regex": reg_expr}, + ], True) + + self.expect_gdbremote_sequence() + + # Wait a moment for completed and now-detached inferior process to + # clear. + time.sleep(self._WAIT_TIMEOUT) + + if not lldb.remote_platform: + # Process should be dead now. Reap results. + poll_result = procs["inferior"].poll() + self.assertIsNotNone(poll_result) + + # Where possible, verify at the system level that the process is not + # running. + self.assertFalse( + lldbgdbserverutils.process_is_running( + procs["inferior"].pid, False)) + + @debugserver_test + def test_attach_commandline_kill_after_initial_stop_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_attach() + self.attach_commandline_kill_after_initial_stop() + + @expectedFailureNetBSD + @llgs_test + def test_attach_commandline_kill_after_initial_stop_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_attach() + self.attach_commandline_kill_after_initial_stop() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteModuleInfo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteModuleInfo.py new file mode 100644 index 00000000000..5e94dbcf922 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteModuleInfo.py @@ -0,0 +1,43 @@ + +import json +import gdbremote_testcase +import lldbgdbserverutils +from lldbsuite.support import seven +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteModuleInfo(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def module_info(self): + procs = self.prep_debug_monitor_and_inferior() + self.add_process_info_collection_packets() + context = self.expect_gdbremote_sequence() + info = self.parse_process_info_response(context) + + self.test_sequence.add_log_lines([ + 'read packet: $jModulesInfo:%s]#00' % json.dumps( + [{"file":lldbutil.append_to_process_working_directory(self, "a.out"), + "triple":seven.unhexlify(info["triple"])}]), + {"direction": "send", + "regex": r'^\$\[{(.*)}\]\]#[0-9A-Fa-f]{2}', + "capture": {1: "spec"}}, + ], True) + + context = self.expect_gdbremote_sequence() + spec = context.get("spec") + self.assertRegexpMatches(spec, '"file_path":".*"') + self.assertRegexpMatches(spec, '"file_offset":\d+') + self.assertRegexpMatches(spec, '"file_size":\d+') + self.assertRegexpMatches(spec, '"triple":"\w*-\w*-.*"') + self.assertRegexpMatches(spec, '"uuid":"[A-Fa-f0-9]+"') + + @llgs_test + def test_module_info(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.module_info() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py new file mode 100644 index 00000000000..bc793a36e99 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py @@ -0,0 +1,209 @@ + + + +import gdbremote_testcase +import lldbgdbserverutils +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteProcessInfo(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def qProcessInfo_returns_running_process(self): + procs = self.prep_debug_monitor_and_inferior() + self.add_process_info_collection_packets() + + # Run the stream + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather process info response + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + + # Ensure the process id looks reasonable. + pid_text = process_info.get("pid") + self.assertIsNotNone(pid_text) + pid = int(pid_text, base=16) + self.assertNotEqual(0, pid) + + # If possible, verify that the process is running. + self.assertTrue(lldbgdbserverutils.process_is_running(pid, True)) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qProcessInfo_returns_running_process_debugserver(self): + self.init_debugserver_test() + self.build() + self.qProcessInfo_returns_running_process() + + @llgs_test + def test_qProcessInfo_returns_running_process_llgs(self): + self.init_llgs_test() + self.build() + self.qProcessInfo_returns_running_process() + + def attach_commandline_qProcessInfo_reports_correct_pid(self): + procs = self.prep_debug_monitor_and_inferior() + self.assertIsNotNone(procs) + self.add_process_info_collection_packets() + + # Run the stream + context = self.expect_gdbremote_sequence(timeout_seconds=self._DEFAULT_TIMEOUT) + self.assertIsNotNone(context) + + # Gather process info response + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + + # Ensure the process id matches what we expected. + pid_text = process_info.get('pid', None) + self.assertIsNotNone(pid_text) + reported_pid = int(pid_text, base=16) + self.assertEqual(reported_pid, procs["inferior"].pid) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_attach_commandline_qProcessInfo_reports_correct_pid_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_attach() + self.attach_commandline_qProcessInfo_reports_correct_pid() + + @expectedFailureNetBSD + @llgs_test + def test_attach_commandline_qProcessInfo_reports_correct_pid_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_attach() + self.attach_commandline_qProcessInfo_reports_correct_pid() + + def qProcessInfo_reports_valid_endian(self): + procs = self.prep_debug_monitor_and_inferior() + self.add_process_info_collection_packets() + + # Run the stream + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather process info response + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + + # Ensure the process id looks reasonable. + endian = process_info.get("endian") + self.assertIsNotNone(endian) + self.assertTrue(endian in ["little", "big", "pdp"]) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qProcessInfo_reports_valid_endian_debugserver(self): + self.init_debugserver_test() + self.build() + self.qProcessInfo_reports_valid_endian() + + @llgs_test + def test_qProcessInfo_reports_valid_endian_llgs(self): + self.init_llgs_test() + self.build() + self.qProcessInfo_reports_valid_endian() + + def qProcessInfo_contains_keys(self, expected_key_set): + procs = self.prep_debug_monitor_and_inferior() + self.add_process_info_collection_packets() + + # Run the stream + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather process info response + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + + # Ensure the expected keys are present and non-None within the process + # info. + missing_key_set = set() + for expected_key in expected_key_set: + if expected_key not in process_info: + missing_key_set.add(expected_key) + + self.assertEqual( + missing_key_set, + set(), + "the listed keys are missing in the qProcessInfo result") + + def qProcessInfo_does_not_contain_keys(self, absent_key_set): + procs = self.prep_debug_monitor_and_inferior() + self.add_process_info_collection_packets() + + # Run the stream + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather process info response + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + + # Ensure the unexpected keys are not present + unexpected_key_set = set() + for unexpected_key in absent_key_set: + if unexpected_key in process_info: + unexpected_key_set.add(unexpected_key) + + self.assertEqual( + unexpected_key_set, + set(), + "the listed keys were present but unexpected in qProcessInfo result") + + @skipUnlessDarwin + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qProcessInfo_contains_cputype_cpusubtype_debugserver_darwin(self): + self.init_debugserver_test() + self.build() + self.qProcessInfo_contains_keys(set(['cputype', 'cpusubtype'])) + + @skipUnlessDarwin + @llgs_test + def test_qProcessInfo_contains_cputype_cpusubtype_llgs_darwin(self): + self.init_llgs_test() + self.build() + self.qProcessInfo_contains_keys(set(['cputype', 'cpusubtype'])) + + @llgs_test + def test_qProcessInfo_contains_triple_ppid_llgs(self): + self.init_llgs_test() + self.build() + self.qProcessInfo_contains_keys(set(['triple', 'parent-pid'])) + + @skipUnlessDarwin + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qProcessInfo_does_not_contain_triple_debugserver_darwin(self): + self.init_debugserver_test() + self.build() + # We don't expect to see triple on darwin. If we do, we'll prefer triple + # to cputype/cpusubtype and skip some darwin-based ProcessGDBRemote ArchSpec setup + # for the remote Host and Process. + self.qProcessInfo_does_not_contain_keys(set(['triple'])) + + @skipUnlessDarwin + @llgs_test + def test_qProcessInfo_does_not_contain_triple_llgs_darwin(self): + self.init_llgs_test() + self.build() + # We don't expect to see triple on darwin. If we do, we'll prefer triple + # to cputype/cpusubtype and skip some darwin-based ProcessGDBRemote ArchSpec setup + # for the remote Host and Process. + self.qProcessInfo_does_not_contain_keys(set(['triple'])) + + @skipIfDarwin + @llgs_test + def test_qProcessInfo_does_not_contain_cputype_cpusubtype_llgs(self): + self.init_llgs_test() + self.build() + self.qProcessInfo_does_not_contain_keys(set(['cputype', 'cpusubtype'])) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py new file mode 100644 index 00000000000..2543ed6e902 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py @@ -0,0 +1,128 @@ +from __future__ import print_function + + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteRegisterState(gdbremote_testcase.GdbRemoteTestCaseBase): + """Test QSaveRegisterState/QRestoreRegisterState support.""" + + mydir = TestBase.compute_mydir(__file__) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def grp_register_save_restore_works(self, with_suffix): + # Start up the process, use thread suffix, grab main thread id. + inferior_args = ["message:main entered", "sleep:5"] + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) + + self.add_process_info_collection_packets() + self.add_register_info_collection_packets() + if with_suffix: + self.add_thread_suffix_request_packets() + self.add_threadinfo_collection_packets() + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather process info. + process_info = self.parse_process_info_response(context) + endian = process_info.get("endian") + self.assertIsNotNone(endian) + + # Gather register info. + reg_infos = self.parse_register_info_packets(context) + self.assertIsNotNone(reg_infos) + self.add_lldb_register_index(reg_infos) + + # Pull out the register infos that we think we can bit flip + # successfully. + gpr_reg_infos = [ + reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)] + self.assertTrue(len(gpr_reg_infos) > 0) + + # Gather thread info. + if with_suffix: + threads = self.parse_threadinfo_packets(context) + self.assertIsNotNone(threads) + thread_id = threads[0] + self.assertIsNotNone(thread_id) + # print("Running on thread: 0x{:x}".format(thread_id)) + else: + thread_id = None + + # Save register state. + self.reset_test_sequence() + self.add_QSaveRegisterState_packets(thread_id) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + (success, state_id) = self.parse_QSaveRegisterState_response(context) + self.assertTrue(success) + self.assertIsNotNone(state_id) + # print("saved register state id: {}".format(state_id)) + + # Remember initial register values. + initial_reg_values = self.read_register_values( + gpr_reg_infos, endian, thread_id=thread_id) + # print("initial_reg_values: {}".format(initial_reg_values)) + + # Flip gpr register values. + (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value( + gpr_reg_infos, endian, thread_id=thread_id) + # print("successful writes: {}, failed writes: {}".format(successful_writes, failed_writes)) + self.assertTrue(successful_writes > 0) + + flipped_reg_values = self.read_register_values( + gpr_reg_infos, endian, thread_id=thread_id) + # print("flipped_reg_values: {}".format(flipped_reg_values)) + + # Restore register values. + self.reset_test_sequence() + self.add_QRestoreRegisterState_packets(state_id, thread_id) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Verify registers match initial register values. + final_reg_values = self.read_register_values( + gpr_reg_infos, endian, thread_id=thread_id) + # print("final_reg_values: {}".format(final_reg_values)) + self.assertIsNotNone(final_reg_values) + self.assertEqual(final_reg_values, initial_reg_values) + + @debugserver_test + def test_grp_register_save_restore_works_with_suffix_debugserver(self): + USE_THREAD_SUFFIX = True + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.grp_register_save_restore_works(USE_THREAD_SUFFIX) + + @llgs_test + def test_grp_register_save_restore_works_with_suffix_llgs(self): + USE_THREAD_SUFFIX = True + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.grp_register_save_restore_works(USE_THREAD_SUFFIX) + + @debugserver_test + def test_grp_register_save_restore_works_no_suffix_debugserver(self): + USE_THREAD_SUFFIX = False + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.grp_register_save_restore_works(USE_THREAD_SUFFIX) + + @llgs_test + def test_grp_register_save_restore_works_no_suffix_llgs(self): + USE_THREAD_SUFFIX = False + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.grp_register_save_restore_works(USE_THREAD_SUFFIX) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py new file mode 100644 index 00000000000..c6c750299b1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py @@ -0,0 +1,39 @@ + + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteSingleStep(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @debugserver_test + def test_single_step_only_steps_one_instruction_with_s_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.single_step_only_steps_one_instruction( + use_Hc_packet=True, step_instruction="s") + + @skipIfWindows # No pty support to test any inferior std -i/e/o + @llgs_test + @expectedFailureAndroid( + bugnumber="llvm.org/pr24739", + archs=[ + "arm", + "aarch64"]) + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + bugnumber="llvm.org/pr24739") + @skipIf(triple='^mips') + def test_single_step_only_steps_one_instruction_with_s_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.single_step_only_steps_one_instruction( + use_Hc_packet=True, step_instruction="s") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py new file mode 100644 index 00000000000..f9bd668a6dd --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py @@ -0,0 +1,315 @@ + +import json +import re + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestGdbRemoteThreadsInStopReply( + gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + ENABLE_THREADS_IN_STOP_REPLY_ENTRIES = [ + "read packet: $QListThreadsInStopReply#21", + "send packet: $OK#00", + ] + + def gather_stop_reply_fields(self, post_startup_log_lines, thread_count, + field_names): + # Set up the inferior args. + inferior_args = [] + for i in range(thread_count - 1): + inferior_args.append("thread:new") + inferior_args.append("sleep:10") + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) + + self.add_register_info_collection_packets() + self.add_process_info_collection_packets() + + # Assumes test_sequence has anything added needed to setup the initial state. + # (Like optionally enabling QThreadsInStopReply.) + if post_startup_log_lines: + self.test_sequence.add_log_lines(post_startup_log_lines, True) + self.test_sequence.add_log_lines([ + "read packet: $c#63" + ], True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + hw_info = self.parse_hw_info(context) + + # Give threads time to start up, then break. + time.sleep(self._WAIT_TIMEOUT) + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + "read packet: {}".format( + chr(3)), + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": { + 1: "stop_result", + 2: "key_vals_text"}}, + ], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Wait until all threads have started. + threads = self.wait_for_thread_count(thread_count, + timeout_seconds=self._WAIT_TIMEOUT) + self.assertIsNotNone(threads) + self.assertEqual(len(threads), thread_count) + + # Run, then stop the process, grab the stop reply content. + self.reset_test_sequence() + self.test_sequence.add_log_lines(["read packet: $c#63", + "read packet: {}".format(chr(3)), + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": {1: "stop_result", + 2: "key_vals_text"}}, + ], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Parse the stop reply contents. + key_vals_text = context.get("key_vals_text") + self.assertIsNotNone(key_vals_text) + kv_dict = self.parse_key_val_dict(key_vals_text) + self.assertIsNotNone(kv_dict) + + result = dict(); + result["pc_register"] = hw_info["pc_register"] + result["little_endian"] = hw_info["little_endian"] + for key_field in field_names: + result[key_field] = kv_dict.get(key_field) + + return result + + def gather_stop_reply_threads(self, post_startup_log_lines, thread_count): + # Pull out threads from stop response. + stop_reply_threads_text = self.gather_stop_reply_fields( + post_startup_log_lines, thread_count, ["threads"])["threads"] + if stop_reply_threads_text: + return [int(thread_id, 16) + for thread_id in stop_reply_threads_text.split(",")] + else: + return [] + + def gather_stop_reply_pcs(self, post_startup_log_lines, thread_count): + results = self.gather_stop_reply_fields( post_startup_log_lines, + thread_count, ["threads", "thread-pcs"]) + if not results: + return [] + + threads_text = results["threads"] + pcs_text = results["thread-pcs"] + thread_ids = threads_text.split(",") + pcs = pcs_text.split(",") + self.assertTrue(len(thread_ids) == len(pcs)) + + thread_pcs = dict() + for i in range(0, len(pcs)): + thread_pcs[int(thread_ids[i], 16)] = pcs[i] + + result = dict() + result["thread_pcs"] = thread_pcs + result["pc_register"] = results["pc_register"] + result["little_endian"] = results["little_endian"] + return result + + def switch_endian(self, egg): + return "".join(reversed(re.findall("..", egg))) + + def parse_hw_info(self, context): + self.assertIsNotNone(context) + process_info = self.parse_process_info_response(context) + endian = process_info.get("endian") + reg_info = self.parse_register_info_packets(context) + (pc_lldb_reg_index, pc_reg_info) = self.find_pc_reg_info(reg_info) + + hw_info = dict() + hw_info["pc_register"] = pc_lldb_reg_index + hw_info["little_endian"] = (endian == "little") + return hw_info + + def gather_threads_info_pcs(self, pc_register, little_endian): + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + "read packet: $jThreadsInfo#c1", + { + "direction": "send", + "regex": r"^\$(.*)#[0-9a-fA-F]{2}$", + "capture": { + 1: "threads_info"}}, + ], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + threads_info = context.get("threads_info") + register = str(pc_register) + # The jThreadsInfo response is not valid JSON data, so we have to + # clean it up first. + jthreads_info = json.loads(re.sub(r"}]", "}", threads_info)) + thread_pcs = dict() + for thread_info in jthreads_info: + tid = thread_info["tid"] + pc = thread_info["registers"][register] + thread_pcs[tid] = self.switch_endian(pc) if little_endian else pc + + return thread_pcs + + def QListThreadsInStopReply_supported(self): + procs = self.prep_debug_monitor_and_inferior() + self.test_sequence.add_log_lines( + self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @debugserver_test + def test_QListThreadsInStopReply_supported_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.QListThreadsInStopReply_supported() + + @llgs_test + def test_QListThreadsInStopReply_supported_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.QListThreadsInStopReply_supported() + + def stop_reply_reports_multiple_threads(self, thread_count): + # Gather threads from stop notification when QThreadsInStopReply is + # enabled. + stop_reply_threads = self.gather_stop_reply_threads( + self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, thread_count) + self.assertEqual(len(stop_reply_threads), thread_count) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @debugserver_test + def test_stop_reply_reports_multiple_threads_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.stop_reply_reports_multiple_threads(5) + + # In current implementation of llgs on Windows, as a response to '\x03' packet, the debugger + # of the native process will trigger a call to DebugBreakProcess that will create a new thread + # to handle the exception debug event. So one more stop thread will be notified to the + # delegate, e.g. llgs. So tests below to assert the stop threads number will all fail. + @expectedFailureAll(oslist=["windows"]) + @skipIfNetBSD + @llgs_test + def test_stop_reply_reports_multiple_threads_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.stop_reply_reports_multiple_threads(5) + + def no_QListThreadsInStopReply_supplies_no_threads(self, thread_count): + # Gather threads from stop notification when QThreadsInStopReply is not + # enabled. + stop_reply_threads = self.gather_stop_reply_threads(None, thread_count) + self.assertEqual(len(stop_reply_threads), 0) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @debugserver_test + def test_no_QListThreadsInStopReply_supplies_no_threads_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.no_QListThreadsInStopReply_supplies_no_threads(5) + + @expectedFailureAll(oslist=["windows"]) + @skipIfNetBSD + @llgs_test + def test_no_QListThreadsInStopReply_supplies_no_threads_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.no_QListThreadsInStopReply_supplies_no_threads(5) + + def stop_reply_reports_correct_threads(self, thread_count): + # Gather threads from stop notification when QThreadsInStopReply is + # enabled. + stop_reply_threads = self.gather_stop_reply_threads( + self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, thread_count) + self.assertEqual(len(stop_reply_threads), thread_count) + + # Gather threads from q{f,s}ThreadInfo. + self.reset_test_sequence() + self.add_threadinfo_collection_packets() + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + threads = self.parse_threadinfo_packets(context) + self.assertIsNotNone(threads) + self.assertEqual(len(threads), thread_count) + + # Ensure each thread in q{f,s}ThreadInfo appears in stop reply threads + for tid in threads: + self.assertTrue(tid in stop_reply_threads) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @debugserver_test + def test_stop_reply_reports_correct_threads_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.stop_reply_reports_correct_threads(5) + + @expectedFailureAll(oslist=["windows"]) + @skipIfNetBSD + @llgs_test + def test_stop_reply_reports_correct_threads_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.stop_reply_reports_correct_threads(5) + + def stop_reply_contains_thread_pcs(self, thread_count): + results = self.gather_stop_reply_pcs( + self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, thread_count) + stop_reply_pcs = results["thread_pcs"] + pc_register = results["pc_register"] + little_endian = results["little_endian"] + self.assertEqual(len(stop_reply_pcs), thread_count) + + threads_info_pcs = self.gather_threads_info_pcs(pc_register, + little_endian) + + self.assertEqual(len(threads_info_pcs), thread_count) + for thread_id in stop_reply_pcs: + self.assertTrue(thread_id in threads_info_pcs) + self.assertTrue(int(stop_reply_pcs[thread_id], 16) + == int(threads_info_pcs[thread_id], 16)) + + @expectedFailureAll(oslist=["windows"]) + @skipIfNetBSD + @llgs_test + def test_stop_reply_contains_thread_pcs_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.stop_reply_contains_thread_pcs(5) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @debugserver_test + def test_stop_reply_contains_thread_pcs_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.stop_reply_contains_thread_pcs(5) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py new file mode 100644 index 00000000000..51dd0cb1a3b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py @@ -0,0 +1,203 @@ + + + +import unittest2 +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemote_qThreadStopInfo(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + THREAD_COUNT = 5 + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + @skipIfDarwinEmbedded # <rdar://problem/27005337> + def gather_stop_replies_via_qThreadStopInfo(self, thread_count): + # Set up the inferior args. + inferior_args = [] + for i in range(thread_count - 1): + inferior_args.append("thread:new") + inferior_args.append("sleep:10") + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) + + # Assumes test_sequence has anything added needed to setup the initial state. + # (Like optionally enabling QThreadsInStopReply.) + self.test_sequence.add_log_lines([ + "read packet: $c#63" + ], True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Give threads time to start up, then break. + time.sleep(self._WAIT_TIMEOUT) + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + "read packet: {}".format( + chr(3)), + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": { + 1: "stop_result", + 2: "key_vals_text"}}, + ], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Wait until all threads have started. + threads = self.wait_for_thread_count(thread_count, + timeout_seconds=self._WAIT_TIMEOUT) + self.assertIsNotNone(threads) + + # On Windows, there could be more threads spawned. For example, DebugBreakProcess will + # create a new thread from the debugged process to handle an exception event. So here we + # assert 'GreaterEqual' condition. + triple = self.dbg.GetSelectedPlatform().GetTriple() + if re.match(".*-.*-windows", triple): + self.assertGreaterEqual(len(threads), thread_count) + else: + self.assertEqual(len(threads), thread_count) + + # Grab stop reply for each thread via qThreadStopInfo{tid:hex}. + stop_replies = {} + thread_dicts = {} + for thread in threads: + # Run the qThreadStopInfo command. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + "read packet: $qThreadStopInfo{:x}#00".format(thread), + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", + "capture": { + 1: "stop_result", + 2: "key_vals_text"}}, + ], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Parse stop reply contents. + key_vals_text = context.get("key_vals_text") + self.assertIsNotNone(key_vals_text) + kv_dict = self.parse_key_val_dict(key_vals_text) + self.assertIsNotNone(kv_dict) + + # Verify there is a thread and that it matches the expected thread + # id. + kv_thread = kv_dict.get("thread") + self.assertIsNotNone(kv_thread) + kv_thread_id = int(kv_thread, 16) + self.assertEqual(kv_thread_id, thread) + + # Grab the stop id reported. + stop_result_text = context.get("stop_result") + self.assertIsNotNone(stop_result_text) + stop_replies[kv_thread_id] = int(stop_result_text, 16) + + # Hang on to the key-val dictionary for the thread. + thread_dicts[kv_thread_id] = kv_dict + + return (stop_replies, thread_dicts) + + def qThreadStopInfo_works_for_multiple_threads(self, thread_count): + (stop_replies, _) = self.gather_stop_replies_via_qThreadStopInfo(thread_count) + triple = self.dbg.GetSelectedPlatform().GetTriple() + # Consider one more thread created by calling DebugBreakProcess. + if re.match(".*-.*-windows", triple): + self.assertGreaterEqual(len(stop_replies), thread_count) + else: + self.assertEqual(len(stop_replies), thread_count) + + @debugserver_test + def test_qThreadStopInfo_works_for_multiple_threads_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadStopInfo_works_for_multiple_threads(self.THREAD_COUNT) + + @llgs_test + @skipIfNetBSD + def test_qThreadStopInfo_works_for_multiple_threads_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadStopInfo_works_for_multiple_threads(self.THREAD_COUNT) + + def qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt( + self, thread_count): + (stop_replies, _) = self.gather_stop_replies_via_qThreadStopInfo(thread_count) + self.assertIsNotNone(stop_replies) + + no_stop_reason_count = sum( + 1 for stop_reason in list( + stop_replies.values()) if stop_reason == 0) + with_stop_reason_count = sum( + 1 for stop_reason in list( + stop_replies.values()) if stop_reason != 0) + + # All but one thread should report no stop reason. + triple = self.dbg.GetSelectedPlatform().GetTriple() + + # Consider one more thread created by calling DebugBreakProcess. + if re.match(".*-.*-windows", triple): + self.assertGreaterEqual(no_stop_reason_count, thread_count - 1) + else: + self.assertEqual(no_stop_reason_count, thread_count - 1) + + # Only one thread should should indicate a stop reason. + self.assertEqual(with_stop_reason_count, 1) + + @debugserver_test + def test_qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt( + self.THREAD_COUNT) + + @expectedFailureNetBSD + @llgs_test + def test_qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt_llgs( + self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt( + self.THREAD_COUNT) + + def qThreadStopInfo_has_valid_thread_names( + self, thread_count, expected_thread_name): + (_, thread_dicts) = self.gather_stop_replies_via_qThreadStopInfo(thread_count) + self.assertIsNotNone(thread_dicts) + + for thread_dict in list(thread_dicts.values()): + name = thread_dict.get("name") + self.assertIsNotNone(name) + self.assertEqual(name, expected_thread_name) + + @unittest2.skip("MacOSX doesn't have a default thread name") + @debugserver_test + def test_qThreadStopInfo_has_valid_thread_names_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadStopInfo_has_valid_thread_names(self.THREAD_COUNT, "a.out") + + # test requires OS with set, equal thread names by default. + # Windows thread does not have name property, equal names as the process's by default. + @skipUnlessPlatform(["linux", "windows"]) + @llgs_test + def test_qThreadStopInfo_has_valid_thread_names_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadStopInfo_has_valid_thread_names(self.THREAD_COUNT, "a.out") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py new file mode 100644 index 00000000000..3511b014d56 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py @@ -0,0 +1,156 @@ + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemote_vCont(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def vCont_supports_mode(self, mode, inferior_args=None): + # Setup the stub and set the gdb remote command stream. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) + self.add_vCont_query_packets() + + # Run the gdb remote command stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Pull out supported modes. + supported_vCont_modes = self.parse_vCont_query_response(context) + self.assertIsNotNone(supported_vCont_modes) + + # Verify we support the given mode. + self.assertTrue(mode in supported_vCont_modes) + + def vCont_supports_c(self): + self.vCont_supports_mode("c") + + def vCont_supports_C(self): + self.vCont_supports_mode("C") + + def vCont_supports_s(self): + self.vCont_supports_mode("s") + + def vCont_supports_S(self): + self.vCont_supports_mode("S") + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @debugserver_test + def test_vCont_supports_c_debugserver(self): + self.init_debugserver_test() + self.build() + self.vCont_supports_c() + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @llgs_test + def test_vCont_supports_c_llgs(self): + self.init_llgs_test() + self.build() + self.vCont_supports_c() + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @debugserver_test + def test_vCont_supports_C_debugserver(self): + self.init_debugserver_test() + self.build() + self.vCont_supports_C() + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @llgs_test + def test_vCont_supports_C_llgs(self): + self.init_llgs_test() + self.build() + self.vCont_supports_C() + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @debugserver_test + def test_vCont_supports_s_debugserver(self): + self.init_debugserver_test() + self.build() + self.vCont_supports_s() + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @llgs_test + def test_vCont_supports_s_llgs(self): + self.init_llgs_test() + self.build() + self.vCont_supports_s() + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @debugserver_test + def test_vCont_supports_S_debugserver(self): + self.init_debugserver_test() + self.build() + self.vCont_supports_S() + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @llgs_test + def test_vCont_supports_S_llgs(self): + self.init_llgs_test() + self.build() + self.vCont_supports_S() + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @debugserver_test + def test_single_step_only_steps_one_instruction_with_Hc_vCont_s_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.single_step_only_steps_one_instruction( + use_Hc_packet=True, step_instruction="vCont;s") + + @skipIfWindows # No pty support to test O* & I* notification packets. + @llgs_test + @expectedFailureAndroid( + bugnumber="llvm.org/pr24739", + archs=[ + "arm", + "aarch64"]) + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + bugnumber="llvm.org/pr24739") + @skipIf(triple='^mips') + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + def test_single_step_only_steps_one_instruction_with_Hc_vCont_s_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.single_step_only_steps_one_instruction( + use_Hc_packet=True, step_instruction="vCont;s") + + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + @debugserver_test + def test_single_step_only_steps_one_instruction_with_vCont_s_thread_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.single_step_only_steps_one_instruction( + use_Hc_packet=False, step_instruction="vCont;s:{thread}") + + @skipIfWindows # No pty support to test O* & I* notification packets. + @llgs_test + @expectedFailureAndroid( + bugnumber="llvm.org/pr24739", + archs=[ + "arm", + "aarch64"]) + @expectedFailureAll( + oslist=["linux"], + archs=["arm"], + bugnumber="llvm.org/pr24739") + @skipIf(triple='^mips') + @expectedFailureAll(oslist=["ios", "tvos", "watchos", "bridgeos"], bugnumber="rdar://27005337") + def test_single_step_only_steps_one_instruction_with_vCont_s_thread_llgs( + self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.single_step_only_steps_one_instruction( + use_Hc_packet=False, step_instruction="vCont;s:{thread}") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vContThreads.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vContThreads.py new file mode 100644 index 00000000000..e16a28a335a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vContThreads.py @@ -0,0 +1,148 @@ + +import json +import re + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestGdbRemote_vContThreads(gdbremote_testcase.GdbRemoteTestCaseBase): + mydir = TestBase.compute_mydir(__file__) + + def start_threads(self, num): + procs = self.prep_debug_monitor_and_inferior( + inferior_args=['thread:new'] * num + ['@started']) + # start the process and wait for output + self.test_sequence.add_log_lines([ + "read packet: $c#63", + {"type": "output_match", "regex": self.maybe_strict_output_regex( + r"@started\r\n")}, + ], True) + # then interrupt it + self.add_interrupt_packets() + self.add_threadinfo_collection_packets() + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + threads = self.parse_threadinfo_packets(context) + self.assertIsNotNone(threads) + self.assertEqual(len(threads), num + 1) + + self.reset_test_sequence() + return threads + + def signal_one_thread(self): + threads = self.start_threads(1) + # try sending a signal to one of the two threads + self.test_sequence.add_log_lines([ + "read packet: $vCont;C{0:x}:{1:x};c#00".format( + lldbutil.get_signal_number('SIGUSR1'), threads[0]), + {"direction": "send", "regex": r"^\$W00#b7$"}, + ], True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + @skipUnlessPlatform(["netbsd"]) + @debugserver_test + def test_signal_one_thread_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.signal_one_thread() + + @skipUnlessPlatform(["netbsd"]) + @llgs_test + def test_signal_one_thread_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.signal_one_thread() + + def signal_all_threads(self): + threads = self.start_threads(1) + # try sending a signal to two threads (= the process) + self.test_sequence.add_log_lines([ + "read packet: $vCont;C{0:x}:{1:x};C{0:x}:{2:x}#00".format( + lldbutil.get_signal_number('SIGUSR1'), + threads[0], threads[1]), + {"direction": "send", "regex": r"^\$W00#b7$"}, + ], True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + @skipUnlessPlatform(["netbsd"]) + @debugserver_test + def test_signal_all_threads_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.signal_all_threads() + + @skipUnlessPlatform(["netbsd"]) + @llgs_test + def test_signal_all_threads_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.signal_all_threads() + + def signal_two_of_three_threads(self): + threads = self.start_threads(2) + # try sending a signal to 2 out of 3 threads + self.test_sequence.add_log_lines([ + "read packet: $vCont;C{0:x}:{1:x};C{0:x}:{2:x};c#00".format( + lldbutil.get_signal_number('SIGUSR1'), + threads[1], threads[2]), + {"direction": "send", "regex": r"^\$E1e#db$"}, + ], True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + @skipUnlessPlatform(["netbsd"]) + @debugserver_test + def test_signal_two_of_three_threads_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.signal_two_of_three_threads() + + @skipUnlessPlatform(["netbsd"]) + @llgs_test + def test_signal_two_of_three_threads_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.signal_two_of_three_threads() + + def signal_two_signals(self): + threads = self.start_threads(1) + # try sending two different signals to two threads + self.test_sequence.add_log_lines([ + "read packet: $vCont;C{0:x}:{1:x};C{2:x}:{3:x}#00".format( + lldbutil.get_signal_number('SIGUSR1'), threads[0], + lldbutil.get_signal_number('SIGUSR2'), threads[1]), + {"direction": "send", "regex": r"^\$E1e#db$"}, + ], True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + @skipUnlessPlatform(["netbsd"]) + @debugserver_test + def test_signal_two_signals_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.signal_two_signals() + + @skipUnlessPlatform(["netbsd"]) + @llgs_test + def test_signal_two_signals_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.signal_two_signals() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py new file mode 100644 index 00000000000..2b7f28a3aef --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py @@ -0,0 +1,1590 @@ +""" +Test case for testing the gdbremote protocol. + +Tests run against debugserver and lldb-server (llgs). +lldb-server tests run where the lldb-server exe is +available. + +This class will be broken into smaller test case classes by +gdb remote packet functional areas. For now it contains +the initial set of tests implemented. +""" + +from __future__ import division, print_function + + +import unittest2 +import gdbremote_testcase +import lldbgdbserverutils +from lldbsuite.support import seven +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test.lldbdwarf import * +from lldbsuite.test import lldbutil + + +class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase, DwarfOpcodeParser): + + mydir = TestBase.compute_mydir(__file__) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_exe_starts_debugserver(self): + self.init_debugserver_test() + server = self.connect_to_debug_monitor() + + @llgs_test + def test_exe_starts_llgs(self): + self.init_llgs_test() + server = self.connect_to_debug_monitor() + + def start_no_ack_mode(self): + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + self.add_no_ack_remote_stream() + self.expect_gdbremote_sequence() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_start_no_ack_mode_debugserver(self): + self.init_debugserver_test() + self.start_no_ack_mode() + + @llgs_test + def test_start_no_ack_mode_llgs(self): + self.init_llgs_test() + self.start_no_ack_mode() + + def thread_suffix_supported(self): + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + self.add_no_ack_remote_stream() + self.test_sequence.add_log_lines( + ["lldb-server < 26> read packet: $QThreadSuffixSupported#e4", + "lldb-server < 6> send packet: $OK#9a"], + True) + + self.expect_gdbremote_sequence() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_thread_suffix_supported_debugserver(self): + self.init_debugserver_test() + self.thread_suffix_supported() + + @llgs_test + def test_thread_suffix_supported_llgs(self): + self.init_llgs_test() + self.thread_suffix_supported() + + def list_threads_in_stop_reply_supported(self): + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + self.add_no_ack_remote_stream() + self.test_sequence.add_log_lines( + ["lldb-server < 27> read packet: $QListThreadsInStopReply#21", + "lldb-server < 6> send packet: $OK#9a"], + True) + self.expect_gdbremote_sequence() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_list_threads_in_stop_reply_supported_debugserver(self): + self.init_debugserver_test() + self.list_threads_in_stop_reply_supported() + + @llgs_test + def test_list_threads_in_stop_reply_supported_llgs(self): + self.init_llgs_test() + self.list_threads_in_stop_reply_supported() + + def c_packet_works(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.test_sequence.add_log_lines( + ["read packet: $c#63", + "send packet: $W00#00"], + True) + + self.expect_gdbremote_sequence() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_c_packet_works_debugserver(self): + self.init_debugserver_test() + self.build() + self.c_packet_works() + + @llgs_test + def test_c_packet_works_llgs(self): + self.init_llgs_test() + self.build() + self.c_packet_works() + + def inferior_print_exit(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + # build launch args + launch_args += ["hello, world"] + + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.test_sequence.add_log_lines( + ["read packet: $vCont;c#a8", + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"hello, world\r\n")}, + "send packet: $W00#00"], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_inferior_print_exit_debugserver(self): + self.init_debugserver_test() + self.build() + self.inferior_print_exit() + + @skipIfWindows # No pty support to test any inferior output + @llgs_test + @expectedFlakeyLinux("llvm.org/pr25652") + def test_inferior_print_exit_llgs(self): + self.init_llgs_test() + self.build() + self.inferior_print_exit() + + def first_launch_stop_reply_thread_matches_first_qC(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + # build launch args + launch_args += ["hello, world"] + + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.test_sequence.add_log_lines(["read packet: $qC#00", + {"direction": "send", + "regex": r"^\$QC([0-9a-fA-F]+)#", + "capture": {1: "thread_id"}}, + "read packet: $?#00", + {"direction": "send", + "regex": r"^\$T[0-9a-fA-F]{2}thread:([0-9a-fA-F]+)", + "expect_captures": {1: "thread_id"}}], + True) + self.expect_gdbremote_sequence() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_first_launch_stop_reply_thread_matches_first_qC_debugserver(self): + self.init_debugserver_test() + self.build() + self.first_launch_stop_reply_thread_matches_first_qC() + + @llgs_test + def test_first_launch_stop_reply_thread_matches_first_qC_llgs(self): + self.init_llgs_test() + self.build() + self.first_launch_stop_reply_thread_matches_first_qC() + + def attach_commandline_continue_app_exits(self): + procs = self.prep_debug_monitor_and_inferior() + self.test_sequence.add_log_lines( + ["read packet: $vCont;c#a8", + "send packet: $W00#00"], + True) + self.expect_gdbremote_sequence() + + # Wait a moment for completed and now-detached inferior process to + # clear. + time.sleep(1) + + if not lldb.remote_platform: + # Process should be dead now. Reap results. + poll_result = procs["inferior"].poll() + self.assertIsNotNone(poll_result) + + # Where possible, verify at the system level that the process is not + # running. + self.assertFalse( + lldbgdbserverutils.process_is_running( + procs["inferior"].pid, False)) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_attach_commandline_continue_app_exits_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_attach() + self.attach_commandline_continue_app_exits() + + @expectedFailureNetBSD + @llgs_test + def test_attach_commandline_continue_app_exits_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_attach() + self.attach_commandline_continue_app_exits() + + def qRegisterInfo_returns_one_valid_result(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + # Build the expected protocol stream + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.test_sequence.add_log_lines( + ["read packet: $qRegisterInfo0#00", + {"direction": "send", "regex": r"^\$(.+);#[0-9A-Fa-f]{2}", "capture": {1: "reginfo_0"}}], + True) + + # Run the stream + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + reg_info_packet = context.get("reginfo_0") + self.assertIsNotNone(reg_info_packet) + self.assert_valid_reg_info( + lldbgdbserverutils.parse_reg_info_response(reg_info_packet)) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qRegisterInfo_returns_one_valid_result_debugserver(self): + self.init_debugserver_test() + self.build() + self.qRegisterInfo_returns_one_valid_result() + + @llgs_test + def test_qRegisterInfo_returns_one_valid_result_llgs(self): + self.init_llgs_test() + self.build() + self.qRegisterInfo_returns_one_valid_result() + + def qRegisterInfo_returns_all_valid_results(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + # Build the expected protocol stream. + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.add_register_info_collection_packets() + + # Run the stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Validate that each register info returned validates. + for reg_info in self.parse_register_info_packets(context): + self.assert_valid_reg_info(reg_info) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qRegisterInfo_returns_all_valid_results_debugserver(self): + self.init_debugserver_test() + self.build() + self.qRegisterInfo_returns_all_valid_results() + + @llgs_test + def test_qRegisterInfo_returns_all_valid_results_llgs(self): + self.init_llgs_test() + self.build() + self.qRegisterInfo_returns_all_valid_results() + + def qRegisterInfo_contains_required_generics(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + # Build the expected protocol stream + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.add_register_info_collection_packets() + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather register info entries. + reg_infos = self.parse_register_info_packets(context) + + # Collect all generic registers found. + generic_regs = { + reg_info['generic']: 1 for reg_info in reg_infos if 'generic' in reg_info} + + # Ensure we have a program counter register. + self.assertTrue('pc' in generic_regs) + + # Ensure we have a frame pointer register. PPC64le's FP is the same as SP + if self.getArchitecture() != 'powerpc64le': + self.assertTrue('fp' in generic_regs) + + # Ensure we have a stack pointer register. + self.assertTrue('sp' in generic_regs) + + # Ensure we have a flags register. + self.assertTrue('flags' in generic_regs) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qRegisterInfo_contains_required_generics_debugserver(self): + self.init_debugserver_test() + self.build() + self.qRegisterInfo_contains_required_generics() + + @llgs_test + def test_qRegisterInfo_contains_required_generics_llgs(self): + self.init_llgs_test() + self.build() + self.qRegisterInfo_contains_required_generics() + + def qRegisterInfo_contains_at_least_one_register_set(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + # Build the expected protocol stream + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.add_register_info_collection_packets() + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather register info entries. + reg_infos = self.parse_register_info_packets(context) + + # Collect all register sets found. + register_sets = { + reg_info['set']: 1 for reg_info in reg_infos if 'set' in reg_info} + self.assertTrue(len(register_sets) >= 1) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qRegisterInfo_contains_at_least_one_register_set_debugserver( + self): + self.init_debugserver_test() + self.build() + self.qRegisterInfo_contains_at_least_one_register_set() + + @llgs_test + def test_qRegisterInfo_contains_at_least_one_register_set_llgs(self): + self.init_llgs_test() + self.build() + self.qRegisterInfo_contains_at_least_one_register_set() + + def targetHasAVX(self): + triple = self.dbg.GetSelectedPlatform().GetTriple() + + # TODO other platforms, please implement this function + if not re.match(".*-.*-linux", triple): + return True + + # Need to do something different for non-Linux/Android targets + if lldb.remote_platform: + self.runCmd('platform get-file "/proc/cpuinfo" "cpuinfo"') + cpuinfo_path = "cpuinfo" + self.addTearDownHook(lambda: os.unlink("cpuinfo")) + else: + cpuinfo_path = "/proc/cpuinfo" + + f = open(cpuinfo_path, 'r') + cpuinfo = f.read() + f.close() + return " avx " in cpuinfo + + def qRegisterInfo_contains_avx_registers(self): + launch_args = self.install_and_create_launch_args() + + server = self.connect_to_debug_monitor() + self.assertIsNotNone(server) + + # Build the expected protocol stream + self.add_no_ack_remote_stream() + self.add_verified_launch_packets(launch_args) + self.add_register_info_collection_packets() + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather register info entries. + reg_infos = self.parse_register_info_packets(context) + + # Collect all generics found. + register_sets = { + reg_info['set']: 1 for reg_info in reg_infos if 'set' in reg_info} + self.assertEqual( + self.targetHasAVX(), + "Advanced Vector Extensions" in register_sets) + + @expectedFailureAll(oslist=["windows"]) # no avx for now. + @expectedFailureNetBSD + @llgs_test + def test_qRegisterInfo_contains_avx_registers_llgs(self): + self.init_llgs_test() + self.build() + self.qRegisterInfo_contains_avx_registers() + + def qThreadInfo_contains_thread(self): + procs = self.prep_debug_monitor_and_inferior() + self.add_threadinfo_collection_packets() + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather threadinfo entries. + threads = self.parse_threadinfo_packets(context) + self.assertIsNotNone(threads) + + # We should have exactly one thread. + self.assertEqual(len(threads), 1) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qThreadInfo_contains_thread_launch_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadInfo_contains_thread() + + @llgs_test + def test_qThreadInfo_contains_thread_launch_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadInfo_contains_thread() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qThreadInfo_contains_thread_attach_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_attach() + self.qThreadInfo_contains_thread() + + @expectedFailureAll(oslist=["windows"]) # expect one more thread stopped + @expectedFailureNetBSD + @llgs_test + def test_qThreadInfo_contains_thread_attach_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_attach() + self.qThreadInfo_contains_thread() + + def qThreadInfo_matches_qC(self): + procs = self.prep_debug_monitor_and_inferior() + + self.add_threadinfo_collection_packets() + self.test_sequence.add_log_lines( + ["read packet: $qC#00", + {"direction": "send", "regex": r"^\$QC([0-9a-fA-F]+)#", "capture": {1: "thread_id"}} + ], True) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather threadinfo entries. + threads = self.parse_threadinfo_packets(context) + self.assertIsNotNone(threads) + + # We should have exactly one thread from threadinfo. + self.assertEqual(len(threads), 1) + + # We should have a valid thread_id from $QC. + QC_thread_id_hex = context.get("thread_id") + self.assertIsNotNone(QC_thread_id_hex) + QC_thread_id = int(QC_thread_id_hex, 16) + + # Those two should be the same. + self.assertEqual(threads[0], QC_thread_id) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qThreadInfo_matches_qC_launch_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadInfo_matches_qC() + + @llgs_test + def test_qThreadInfo_matches_qC_launch_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qThreadInfo_matches_qC() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qThreadInfo_matches_qC_attach_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_attach() + self.qThreadInfo_matches_qC() + + @expectedFailureAll(oslist=["windows"]) # expect one more thread stopped + @expectedFailureNetBSD + @llgs_test + def test_qThreadInfo_matches_qC_attach_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_attach() + self.qThreadInfo_matches_qC() + + def p_returns_correct_data_size_for_each_qRegisterInfo(self): + procs = self.prep_debug_monitor_and_inferior() + self.add_register_info_collection_packets() + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather register info entries. + reg_infos = self.parse_register_info_packets(context) + self.assertIsNotNone(reg_infos) + self.assertTrue(len(reg_infos) > 0) + + byte_order = self.get_target_byte_order() + + # Read value for each register. + reg_index = 0 + for reg_info in reg_infos: + # Skip registers that don't have a register set. For x86, these are + # the DRx registers, which have no LLDB-kind register number and thus + # cannot be read via normal + # NativeRegisterContext::ReadRegister(reg_info,...) calls. + if not "set" in reg_info: + continue + + # Clear existing packet expectations. + self.reset_test_sequence() + + # Run the register query + self.test_sequence.add_log_lines( + ["read packet: $p{0:x}#00".format(reg_index), + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Verify the response length. + p_response = context.get("p_response") + self.assertIsNotNone(p_response) + + if "dynamic_size_dwarf_expr_bytes" in reg_info: + self.updateRegInfoBitsize(reg_info, byte_order) + self.assertEqual(len(p_response), 2 * int(reg_info["bitsize"]) / 8) + + # Increment loop + reg_index += 1 + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.p_returns_correct_data_size_for_each_qRegisterInfo() + + @expectedFailureNetBSD + @llgs_test + def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_llgs( + self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.p_returns_correct_data_size_for_each_qRegisterInfo() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_attach() + self.p_returns_correct_data_size_for_each_qRegisterInfo() + + @expectedFailureNetBSD + @llgs_test + def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_llgs( + self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_attach() + self.p_returns_correct_data_size_for_each_qRegisterInfo() + + def Hg_switches_to_3_threads(self): + # Startup the inferior with three threads (main + 2 new ones). + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["thread:new", "thread:new"]) + + # Let the inferior process have a few moments to start up the thread + # when launched. (The launch scenario has no time to run, so threads + # won't be there yet.) + self.run_process_then_stop(run_seconds=1) + + # Wait at most x seconds for 3 threads to be present. + threads = self.wait_for_thread_count(3, timeout_seconds=self._WAIT_TIMEOUT) + self.assertEqual(len(threads), 3) + + # verify we can $H to each thead, and $qC matches the thread we set. + for thread in threads: + # Change to each thread, verify current thread id. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + ["read packet: $Hg{0:x}#00".format(thread), # Set current thread. + "send packet: $OK#00", + "read packet: $qC#00", + {"direction": "send", "regex": r"^\$QC([0-9a-fA-F]+)#", "capture": {1: "thread_id"}}], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Verify the thread id. + self.assertIsNotNone(context.get("thread_id")) + self.assertEqual(int(context.get("thread_id"), 16), thread) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_Hg_switches_to_3_threads_launch_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.Hg_switches_to_3_threads() + + @expectedFailureAll(oslist=["windows"]) # expect 4 threads + @llgs_test + def test_Hg_switches_to_3_threads_launch_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.Hg_switches_to_3_threads() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_Hg_switches_to_3_threads_attach_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_attach() + self.Hg_switches_to_3_threads() + + @expectedFailureAll(oslist=["windows"]) # expecting one more thread + @expectedFailureNetBSD + @llgs_test + def test_Hg_switches_to_3_threads_attach_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_attach() + self.Hg_switches_to_3_threads() + + def Hc_then_Csignal_signals_correct_thread(self, segfault_signo): + # NOTE only run this one in inferior-launched mode: we can't grab inferior stdout when running attached, + # and the test requires getting stdout from the exe. + + NUM_THREADS = 3 + + # Startup the inferior with three threads (main + NUM_THREADS-1 worker threads). + # inferior_args=["thread:print-ids"] + inferior_args = ["thread:segfault"] + for i in range(NUM_THREADS - 1): + # if i > 0: + # Give time between thread creation/segfaulting for the handler to work. + # inferior_args.append("sleep:1") + inferior_args.append("thread:new") + inferior_args.append("sleep:10") + + # Launch/attach. (In our case, this should only ever be launched since + # we need inferior stdout/stderr). + procs = self.prep_debug_monitor_and_inferior( + inferior_args=inferior_args) + self.test_sequence.add_log_lines(["read packet: $c#63"], True) + context = self.expect_gdbremote_sequence() + + # Let the inferior process have a few moments to start up the thread when launched. + # context = self.run_process_then_stop(run_seconds=1) + + # Wait at most x seconds for all threads to be present. + # threads = self.wait_for_thread_count(NUM_THREADS, timeout_seconds=5) + # self.assertEquals(len(threads), NUM_THREADS) + + signaled_tids = {} + print_thread_ids = {} + + # Switch to each thread, deliver a signal, and verify signal delivery + for i in range(NUM_THREADS - 1): + # Run until SIGSEGV comes in. + self.reset_test_sequence() + self.test_sequence.add_log_lines([{"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", + "capture": {1: "signo", + 2: "thread_id"}}], + True) + + context = self.expect_gdbremote_sequence(timeout_seconds=self._DEFAULT_TIMEOUT) + self.assertIsNotNone(context) + signo = context.get("signo") + self.assertEqual(int(signo, 16), segfault_signo) + + # Ensure we haven't seen this tid yet. + thread_id = int(context.get("thread_id"), 16) + self.assertFalse(thread_id in signaled_tids) + signaled_tids[thread_id] = 1 + + # Send SIGUSR1 to the thread that signaled the SIGSEGV. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + # Set the continue thread. + # Set current thread. + "read packet: $Hc{0:x}#00".format(thread_id), + "send packet: $OK#00", + + # Continue sending the signal number to the continue thread. + # The commented out packet is a way to do this same operation without using + # a $Hc (but this test is testing $Hc, so we'll stick with the former). + "read packet: $C{0:x}#00".format(lldbutil.get_signal_number('SIGUSR1')), + # "read packet: $vCont;C{0:x}:{1:x};c#00".format(lldbutil.get_signal_number('SIGUSR1'), thread_id), + + # FIXME: Linux does not report the thread stop on the delivered signal (SIGUSR1 here). MacOSX debugserver does. + # But MacOSX debugserver isn't guaranteeing the thread the signal handler runs on, so currently its an XFAIL. + # Need to rectify behavior here. The linux behavior is more intuitive to me since we're essentially swapping out + # an about-to-be-delivered signal (for which we already sent a stop packet) to a different signal. + # {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }, + # "read packet: $c#63", + {"type": "output_match", "regex": r"^received SIGUSR1 on thread id: ([0-9a-fA-F]+)\r\nthread ([0-9a-fA-F]+): past SIGSEGV\r\n", "capture": {1: "print_thread_id", 2: "post_handle_thread_id"}}, + ], + True) + + # Run the sequence. + context = self.expect_gdbremote_sequence( + timeout_seconds=self._DEFAULT_TIMEOUT) + self.assertIsNotNone(context) + + # Ensure the stop signal is the signal we delivered. + # stop_signo = context.get("stop_signo") + # self.assertIsNotNone(stop_signo) + # self.assertEquals(int(stop_signo,16), lldbutil.get_signal_number('SIGUSR1')) + + # Ensure the stop thread is the thread to which we delivered the signal. + # stop_thread_id = context.get("stop_thread_id") + # self.assertIsNotNone(stop_thread_id) + # self.assertEquals(int(stop_thread_id,16), thread_id) + + # Ensure we haven't seen this thread id yet. The inferior's + # self-obtained thread ids are not guaranteed to match the stub + # tids (at least on MacOSX). + print_thread_id = context.get("print_thread_id") + self.assertIsNotNone(print_thread_id) + print_thread_id = int(print_thread_id, 16) + self.assertFalse(print_thread_id in print_thread_ids) + + # Now remember this print (i.e. inferior-reflected) thread id and + # ensure we don't hit it again. + print_thread_ids[print_thread_id] = 1 + + # Ensure post signal-handle thread id matches the thread that + # initially raised the SIGSEGV. + post_handle_thread_id = context.get("post_handle_thread_id") + self.assertIsNotNone(post_handle_thread_id) + post_handle_thread_id = int(post_handle_thread_id, 16) + self.assertEqual(post_handle_thread_id, print_thread_id) + + @unittest2.expectedFailure() + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_Hc_then_Csignal_signals_correct_thread_launch_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + # Darwin debugserver translates some signals like SIGSEGV into some gdb + # expectations about fixed signal numbers. + self.Hc_then_Csignal_signals_correct_thread(self.TARGET_EXC_BAD_ACCESS) + + @skipIfWindows # no SIGSEGV support + @expectedFailureNetBSD + @llgs_test + def test_Hc_then_Csignal_signals_correct_thread_launch_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.Hc_then_Csignal_signals_correct_thread( + lldbutil.get_signal_number('SIGSEGV')) + + def m_packet_reads_memory(self): + # This is the memory we will write into the inferior and then ensure we + # can read back with $m. + MEMORY_CONTENTS = "Test contents 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz" + + # Start up the inferior. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=[ + "set-message:%s" % + MEMORY_CONTENTS, + "get-data-address-hex:g_message", + "sleep:5"]) + + # Run the process + self.test_sequence.add_log_lines( + [ + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "message_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], + True) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Grab the message address. + self.assertIsNotNone(context.get("message_address")) + message_address = int(context.get("message_address"), 16) + + # Grab contents from the inferior. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + ["read packet: $m{0:x},{1:x}#00".format(message_address, len(MEMORY_CONTENTS)), + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "read_contents"}}], + True) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Ensure what we read from inferior memory is what we wrote. + self.assertIsNotNone(context.get("read_contents")) + read_contents = seven.unhexlify(context.get("read_contents")) + self.assertEqual(read_contents, MEMORY_CONTENTS) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_m_packet_reads_memory_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.m_packet_reads_memory() + + @skipIfWindows # No pty support to test any inferior output + @llgs_test + def test_m_packet_reads_memory_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.m_packet_reads_memory() + + def qMemoryRegionInfo_is_supported(self): + # Start up the inferior. + procs = self.prep_debug_monitor_and_inferior() + + # Ask if it supports $qMemoryRegionInfo. + self.test_sequence.add_log_lines( + ["read packet: $qMemoryRegionInfo#00", + "send packet: $OK#00" + ], True) + self.expect_gdbremote_sequence() + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qMemoryRegionInfo_is_supported_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qMemoryRegionInfo_is_supported() + + @llgs_test + def test_qMemoryRegionInfo_is_supported_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qMemoryRegionInfo_is_supported() + + def qMemoryRegionInfo_reports_code_address_as_executable(self): + # Start up the inferior. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["get-code-address-hex:hello", "sleep:5"]) + + # Run the process + self.test_sequence.add_log_lines( + [ + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "code_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], + True) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Grab the code address. + self.assertIsNotNone(context.get("code_address")) + code_address = int(context.get("code_address"), 16) + + # Grab memory region info from the inferior. + self.reset_test_sequence() + self.add_query_memory_region_packets(code_address) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + mem_region_dict = self.parse_memory_region_packet(context) + + # Ensure there are no errors reported. + self.assertFalse("error" in mem_region_dict) + + # Ensure code address is readable and executable. + self.assertTrue("permissions" in mem_region_dict) + self.assertTrue("r" in mem_region_dict["permissions"]) + self.assertTrue("x" in mem_region_dict["permissions"]) + + # Ensure the start address and size encompass the address we queried. + self.assert_address_within_memory_region(code_address, mem_region_dict) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qMemoryRegionInfo_reports_code_address_as_executable_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qMemoryRegionInfo_reports_code_address_as_executable() + + @skipIfWindows # No pty support to test any inferior output + @llgs_test + def test_qMemoryRegionInfo_reports_code_address_as_executable_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qMemoryRegionInfo_reports_code_address_as_executable() + + def qMemoryRegionInfo_reports_stack_address_as_readable_writeable(self): + # Start up the inferior. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["get-stack-address-hex:", "sleep:5"]) + + # Run the process + self.test_sequence.add_log_lines( + [ + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"stack address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "stack_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], + True) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Grab the address. + self.assertIsNotNone(context.get("stack_address")) + stack_address = int(context.get("stack_address"), 16) + + # Grab memory region info from the inferior. + self.reset_test_sequence() + self.add_query_memory_region_packets(stack_address) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + mem_region_dict = self.parse_memory_region_packet(context) + + # Ensure there are no errors reported. + self.assertFalse("error" in mem_region_dict) + + # Ensure address is readable and executable. + self.assertTrue("permissions" in mem_region_dict) + self.assertTrue("r" in mem_region_dict["permissions"]) + self.assertTrue("w" in mem_region_dict["permissions"]) + + # Ensure the start address and size encompass the address we queried. + self.assert_address_within_memory_region( + stack_address, mem_region_dict) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable() + + @skipIfWindows # No pty support to test any inferior output + @llgs_test + def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_llgs( + self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable() + + def qMemoryRegionInfo_reports_heap_address_as_readable_writeable(self): + # Start up the inferior. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["get-heap-address-hex:", "sleep:5"]) + + # Run the process + self.test_sequence.add_log_lines( + [ + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"heap address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "heap_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], + True) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Grab the address. + self.assertIsNotNone(context.get("heap_address")) + heap_address = int(context.get("heap_address"), 16) + + # Grab memory region info from the inferior. + self.reset_test_sequence() + self.add_query_memory_region_packets(heap_address) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + mem_region_dict = self.parse_memory_region_packet(context) + + # Ensure there are no errors reported. + self.assertFalse("error" in mem_region_dict) + + # Ensure address is readable and executable. + self.assertTrue("permissions" in mem_region_dict) + self.assertTrue("r" in mem_region_dict["permissions"]) + self.assertTrue("w" in mem_region_dict["permissions"]) + + # Ensure the start address and size encompass the address we queried. + self.assert_address_within_memory_region(heap_address, mem_region_dict) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_debugserver( + self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable() + + @skipIfWindows # No pty support to test any inferior output + @llgs_test + def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_llgs( + self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable() + + def breakpoint_set_and_remove_work(self, want_hardware=False): + # Start up the inferior. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=[ + "get-code-address-hex:hello", + "sleep:1", + "call-function:hello"]) + + # Run the process + self.add_register_info_collection_packets() + self.add_process_info_collection_packets() + self.test_sequence.add_log_lines( + [ # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the function call entry point. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "function_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], + True) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather process info - we need endian of target to handle register + # value conversions. + process_info = self.parse_process_info_response(context) + endian = process_info.get("endian") + self.assertIsNotNone(endian) + + # Gather register info entries. + reg_infos = self.parse_register_info_packets(context) + (pc_lldb_reg_index, pc_reg_info) = self.find_pc_reg_info(reg_infos) + self.assertIsNotNone(pc_lldb_reg_index) + self.assertIsNotNone(pc_reg_info) + + # Grab the function address. + self.assertIsNotNone(context.get("function_address")) + function_address = int(context.get("function_address"), 16) + + # Get current target architecture + target_arch = self.getArchitecture() + + # Set the breakpoint. + if (target_arch == "arm") or (target_arch == "aarch64"): + # TODO: Handle case when setting breakpoint in thumb code + BREAKPOINT_KIND = 4 + else: + BREAKPOINT_KIND = 1 + + # Set default packet type to Z0 (software breakpoint) + z_packet_type = 0 + + # If hardware breakpoint is requested set packet type to Z1 + if want_hardware == True: + z_packet_type = 1 + + self.reset_test_sequence() + self.add_set_breakpoint_packets( + function_address, + z_packet_type, + do_continue=True, + breakpoint_kind=BREAKPOINT_KIND) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Verify the stop signal reported was the breakpoint signal number. + stop_signo = context.get("stop_signo") + self.assertIsNotNone(stop_signo) + self.assertEqual(int(stop_signo, 16), + lldbutil.get_signal_number('SIGTRAP')) + + # Ensure we did not receive any output. If the breakpoint was not set, we would + # see output (from a launched process with captured stdio) printing a hello, world message. + # That would indicate the breakpoint didn't take. + self.assertEqual(len(context["O_content"]), 0) + + # Verify that the PC for the main thread is where we expect it - right at the breakpoint address. + # This acts as a another validation on the register reading code. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + # Print the PC. This should match the breakpoint address. + "read packet: $p{0:x}#00".format(pc_lldb_reg_index), + # Capture $p results. + {"direction": "send", + "regex": r"^\$([0-9a-fA-F]+)#", + "capture": {1: "p_response"}}, + ], True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Verify the PC is where we expect. Note response is in endianness of + # the inferior. + p_response = context.get("p_response") + self.assertIsNotNone(p_response) + + # Convert from target endian to int. + returned_pc = lldbgdbserverutils.unpack_register_hex_unsigned( + endian, p_response) + self.assertEqual(returned_pc, function_address) + + # Verify that a breakpoint remove and continue gets us the expected + # output. + self.reset_test_sequence() + + # Add breakpoint remove packets + self.add_remove_breakpoint_packets( + function_address, + z_packet_type, + breakpoint_kind=BREAKPOINT_KIND) + + self.test_sequence.add_log_lines( + [ + # Continue running. + "read packet: $c#63", + # We should now receive the output from the call. + {"type": "output_match", "regex": r"^hello, world\r\n$"}, + # And wait for program completion. + {"direction": "send", "regex": r"^\$W00(.*)#[0-9a-fA-F]{2}$"}, + ], True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_software_breakpoint_set_and_remove_work_debugserver(self): + self.init_debugserver_test() + if self.getArchitecture() == "arm": + # TODO: Handle case when setting breakpoint in thumb code + self.build(dictionary={'CFLAGS_EXTRAS': '-marm'}) + else: + self.build() + self.set_inferior_startup_launch() + self.breakpoint_set_and_remove_work(want_hardware=False) + + @skipIfWindows # No pty support to test any inferior output + @llgs_test + @expectedFlakeyLinux("llvm.org/pr25652") + def test_software_breakpoint_set_and_remove_work_llgs(self): + self.init_llgs_test() + if self.getArchitecture() == "arm": + # TODO: Handle case when setting breakpoint in thumb code + self.build(dictionary={'CFLAGS_EXTRAS': '-marm'}) + else: + self.build() + self.set_inferior_startup_launch() + self.breakpoint_set_and_remove_work(want_hardware=False) + + @debugserver_test + @skipUnlessPlatform(oslist=['linux']) + @expectedFailureAndroid + @skipIf(archs=no_match(['arm', 'aarch64'])) + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_hardware_breakpoint_set_and_remove_work_debugserver(self): + self.init_debugserver_test() + if self.getArchitecture() == "arm": + # TODO: Handle case when setting breakpoint in thumb code + self.build(dictionary={'CFLAGS_EXTRAS': '-marm'}) + else: + self.build() + self.set_inferior_startup_launch() + self.breakpoint_set_and_remove_work(want_hardware=True) + + @llgs_test + @skipUnlessPlatform(oslist=['linux']) + @skipIf(archs=no_match(['arm', 'aarch64'])) + def test_hardware_breakpoint_set_and_remove_work_llgs(self): + self.init_llgs_test() + if self.getArchitecture() == "arm": + # TODO: Handle case when setting breakpoint in thumb code + self.build(dictionary={'CFLAGS_EXTRAS': '-marm'}) + else: + self.build() + self.set_inferior_startup_launch() + self.breakpoint_set_and_remove_work(want_hardware=True) + + def qSupported_returns_known_stub_features(self): + # Start up the stub and start/prep the inferior. + procs = self.prep_debug_monitor_and_inferior() + self.add_qSupported_packets() + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Retrieve the qSupported features. + supported_dict = self.parse_qSupported_response(context) + self.assertIsNotNone(supported_dict) + self.assertTrue(len(supported_dict) > 0) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_qSupported_returns_known_stub_features_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.qSupported_returns_known_stub_features() + + @llgs_test + def test_qSupported_returns_known_stub_features_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.qSupported_returns_known_stub_features() + + def written_M_content_reads_back_correctly(self): + TEST_MESSAGE = "Hello, memory" + + # Start up the stub and start/prep the inferior. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=[ + "set-message:xxxxxxxxxxxxxX", + "get-data-address-hex:g_message", + "sleep:1", + "print-message:"]) + self.test_sequence.add_log_lines( + [ + # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the message buffer within the inferior. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"), + "capture": {1: "message_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Grab the message address. + self.assertIsNotNone(context.get("message_address")) + message_address = int(context.get("message_address"), 16) + + # Hex-encode the test message, adding null termination. + hex_encoded_message = seven.hexlify(TEST_MESSAGE) + + # Write the message to the inferior. Verify that we can read it with the hex-encoded (m) + # and binary (x) memory read packets. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + ["read packet: $M{0:x},{1:x}:{2}#00".format(message_address, len(TEST_MESSAGE), hex_encoded_message), + "send packet: $OK#00", + "read packet: $m{0:x},{1:x}#00".format(message_address, len(TEST_MESSAGE)), + "send packet: ${0}#00".format(hex_encoded_message), + "read packet: $x{0:x},{1:x}#00".format(message_address, len(TEST_MESSAGE)), + "send packet: ${0}#00".format(TEST_MESSAGE), + "read packet: $m{0:x},4#00".format(message_address), + "send packet: ${0}#00".format(hex_encoded_message[0:8]), + "read packet: $x{0:x},4#00".format(message_address), + "send packet: ${0}#00".format(TEST_MESSAGE[0:4]), + "read packet: $c#63", + {"type": "output_match", "regex": r"^message: (.+)\r\n$", "capture": {1: "printed_message"}}, + "send packet: $W00#00", + ], True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Ensure what we read from inferior memory is what we wrote. + printed_message = context.get("printed_message") + self.assertIsNotNone(printed_message) + self.assertEqual(printed_message, TEST_MESSAGE + "X") + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_written_M_content_reads_back_correctly_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.written_M_content_reads_back_correctly() + + @skipIfWindows # No pty support to test any inferior output + @llgs_test + @expectedFlakeyLinux("llvm.org/pr25652") + def test_written_M_content_reads_back_correctly_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.written_M_content_reads_back_correctly() + + def P_writes_all_gpr_registers(self): + # Start inferior debug session, grab all register info. + procs = self.prep_debug_monitor_and_inferior(inferior_args=["sleep:2"]) + self.add_register_info_collection_packets() + self.add_process_info_collection_packets() + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Process register infos. + reg_infos = self.parse_register_info_packets(context) + self.assertIsNotNone(reg_infos) + self.add_lldb_register_index(reg_infos) + + # Process endian. + process_info = self.parse_process_info_response(context) + endian = process_info.get("endian") + self.assertIsNotNone(endian) + + # Pull out the register infos that we think we can bit flip + # successfully,. + gpr_reg_infos = [ + reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)] + self.assertTrue(len(gpr_reg_infos) > 0) + + # Write flipped bit pattern of existing value to each register. + (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value( + gpr_reg_infos, endian) + # print("successful writes: {}, failed writes: {}".format(successful_writes, failed_writes)) + self.assertTrue(successful_writes > 0) + + # Note: as of this moment, a hefty number of the GPR writes are failing with E32 (everything except rax-rdx, rdi, rsi, rbp). + # Come back to this. I have the test rigged to verify that at least some + # of the bit-flip writes work. + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_P_writes_all_gpr_registers_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.P_writes_all_gpr_registers() + + @llgs_test + def test_P_writes_all_gpr_registers_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.P_writes_all_gpr_registers() + + def P_and_p_thread_suffix_work(self): + # Startup the inferior with three threads. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["thread:new", "thread:new"]) + self.add_thread_suffix_request_packets() + self.add_register_info_collection_packets() + self.add_process_info_collection_packets() + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + process_info = self.parse_process_info_response(context) + self.assertIsNotNone(process_info) + endian = process_info.get("endian") + self.assertIsNotNone(endian) + + reg_infos = self.parse_register_info_packets(context) + self.assertIsNotNone(reg_infos) + self.add_lldb_register_index(reg_infos) + + reg_index = self.select_modifiable_register(reg_infos) + self.assertIsNotNone(reg_index) + reg_byte_size = int(reg_infos[reg_index]["bitsize"]) // 8 + self.assertTrue(reg_byte_size > 0) + + # Run the process a bit so threads can start up, and collect register + # info. + context = self.run_process_then_stop(run_seconds=1) + self.assertIsNotNone(context) + + # Wait for 3 threads to be present. + threads = self.wait_for_thread_count(3, timeout_seconds=self._WAIT_TIMEOUT) + self.assertEqual(len(threads), 3) + + expected_reg_values = [] + register_increment = 1 + next_value = None + + # Set the same register in each of 3 threads to a different value. + # Verify each one has the unique value. + for thread in threads: + # If we don't have a next value yet, start it with the initial read + # value + 1 + if not next_value: + # Read pre-existing register value. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread), + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Set the next value to use for writing as the increment plus + # current value. + p_response = context.get("p_response") + self.assertIsNotNone(p_response) + next_value = lldbgdbserverutils.unpack_register_hex_unsigned( + endian, p_response) + + # Set new value using P and thread suffix. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + "read packet: $P{0:x}={1};thread:{2:x}#00".format( + reg_index, + lldbgdbserverutils.pack_register_hex( + endian, + next_value, + byte_size=reg_byte_size), + thread), + "send packet: $OK#00", + ], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Save the value we set. + expected_reg_values.append(next_value) + + # Increment value for next thread to use (we want them all + # different so we can verify they wrote to each thread correctly + # next.) + next_value += register_increment + + # Revisit each thread and verify they have the expected value set for + # the register we wrote. + thread_index = 0 + for thread in threads: + # Read pre-existing register value. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread), + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Get the register value. + p_response = context.get("p_response") + self.assertIsNotNone(p_response) + read_value = lldbgdbserverutils.unpack_register_hex_unsigned( + endian, p_response) + + # Make sure we read back what we wrote. + self.assertEqual(read_value, expected_reg_values[thread_index]) + thread_index += 1 + + # Note: as of this moment, a hefty number of the GPR writes are failing + # with E32 (everything except rax-rdx, rdi, rsi, rbp). + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_P_and_p_thread_suffix_work_debugserver(self): + self.init_debugserver_test() + self.build() + self.set_inferior_startup_launch() + self.P_and_p_thread_suffix_work() + + @skipIfWindows + @llgs_test + def test_P_and_p_thread_suffix_work_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.P_and_p_thread_suffix_work() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py new file mode 100644 index 00000000000..664b6001d8d --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py @@ -0,0 +1,97 @@ +from __future__ import print_function + +import gdbremote_testcase +import lldbgdbserverutils +import re +import select +import socket +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestStubReverseConnect(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + _DEFAULT_TIMEOUT = 20 * (10 if ('ASAN_OPTIONS' in os.environ) else 1) + + def setUp(self): + # Set up the test. + gdbremote_testcase.GdbRemoteTestCaseBase.setUp(self) + + # Create a listener on a local port. + self.listener_socket = self.create_listener_socket() + self.assertIsNotNone(self.listener_socket) + self.listener_port = self.listener_socket.getsockname()[1] + + def create_listener_socket(self, timeout_seconds=_DEFAULT_TIMEOUT): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.assertIsNotNone(sock) + + sock.settimeout(timeout_seconds) + sock.bind(("127.0.0.1", 0)) + sock.listen(1) + + def tear_down_listener(): + try: + sock.shutdown(socket.SHUT_RDWR) + except: + # ignore + None + + self.addTearDownHook(tear_down_listener) + return sock + + def reverse_connect_works(self): + # Indicate stub startup should do a reverse connect. + appended_stub_args = ["--reverse-connect"] + if self.debug_monitor_extra_args: + self.debug_monitor_extra_args += appended_stub_args + else: + self.debug_monitor_extra_args = appended_stub_args + + self.stub_hostname = "127.0.0.1" + self.port = self.listener_port + + triple = self.dbg.GetSelectedPlatform().GetTriple() + if re.match(".*-.*-.*-android", triple): + self.forward_adb_port( + self.port, + self.port, + "reverse", + self.stub_device) + + # Start the stub. + server = self.launch_debug_monitor(logfile=sys.stdout) + self.assertIsNotNone(server) + self.assertTrue( + lldbgdbserverutils.process_is_running( + server.pid, True)) + + # Listen for the stub's connection to us. + (stub_socket, address) = self.listener_socket.accept() + self.assertIsNotNone(stub_socket) + self.assertIsNotNone(address) + print("connected to stub {} on {}".format( + address, stub_socket.getsockname())) + + # Verify we can do the handshake. If that works, we'll call it good. + self.do_handshake(stub_socket, timeout_seconds=self._DEFAULT_TIMEOUT) + + # Clean up. + stub_socket.shutdown(socket.SHUT_RDWR) + + @debugserver_test + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def test_reverse_connect_works_debugserver(self): + self.init_debugserver_test(use_named_pipe=False) + self.set_inferior_startup_launch() + self.reverse_connect_works() + + @llgs_test + @skipIfRemote # reverse connect is not a supported use case for now + def test_reverse_connect_works_llgs(self): + self.init_llgs_test(use_named_pipe=False) + self.set_inferior_startup_launch() + self.reverse_connect_works() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py new file mode 100644 index 00000000000..4641b175bca --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py @@ -0,0 +1,86 @@ + + +import gdbremote_testcase +import lldbgdbserverutils +import os +import select +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestStubSetSIDTestCase(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def get_stub_sid(self, extra_stub_args=None): + # Launch debugserver + if extra_stub_args: + self.debug_monitor_extra_args += extra_stub_args + + server = self.launch_debug_monitor() + self.assertIsNotNone(server) + self.assertTrue( + lldbgdbserverutils.process_is_running( + server.pid, True)) + + # Get the process id for the stub. + return os.getsid(server.pid) + + def sid_is_same_without_setsid(self): + stub_sid = self.get_stub_sid() + self.assertEqual(stub_sid, os.getsid(0)) + + def sid_is_different_with_setsid(self): + stub_sid = self.get_stub_sid(["--setsid"]) + self.assertNotEqual(stub_sid, os.getsid(0)) + + def sid_is_different_with_S(self): + stub_sid = self.get_stub_sid(["-S"]) + self.assertNotEqual(stub_sid, os.getsid(0)) + + @debugserver_test + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + def test_sid_is_same_without_setsid_debugserver(self): + self.init_debugserver_test() + self.set_inferior_startup_launch() + self.sid_is_same_without_setsid() + + @skipIfWindows + @llgs_test + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + @expectedFailureAll(oslist=['freebsd']) + def test_sid_is_same_without_setsid_llgs(self): + self.init_llgs_test() + self.set_inferior_startup_launch() + self.sid_is_same_without_setsid() + + @debugserver_test + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + def test_sid_is_different_with_setsid_debugserver(self): + self.init_debugserver_test() + self.set_inferior_startup_launch() + self.sid_is_different_with_setsid() + + @skipIfWindows + @llgs_test + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + def test_sid_is_different_with_setsid_llgs(self): + self.init_llgs_test() + self.set_inferior_startup_launch() + self.sid_is_different_with_setsid() + + @debugserver_test + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + def test_sid_is_different_with_S_debugserver(self): + self.init_debugserver_test() + self.set_inferior_startup_launch() + self.sid_is_different_with_S() + + @skipIfWindows + @llgs_test + @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target + def test_sid_is_different_with_S_llgs(self): + self.init_llgs_test() + self.set_inferior_startup_launch() + self.sid_is_different_with_S() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py new file mode 100644 index 00000000000..ac611bcca16 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py @@ -0,0 +1,1684 @@ +""" +Base class for gdb-remote test cases. +""" + +from __future__ import division, print_function + + +import errno +import os +import os.path +import random +import re +import select +import socket +import subprocess +import sys +import tempfile +import time +from lldbsuite.test import configuration +from lldbsuite.test.lldbtest import * +from lldbsuite.support import seven +from lldbgdbserverutils import * +import logging + + +class _ConnectionRefused(IOError): + pass + + +class GdbRemoteTestCaseBase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + + _TIMEOUT_SECONDS = 120 * (10 if ('ASAN_OPTIONS' in os.environ) else 1) + _DEFAULT_TIMEOUT = 10 * (10 if ('ASAN_OPTIONS' in os.environ) else 1) + _READ_TIMEOUT = 5 * (10 if ('ASAN_OPTIONS' in os.environ) else 1) + _WAIT_TIMEOUT = 5 * (10 if ('ASAN_OPTIONS' in os.environ) else 1) + + _GDBREMOTE_KILL_PACKET = "$k#6b" + + # Start the inferior separately, attach to the inferior on the stub + # command line. + _STARTUP_ATTACH = "attach" + # Start the inferior separately, start the stub without attaching, allow + # the test to attach to the inferior however it wants (e.g. $vAttach;pid). + _STARTUP_ATTACH_MANUALLY = "attach_manually" + # Start the stub, and launch the inferior with an $A packet via the + # initial packet stream. + _STARTUP_LAUNCH = "launch" + + # GDB Signal numbers that are not target-specific used for common + # exceptions + TARGET_EXC_BAD_ACCESS = 0x91 + TARGET_EXC_BAD_INSTRUCTION = 0x92 + TARGET_EXC_ARITHMETIC = 0x93 + TARGET_EXC_EMULATION = 0x94 + TARGET_EXC_SOFTWARE = 0x95 + TARGET_EXC_BREAKPOINT = 0x96 + + _verbose_log_handler = None + _log_formatter = logging.Formatter( + fmt='%(asctime)-15s %(levelname)-8s %(message)s') + + def setUpBaseLogging(self): + self.logger = logging.getLogger(__name__) + + if len(self.logger.handlers) > 0: + return # We have set up this handler already + + self.logger.propagate = False + self.logger.setLevel(logging.DEBUG) + + # log all warnings to stderr + handler = logging.StreamHandler() + handler.setLevel(logging.WARNING) + handler.setFormatter(self._log_formatter) + self.logger.addHandler(handler) + + def isVerboseLoggingRequested(self): + # We will report our detailed logs if the user requested that the "gdb-remote" channel is + # logged. + return any(("gdb-remote" in channel) + for channel in lldbtest_config.channels) + + def setUp(self): + TestBase.setUp(self) + + self.setUpBaseLogging() + self.debug_monitor_extra_args = [] + self._pump_queues = socket_packet_pump.PumpQueues() + + if self.isVerboseLoggingRequested(): + # If requested, full logs go to a log file + self._verbose_log_handler = logging.FileHandler( + self.log_basename + "-host.log") + self._verbose_log_handler.setFormatter(self._log_formatter) + self._verbose_log_handler.setLevel(logging.DEBUG) + self.logger.addHandler(self._verbose_log_handler) + + self.test_sequence = GdbRemoteTestSequence(self.logger) + self.set_inferior_startup_launch() + self.port = self.get_next_port() + self.named_pipe_path = None + self.named_pipe = None + self.named_pipe_fd = None + self.stub_sends_two_stop_notifications_on_kill = False + if configuration.lldb_platform_url: + if configuration.lldb_platform_url.startswith('unix-'): + url_pattern = '(.+)://\[?(.+?)\]?/.*' + else: + url_pattern = '(.+)://(.+):\d+' + scheme, host = re.match( + url_pattern, configuration.lldb_platform_url).groups() + if configuration.lldb_platform_name == 'remote-android' and host != 'localhost': + self.stub_device = host + self.stub_hostname = 'localhost' + else: + self.stub_device = None + self.stub_hostname = host + else: + self.stub_hostname = "localhost" + + def tearDown(self): + self._pump_queues.verify_queues_empty() + + self.logger.removeHandler(self._verbose_log_handler) + self._verbose_log_handler = None + TestBase.tearDown(self) + + def getLocalServerLogFile(self): + return self.log_basename + "-server.log" + + def setUpServerLogging(self, is_llgs): + if len(lldbtest_config.channels) == 0: + return # No logging requested + + if lldb.remote_platform: + log_file = lldbutil.join_remote_paths( + lldb.remote_platform.GetWorkingDirectory(), "server.log") + else: + log_file = self.getLocalServerLogFile() + + if is_llgs: + self.debug_monitor_extra_args.append("--log-file=" + log_file) + self.debug_monitor_extra_args.append( + "--log-channels={}".format(":".join(lldbtest_config.channels))) + else: + self.debug_monitor_extra_args = [ + "--log-file=" + log_file, "--log-flags=0x800000"] + + def get_next_port(self): + return 12000 + random.randint(0, 3999) + + def reset_test_sequence(self): + self.test_sequence = GdbRemoteTestSequence(self.logger) + + def create_named_pipe(self): + # Create a temp dir and name for a pipe. + temp_dir = tempfile.mkdtemp() + named_pipe_path = os.path.join(temp_dir, "stub_port_number") + + # Create the named pipe. + os.mkfifo(named_pipe_path) + + # Open the read side of the pipe in non-blocking mode. This will + # return right away, ready or not. + named_pipe_fd = os.open(named_pipe_path, os.O_RDONLY | os.O_NONBLOCK) + + # Create the file for the named pipe. Note this will follow semantics of + # a non-blocking read side of a named pipe, which has different semantics + # than a named pipe opened for read in non-blocking mode. + named_pipe = os.fdopen(named_pipe_fd, "r") + self.assertIsNotNone(named_pipe) + + def shutdown_named_pipe(): + # Close the pipe. + try: + named_pipe.close() + except: + print("failed to close named pipe") + None + + # Delete the pipe. + try: + os.remove(named_pipe_path) + except: + print("failed to delete named pipe: {}".format(named_pipe_path)) + None + + # Delete the temp directory. + try: + os.rmdir(temp_dir) + except: + print( + "failed to delete temp dir: {}, directory contents: '{}'".format( + temp_dir, os.listdir(temp_dir))) + None + + # Add the shutdown hook to clean up the named pipe. + self.addTearDownHook(shutdown_named_pipe) + + # Clear the port so the stub selects a port number. + self.port = 0 + + return (named_pipe_path, named_pipe, named_pipe_fd) + + def get_stub_port_from_named_socket(self, read_timeout_seconds): + # Wait for something to read with a max timeout. + (ready_readers, _, _) = select.select( + [self.named_pipe_fd], [], [], read_timeout_seconds) + self.assertIsNotNone( + ready_readers, + "write side of pipe has not written anything - stub isn't writing to pipe.") + self.assertNotEqual( + len(ready_readers), + 0, + "write side of pipe has not written anything - stub isn't writing to pipe.") + + # Read the port from the named pipe. + stub_port_raw = self.named_pipe.read() + self.assertIsNotNone(stub_port_raw) + self.assertNotEqual( + len(stub_port_raw), + 0, + "no content to read on pipe") + + # Trim null byte, convert to int. + stub_port_raw = stub_port_raw[:-1] + stub_port = int(stub_port_raw) + self.assertTrue(stub_port > 0) + + return stub_port + + def init_llgs_test(self, use_named_pipe=True): + if lldb.remote_platform: + # Remote platforms don't support named pipe based port negotiation + use_named_pipe = False + + triple = self.dbg.GetSelectedPlatform().GetTriple() + if re.match(".*-.*-windows", triple): + self.skipTest("Remotely testing is not supported on Windows yet.") + + # Grab the ppid from /proc/[shell pid]/stat + err, retcode, shell_stat = self.run_platform_command( + "cat /proc/$$/stat") + self.assertTrue( + err.Success() and retcode == 0, + "Failed to read file /proc/$$/stat: %s, retcode: %d" % + (err.GetCString(), + retcode)) + + # [pid] ([executable]) [state] [*ppid*] + pid = re.match(r"^\d+ \(.+\) . (\d+)", shell_stat).group(1) + err, retcode, ls_output = self.run_platform_command( + "ls -l /proc/%s/exe" % pid) + self.assertTrue( + err.Success() and retcode == 0, + "Failed to read file /proc/%s/exe: %s, retcode: %d" % + (pid, + err.GetCString(), + retcode)) + exe = ls_output.split()[-1] + + # If the binary has been deleted, the link name has " (deleted)" appended. + # Remove if it's there. + self.debug_monitor_exe = re.sub(r' \(deleted\)$', '', exe) + else: + # Need to figure out how to create a named pipe on Windows. + if platform.system() == 'Windows': + use_named_pipe = False + + self.debug_monitor_exe = get_lldb_server_exe() + if not self.debug_monitor_exe: + self.skipTest("lldb-server exe not found") + + self.debug_monitor_extra_args = ["gdbserver"] + self.setUpServerLogging(is_llgs=True) + + if use_named_pipe: + (self.named_pipe_path, self.named_pipe, + self.named_pipe_fd) = self.create_named_pipe() + + def init_debugserver_test(self, use_named_pipe=True): + self.debug_monitor_exe = get_debugserver_exe() + if not self.debug_monitor_exe: + self.skipTest("debugserver exe not found") + self.setUpServerLogging(is_llgs=False) + if use_named_pipe: + (self.named_pipe_path, self.named_pipe, + self.named_pipe_fd) = self.create_named_pipe() + # The debugserver stub has a race on handling the 'k' command, so it sends an X09 right away, then sends the real X notification + # when the process truly dies. + self.stub_sends_two_stop_notifications_on_kill = True + + def forward_adb_port(self, source, target, direction, device): + adb = ['adb'] + (['-s', device] if device else []) + [direction] + + def remove_port_forward(): + subprocess.call(adb + ["--remove", "tcp:%d" % source]) + + subprocess.call(adb + ["tcp:%d" % source, "tcp:%d" % target]) + self.addTearDownHook(remove_port_forward) + + def _verify_socket(self, sock): + # Normally, when the remote stub is not ready, we will get ECONNREFUSED during the + # connect() attempt. However, due to the way how ADB forwarding works, on android targets + # the connect() will always be successful, but the connection will be immediately dropped + # if ADB could not connect on the remote side. This function tries to detect this + # situation, and report it as "connection refused" so that the upper layers attempt the + # connection again. + triple = self.dbg.GetSelectedPlatform().GetTriple() + if not re.match(".*-.*-.*-android", triple): + return # Not android. + can_read, _, _ = select.select([sock], [], [], 0.1) + if sock not in can_read: + return # Data is not available, but the connection is alive. + if len(sock.recv(1, socket.MSG_PEEK)) == 0: + raise _ConnectionRefused() # Got EOF, connection dropped. + + def create_socket(self): + sock = socket.socket() + logger = self.logger + + triple = self.dbg.GetSelectedPlatform().GetTriple() + if re.match(".*-.*-.*-android", triple): + self.forward_adb_port( + self.port, + self.port, + "forward", + self.stub_device) + + logger.info( + "Connecting to debug monitor on %s:%d", + self.stub_hostname, + self.port) + connect_info = (self.stub_hostname, self.port) + try: + sock.connect(connect_info) + except socket.error as serr: + if serr.errno == errno.ECONNREFUSED: + raise _ConnectionRefused() + raise serr + + def shutdown_socket(): + if sock: + try: + # send the kill packet so lldb-server shuts down gracefully + sock.sendall(GdbRemoteTestCaseBase._GDBREMOTE_KILL_PACKET) + except: + logger.warning( + "failed to send kill packet to debug monitor: {}; ignoring".format( + sys.exc_info()[0])) + + try: + sock.close() + except: + logger.warning( + "failed to close socket to debug monitor: {}; ignoring".format( + sys.exc_info()[0])) + + self.addTearDownHook(shutdown_socket) + + self._verify_socket(sock) + + return sock + + def set_inferior_startup_launch(self): + self._inferior_startup = self._STARTUP_LAUNCH + + def set_inferior_startup_attach(self): + self._inferior_startup = self._STARTUP_ATTACH + + def set_inferior_startup_attach_manually(self): + self._inferior_startup = self._STARTUP_ATTACH_MANUALLY + + def get_debug_monitor_command_line_args(self, attach_pid=None): + if lldb.remote_platform: + commandline_args = self.debug_monitor_extra_args + \ + ["*:{}".format(self.port)] + else: + commandline_args = self.debug_monitor_extra_args + \ + ["127.0.0.1:{}".format(self.port)] + + if attach_pid: + commandline_args += ["--attach=%d" % attach_pid] + if self.named_pipe_path: + commandline_args += ["--named-pipe", self.named_pipe_path] + return commandline_args + + def get_target_byte_order(self): + inferior_exe_path = self.getBuildArtifact("a.out") + target = self.dbg.CreateTarget(inferior_exe_path) + return target.GetByteOrder() + + def launch_debug_monitor(self, attach_pid=None, logfile=None): + # Create the command line. + commandline_args = self.get_debug_monitor_command_line_args( + attach_pid=attach_pid) + + # Start the server. + server = self.spawnSubprocess( + self.debug_monitor_exe, + commandline_args, + install_remote=False) + self.addTearDownHook(self.cleanupSubprocesses) + self.assertIsNotNone(server) + + # If we're receiving the stub's listening port from the named pipe, do + # that here. + if self.named_pipe: + self.port = self.get_stub_port_from_named_socket(self._READ_TIMEOUT) + + return server + + def connect_to_debug_monitor(self, attach_pid=None): + if self.named_pipe: + # Create the stub. + server = self.launch_debug_monitor(attach_pid=attach_pid) + self.assertIsNotNone(server) + + def shutdown_debug_monitor(): + try: + server.terminate() + except: + logger.warning( + "failed to terminate server for debug monitor: {}; ignoring".format( + sys.exc_info()[0])) + self.addTearDownHook(shutdown_debug_monitor) + + # Schedule debug monitor to be shut down during teardown. + logger = self.logger + + # Attach to the stub and return a socket opened to it. + self.sock = self.create_socket() + return server + + # We're using a random port algorithm to try not to collide with other ports, + # and retry a max # times. + attempts = 0 + MAX_ATTEMPTS = 20 + + while attempts < MAX_ATTEMPTS: + server = self.launch_debug_monitor(attach_pid=attach_pid) + + # Schedule debug monitor to be shut down during teardown. + logger = self.logger + + def shutdown_debug_monitor(): + try: + server.terminate() + except: + logger.warning( + "failed to terminate server for debug monitor: {}; ignoring".format( + sys.exc_info()[0])) + self.addTearDownHook(shutdown_debug_monitor) + + connect_attemps = 0 + MAX_CONNECT_ATTEMPTS = 10 + + while connect_attemps < MAX_CONNECT_ATTEMPTS: + # Create a socket to talk to the server + try: + logger.info("Connect attempt %d", connect_attemps + 1) + self.sock = self.create_socket() + return server + except _ConnectionRefused as serr: + # Ignore, and try again. + pass + time.sleep(0.5) + connect_attemps += 1 + + # We should close the server here to be safe. + server.terminate() + + # Increment attempts. + print( + "connect to debug monitor on port %d failed, attempt #%d of %d" % + (self.port, attempts + 1, MAX_ATTEMPTS)) + attempts += 1 + + # And wait a random length of time before next attempt, to avoid + # collisions. + time.sleep(random.randint(1, 5)) + + # Now grab a new port number. + self.port = self.get_next_port() + + raise Exception( + "failed to create a socket to the launched debug monitor after %d tries" % + attempts) + + def launch_process_for_attach( + self, + inferior_args=None, + sleep_seconds=3, + exe_path=None): + # We're going to start a child process that the debug monitor stub can later attach to. + # This process needs to be started so that it just hangs around for a while. We'll + # have it sleep. + if not exe_path: + exe_path = self.getBuildArtifact("a.out") + + args = [] + if inferior_args: + args.extend(inferior_args) + if sleep_seconds: + args.append("sleep:%d" % sleep_seconds) + + inferior = self.spawnSubprocess(exe_path, args) + + def shutdown_process_for_attach(): + try: + inferior.terminate() + except: + logger.warning( + "failed to terminate inferior process for attach: {}; ignoring".format( + sys.exc_info()[0])) + self.addTearDownHook(shutdown_process_for_attach) + return inferior + + def prep_debug_monitor_and_inferior( + self, + inferior_args=None, + inferior_sleep_seconds=3, + inferior_exe_path=None, + inferior_env=None): + """Prep the debug monitor, the inferior, and the expected packet stream. + + Handle the separate cases of using the debug monitor in attach-to-inferior mode + and in launch-inferior mode. + + For attach-to-inferior mode, the inferior process is first started, then + the debug monitor is started in attach to pid mode (using --attach on the + stub command line), and the no-ack-mode setup is appended to the packet + stream. The packet stream is not yet executed, ready to have more expected + packet entries added to it. + + For launch-inferior mode, the stub is first started, then no ack mode is + setup on the expected packet stream, then the verified launch packets are added + to the expected socket stream. The packet stream is not yet executed, ready + to have more expected packet entries added to it. + + The return value is: + {inferior:<inferior>, server:<server>} + """ + inferior = None + attach_pid = None + + if self._inferior_startup == self._STARTUP_ATTACH or self._inferior_startup == self._STARTUP_ATTACH_MANUALLY: + # Launch the process that we'll use as the inferior. + inferior = self.launch_process_for_attach( + inferior_args=inferior_args, + sleep_seconds=inferior_sleep_seconds, + exe_path=inferior_exe_path) + self.assertIsNotNone(inferior) + self.assertTrue(inferior.pid > 0) + if self._inferior_startup == self._STARTUP_ATTACH: + # In this case, we want the stub to attach via the command + # line, so set the command line attach pid here. + attach_pid = inferior.pid + + if self._inferior_startup == self._STARTUP_LAUNCH: + # Build launch args + if not inferior_exe_path: + inferior_exe_path = self.getBuildArtifact("a.out") + + if lldb.remote_platform: + remote_path = lldbutil.append_to_process_working_directory(self, + os.path.basename(inferior_exe_path)) + remote_file_spec = lldb.SBFileSpec(remote_path, False) + err = lldb.remote_platform.Install(lldb.SBFileSpec( + inferior_exe_path, True), remote_file_spec) + if err.Fail(): + raise Exception( + "remote_platform.Install('%s', '%s') failed: %s" % + (inferior_exe_path, remote_path, err)) + inferior_exe_path = remote_path + + launch_args = [inferior_exe_path] + if inferior_args: + launch_args.extend(inferior_args) + + # Launch the debug monitor stub, attaching to the inferior. + server = self.connect_to_debug_monitor(attach_pid=attach_pid) + self.assertIsNotNone(server) + + # Build the expected protocol stream + self.add_no_ack_remote_stream() + if inferior_env: + for name, value in inferior_env.items(): + self.add_set_environment_packets(name, value) + if self._inferior_startup == self._STARTUP_LAUNCH: + self.add_verified_launch_packets(launch_args) + + return {"inferior": inferior, "server": server} + + def expect_socket_recv( + self, + sock, + expected_content_regex, + timeout_seconds): + response = "" + timeout_time = time.time() + timeout_seconds + + while not expected_content_regex.match( + response) and time.time() < timeout_time: + can_read, _, _ = select.select([sock], [], [], timeout_seconds) + if can_read and sock in can_read: + recv_bytes = sock.recv(4096) + if recv_bytes: + response += seven.bitcast_to_string(recv_bytes) + + self.assertTrue(expected_content_regex.match(response)) + + def expect_socket_send(self, sock, content, timeout_seconds): + request_bytes_remaining = content + timeout_time = time.time() + timeout_seconds + + while len(request_bytes_remaining) > 0 and time.time() < timeout_time: + _, can_write, _ = select.select([], [sock], [], timeout_seconds) + if can_write and sock in can_write: + written_byte_count = sock.send(request_bytes_remaining.encode()) + request_bytes_remaining = request_bytes_remaining[ + written_byte_count:] + self.assertEqual(len(request_bytes_remaining), 0) + + def do_handshake(self, stub_socket, timeout_seconds=None): + if not timeout_seconds: + timeout_seconds = self._WAIT_TIMEOUT + + # Write the ack. + self.expect_socket_send(stub_socket, "+", timeout_seconds) + + # Send the start no ack mode packet. + NO_ACK_MODE_REQUEST = "$QStartNoAckMode#b0" + bytes_sent = stub_socket.send(NO_ACK_MODE_REQUEST.encode()) + self.assertEqual(bytes_sent, len(NO_ACK_MODE_REQUEST)) + + # Receive the ack and "OK" + self.expect_socket_recv(stub_socket, re.compile( + r"^\+\$OK#[0-9a-fA-F]{2}$"), timeout_seconds) + + # Send the final ack. + self.expect_socket_send(stub_socket, "+", timeout_seconds) + + def add_no_ack_remote_stream(self): + self.test_sequence.add_log_lines( + ["read packet: +", + "read packet: $QStartNoAckMode#b0", + "send packet: +", + "send packet: $OK#9a", + "read packet: +"], + True) + + def add_verified_launch_packets(self, launch_args): + self.test_sequence.add_log_lines( + ["read packet: %s" % build_gdbremote_A_packet(launch_args), + "send packet: $OK#00", + "read packet: $qLaunchSuccess#a5", + "send packet: $OK#00"], + True) + + def add_thread_suffix_request_packets(self): + self.test_sequence.add_log_lines( + ["read packet: $QThreadSuffixSupported#e4", + "send packet: $OK#00", + ], True) + + def add_process_info_collection_packets(self): + self.test_sequence.add_log_lines( + ["read packet: $qProcessInfo#dc", + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "process_info_raw"}}], + True) + + def add_set_environment_packets(self, name, value): + self.test_sequence.add_log_lines( + ["read packet: $QEnvironment:" + name + "=" + value + "#00", + "send packet: $OK#00", + ], True) + + _KNOWN_PROCESS_INFO_KEYS = [ + "pid", + "parent-pid", + "real-uid", + "real-gid", + "effective-uid", + "effective-gid", + "cputype", + "cpusubtype", + "ostype", + "triple", + "vendor", + "endian", + "elf_abi", + "ptrsize" + ] + + def parse_process_info_response(self, context): + # Ensure we have a process info response. + self.assertIsNotNone(context) + process_info_raw = context.get("process_info_raw") + self.assertIsNotNone(process_info_raw) + + # Pull out key:value; pairs. + process_info_dict = { + match.group(1): match.group(2) for match in re.finditer( + r"([^:]+):([^;]+);", process_info_raw)} + + # Validate keys are known. + for (key, val) in list(process_info_dict.items()): + self.assertTrue(key in self._KNOWN_PROCESS_INFO_KEYS) + self.assertIsNotNone(val) + + return process_info_dict + + def add_register_info_collection_packets(self): + self.test_sequence.add_log_lines( + [{"type": "multi_response", "query": "qRegisterInfo", "append_iteration_suffix": True, + "end_regex": re.compile(r"^\$(E\d+)?#[0-9a-fA-F]{2}$"), + "save_key": "reg_info_responses"}], + True) + + def parse_register_info_packets(self, context): + """Return an array of register info dictionaries, one per register info.""" + reg_info_responses = context.get("reg_info_responses") + self.assertIsNotNone(reg_info_responses) + + # Parse register infos. + return [parse_reg_info_response(reg_info_response) + for reg_info_response in reg_info_responses] + + def expect_gdbremote_sequence(self, timeout_seconds=None): + if not timeout_seconds: + timeout_seconds = self._TIMEOUT_SECONDS + return expect_lldb_gdbserver_replay( + self, + self.sock, + self.test_sequence, + self._pump_queues, + timeout_seconds, + self.logger) + + _KNOWN_REGINFO_KEYS = [ + "name", + "alt-name", + "bitsize", + "offset", + "encoding", + "format", + "set", + "gcc", + "ehframe", + "dwarf", + "generic", + "container-regs", + "invalidate-regs", + "dynamic_size_dwarf_expr_bytes", + "dynamic_size_dwarf_len" + ] + + def assert_valid_reg_info(self, reg_info): + # Assert we know about all the reginfo keys parsed. + for key in reg_info: + self.assertTrue(key in self._KNOWN_REGINFO_KEYS) + + # Check the bare-minimum expected set of register info keys. + self.assertTrue("name" in reg_info) + self.assertTrue("bitsize" in reg_info) + self.assertTrue("offset" in reg_info) + self.assertTrue("encoding" in reg_info) + self.assertTrue("format" in reg_info) + + def find_pc_reg_info(self, reg_infos): + lldb_reg_index = 0 + for reg_info in reg_infos: + if ("generic" in reg_info) and (reg_info["generic"] == "pc"): + return (lldb_reg_index, reg_info) + lldb_reg_index += 1 + + return (None, None) + + def add_lldb_register_index(self, reg_infos): + """Add a "lldb_register_index" key containing the 0-baed index of each reg_infos entry. + + We'll use this when we want to call packets like P/p with a register index but do so + on only a subset of the full register info set. + """ + self.assertIsNotNone(reg_infos) + + reg_index = 0 + for reg_info in reg_infos: + reg_info["lldb_register_index"] = reg_index + reg_index += 1 + + def add_query_memory_region_packets(self, address): + self.test_sequence.add_log_lines( + ["read packet: $qMemoryRegionInfo:{0:x}#00".format(address), + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "memory_region_response"}}], + True) + + def parse_key_val_dict(self, key_val_text, allow_dupes=True): + self.assertIsNotNone(key_val_text) + kv_dict = {} + for match in re.finditer(r";?([^:]+):([^;]+)", key_val_text): + key = match.group(1) + val = match.group(2) + if key in kv_dict: + if allow_dupes: + if isinstance(kv_dict[key], list): + kv_dict[key].append(val) + else: + # Promote to list + kv_dict[key] = [kv_dict[key], val] + else: + self.fail( + "key '{}' already present when attempting to add value '{}' (text='{}', dict={})".format( + key, val, key_val_text, kv_dict)) + else: + kv_dict[key] = val + return kv_dict + + def parse_memory_region_packet(self, context): + # Ensure we have a context. + self.assertIsNotNone(context.get("memory_region_response")) + + # Pull out key:value; pairs. + mem_region_dict = self.parse_key_val_dict( + context.get("memory_region_response")) + + # Validate keys are known. + for (key, val) in list(mem_region_dict.items()): + self.assertTrue( + key in [ + "start", + "size", + "permissions", + "name", + "error"]) + self.assertIsNotNone(val) + + mem_region_dict["name"] = seven.unhexlify(mem_region_dict.get("name", "")) + # Return the dictionary of key-value pairs for the memory region. + return mem_region_dict + + def assert_address_within_memory_region( + self, test_address, mem_region_dict): + self.assertIsNotNone(mem_region_dict) + self.assertTrue("start" in mem_region_dict) + self.assertTrue("size" in mem_region_dict) + + range_start = int(mem_region_dict["start"], 16) + range_size = int(mem_region_dict["size"], 16) + range_end = range_start + range_size + + if test_address < range_start: + self.fail( + "address 0x{0:x} comes before range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format( + test_address, + range_start, + range_end, + range_size)) + elif test_address >= range_end: + self.fail( + "address 0x{0:x} comes after range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format( + test_address, + range_start, + range_end, + range_size)) + + def add_threadinfo_collection_packets(self): + self.test_sequence.add_log_lines( + [{"type": "multi_response", "first_query": "qfThreadInfo", "next_query": "qsThreadInfo", + "append_iteration_suffix": False, "end_regex": re.compile(r"^\$(l)?#[0-9a-fA-F]{2}$"), + "save_key": "threadinfo_responses"}], + True) + + def parse_threadinfo_packets(self, context): + """Return an array of thread ids (decimal ints), one per thread.""" + threadinfo_responses = context.get("threadinfo_responses") + self.assertIsNotNone(threadinfo_responses) + + thread_ids = [] + for threadinfo_response in threadinfo_responses: + new_thread_infos = parse_threadinfo_response(threadinfo_response) + thread_ids.extend(new_thread_infos) + return thread_ids + + def wait_for_thread_count(self, thread_count, timeout_seconds=None): + if not timeout_seconds: + timeout_seconds = self._WAIT_TIMEOUT + start_time = time.time() + timeout_time = start_time + timeout_seconds + + actual_thread_count = 0 + while actual_thread_count < thread_count: + self.reset_test_sequence() + self.add_threadinfo_collection_packets() + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + threads = self.parse_threadinfo_packets(context) + self.assertIsNotNone(threads) + + actual_thread_count = len(threads) + + if time.time() > timeout_time: + raise Exception( + 'timed out after {} seconds while waiting for theads: waiting for at least {} threads, found {}'.format( + timeout_seconds, thread_count, actual_thread_count)) + + return threads + + def add_set_breakpoint_packets( + self, + address, + z_packet_type=0, + do_continue=True, + breakpoint_kind=1): + self.test_sequence.add_log_lines( + [ # Set the breakpoint. + "read packet: $Z{2},{0:x},{1}#00".format( + address, breakpoint_kind, z_packet_type), + # Verify the stub could set it. + "send packet: $OK#00", + ], True) + + if (do_continue): + self.test_sequence.add_log_lines( + [ # Continue the inferior. + "read packet: $c#63", + # Expect a breakpoint stop report. + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", + "capture": {1: "stop_signo", + 2: "stop_thread_id"}}, + ], True) + + def add_remove_breakpoint_packets( + self, + address, + z_packet_type=0, + breakpoint_kind=1): + self.test_sequence.add_log_lines( + [ # Remove the breakpoint. + "read packet: $z{2},{0:x},{1}#00".format( + address, breakpoint_kind, z_packet_type), + # Verify the stub could unset it. + "send packet: $OK#00", + ], True) + + def add_qSupported_packets(self): + self.test_sequence.add_log_lines( + ["read packet: $qSupported#00", + {"direction": "send", "regex": r"^\$(.*)#[0-9a-fA-F]{2}", "capture": {1: "qSupported_response"}}, + ], True) + + _KNOWN_QSUPPORTED_STUB_FEATURES = [ + "augmented-libraries-svr4-read", + "PacketSize", + "QStartNoAckMode", + "QThreadSuffixSupported", + "QListThreadsInStopReply", + "qXfer:auxv:read", + "qXfer:libraries:read", + "qXfer:libraries-svr4:read", + "qXfer:features:read", + "qEcho", + "QPassSignals" + ] + + def parse_qSupported_response(self, context): + self.assertIsNotNone(context) + + raw_response = context.get("qSupported_response") + self.assertIsNotNone(raw_response) + + # For values with key=val, the dict key and vals are set as expected. For feature+, feature- and feature?, the + # +,-,? is stripped from the key and set as the value. + supported_dict = {} + for match in re.finditer(r";?([^=;]+)(=([^;]+))?", raw_response): + key = match.group(1) + val = match.group(3) + + # key=val: store as is + if val and len(val) > 0: + supported_dict[key] = val + else: + if len(key) < 2: + raise Exception( + "singular stub feature is too short: must be stub_feature{+,-,?}") + supported_type = key[-1] + key = key[:-1] + if not supported_type in ["+", "-", "?"]: + raise Exception( + "malformed stub feature: final character {} not in expected set (+,-,?)".format(supported_type)) + supported_dict[key] = supported_type + # Ensure we know the supported element + if key not in self._KNOWN_QSUPPORTED_STUB_FEATURES: + raise Exception( + "unknown qSupported stub feature reported: %s" % + key) + + return supported_dict + + def run_process_then_stop(self, run_seconds=1): + # Tell the stub to continue. + self.test_sequence.add_log_lines( + ["read packet: $vCont;c#a8"], + True) + context = self.expect_gdbremote_sequence() + + # Wait for run_seconds. + time.sleep(run_seconds) + + # Send an interrupt, capture a T response. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + ["read packet: {}".format(chr(3)), + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture": {1: "stop_result"}}], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + self.assertIsNotNone(context.get("stop_result")) + + return context + + def continue_process_and_wait_for_stop(self): + self.test_sequence.add_log_lines( + [ + "read packet: $vCont;c#a8", + { + "direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})(.*)#[0-9a-fA-F]{2}$", + "capture": {1: "stop_signo", 2: "stop_key_val_text"}, + }, + ], + True, + ) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + return self.parse_interrupt_packets(context) + + def select_modifiable_register(self, reg_infos): + """Find a register that can be read/written freely.""" + PREFERRED_REGISTER_NAMES = set(["rax", ]) + + # First check for the first register from the preferred register name + # set. + alternative_register_index = None + + self.assertIsNotNone(reg_infos) + for reg_info in reg_infos: + if ("name" in reg_info) and ( + reg_info["name"] in PREFERRED_REGISTER_NAMES): + # We found a preferred register. Use it. + return reg_info["lldb_register_index"] + if ("generic" in reg_info) and (reg_info["generic"] == "fp" or + reg_info["generic"] == "arg1"): + # A frame pointer or first arg register will do as a + # register to modify temporarily. + alternative_register_index = reg_info["lldb_register_index"] + + # We didn't find a preferred register. Return whatever alternative register + # we found, if any. + return alternative_register_index + + def extract_registers_from_stop_notification(self, stop_key_vals_text): + self.assertIsNotNone(stop_key_vals_text) + kv_dict = self.parse_key_val_dict(stop_key_vals_text) + + registers = {} + for (key, val) in list(kv_dict.items()): + if re.match(r"^[0-9a-fA-F]+$", key): + registers[int(key, 16)] = val + return registers + + def gather_register_infos(self): + self.reset_test_sequence() + self.add_register_info_collection_packets() + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + reg_infos = self.parse_register_info_packets(context) + self.assertIsNotNone(reg_infos) + self.add_lldb_register_index(reg_infos) + + return reg_infos + + def find_generic_register_with_name(self, reg_infos, generic_name): + self.assertIsNotNone(reg_infos) + for reg_info in reg_infos: + if ("generic" in reg_info) and ( + reg_info["generic"] == generic_name): + return reg_info + return None + + def decode_gdbremote_binary(self, encoded_bytes): + decoded_bytes = "" + i = 0 + while i < len(encoded_bytes): + if encoded_bytes[i] == "}": + # Handle escaped char. + self.assertTrue(i + 1 < len(encoded_bytes)) + decoded_bytes += chr(ord(encoded_bytes[i + 1]) ^ 0x20) + i += 2 + elif encoded_bytes[i] == "*": + # Handle run length encoding. + self.assertTrue(len(decoded_bytes) > 0) + self.assertTrue(i + 1 < len(encoded_bytes)) + repeat_count = ord(encoded_bytes[i + 1]) - 29 + decoded_bytes += decoded_bytes[-1] * repeat_count + i += 2 + else: + decoded_bytes += encoded_bytes[i] + i += 1 + return decoded_bytes + + def build_auxv_dict(self, endian, word_size, auxv_data): + self.assertIsNotNone(endian) + self.assertIsNotNone(word_size) + self.assertIsNotNone(auxv_data) + + auxv_dict = {} + + # PowerPC64le's auxvec has a special key that must be ignored. + # This special key may be used multiple times, resulting in + # multiple key/value pairs with the same key, which would otherwise + # break this test check for repeated keys. + # + # AT_IGNOREPPC = 22 + ignored_keys_for_arch = { 'powerpc64le' : [22] } + arch = self.getArchitecture() + ignore_keys = None + if arch in ignored_keys_for_arch: + ignore_keys = ignored_keys_for_arch[arch] + + while len(auxv_data) > 0: + # Chop off key. + raw_key = auxv_data[:word_size] + auxv_data = auxv_data[word_size:] + + # Chop of value. + raw_value = auxv_data[:word_size] + auxv_data = auxv_data[word_size:] + + # Convert raw text from target endian. + key = unpack_endian_binary_string(endian, raw_key) + value = unpack_endian_binary_string(endian, raw_value) + + if ignore_keys and key in ignore_keys: + continue + + # Handle ending entry. + if key == 0: + self.assertEqual(value, 0) + return auxv_dict + + # The key should not already be present. + self.assertFalse(key in auxv_dict) + auxv_dict[key] = value + + self.fail( + "should not reach here - implies required double zero entry not found") + return auxv_dict + + def read_binary_data_in_chunks(self, command_prefix, chunk_length): + """Collect command_prefix{offset:x},{chunk_length:x} until a single 'l' or 'l' with data is returned.""" + offset = 0 + done = False + decoded_data = "" + + while not done: + # Grab the next iteration of data. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + "read packet: ${}{:x},{:x}:#00".format( + command_prefix, + offset, + chunk_length), + { + "direction": "send", + "regex": re.compile( + r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", + re.MULTILINE | re.DOTALL), + "capture": { + 1: "response_type", + 2: "content_raw"}}], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + response_type = context.get("response_type") + self.assertIsNotNone(response_type) + self.assertTrue(response_type in ["l", "m"]) + + # Move offset along. + offset += chunk_length + + # Figure out if we're done. We're done if the response type is l. + done = response_type == "l" + + # Decode binary data. + content_raw = context.get("content_raw") + if content_raw and len(content_raw) > 0: + self.assertIsNotNone(content_raw) + decoded_data += self.decode_gdbremote_binary(content_raw) + return decoded_data + + def add_interrupt_packets(self): + self.test_sequence.add_log_lines([ + # Send the intterupt. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})(.*)#[0-9a-fA-F]{2}$", + "capture": {1: "stop_signo", + 2: "stop_key_val_text"}}, + ], True) + + def parse_interrupt_packets(self, context): + self.assertIsNotNone(context.get("stop_signo")) + self.assertIsNotNone(context.get("stop_key_val_text")) + return (int(context["stop_signo"], 16), self.parse_key_val_dict( + context["stop_key_val_text"])) + + def add_QSaveRegisterState_packets(self, thread_id): + if thread_id: + # Use the thread suffix form. + request = "read packet: $QSaveRegisterState;thread:{:x}#00".format( + thread_id) + else: + request = "read packet: $QSaveRegisterState#00" + + self.test_sequence.add_log_lines([request, + {"direction": "send", + "regex": r"^\$(E?.*)#[0-9a-fA-F]{2}$", + "capture": {1: "save_response"}}, + ], + True) + + def parse_QSaveRegisterState_response(self, context): + self.assertIsNotNone(context) + + save_response = context.get("save_response") + self.assertIsNotNone(save_response) + + if len(save_response) < 1 or save_response[0] == "E": + # error received + return (False, None) + else: + return (True, int(save_response)) + + def add_QRestoreRegisterState_packets(self, save_id, thread_id=None): + if thread_id: + # Use the thread suffix form. + request = "read packet: $QRestoreRegisterState:{};thread:{:x}#00".format( + save_id, thread_id) + else: + request = "read packet: $QRestoreRegisterState:{}#00".format( + save_id) + + self.test_sequence.add_log_lines([ + request, + "send packet: $OK#00" + ], True) + + def flip_all_bits_in_each_register_value( + self, reg_infos, endian, thread_id=None): + self.assertIsNotNone(reg_infos) + + successful_writes = 0 + failed_writes = 0 + + for reg_info in reg_infos: + # Use the lldb register index added to the reg info. We're not necessarily + # working off a full set of register infos, so an inferred register + # index could be wrong. + reg_index = reg_info["lldb_register_index"] + self.assertIsNotNone(reg_index) + + reg_byte_size = int(reg_info["bitsize"]) // 8 + self.assertTrue(reg_byte_size > 0) + + # Handle thread suffix. + if thread_id: + p_request = "read packet: $p{:x};thread:{:x}#00".format( + reg_index, thread_id) + else: + p_request = "read packet: $p{:x}#00".format(reg_index) + + # Read the existing value. + self.reset_test_sequence() + self.test_sequence.add_log_lines([ + p_request, + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Verify the response length. + p_response = context.get("p_response") + self.assertIsNotNone(p_response) + initial_reg_value = unpack_register_hex_unsigned( + endian, p_response) + + # Flip the value by xoring with all 1s + all_one_bits_raw = "ff" * (int(reg_info["bitsize"]) // 8) + flipped_bits_int = initial_reg_value ^ int(all_one_bits_raw, 16) + # print("reg (index={}, name={}): val={}, flipped bits (int={}, hex={:x})".format(reg_index, reg_info["name"], initial_reg_value, flipped_bits_int, flipped_bits_int)) + + # Handle thread suffix for P. + if thread_id: + P_request = "read packet: $P{:x}={};thread:{:x}#00".format( + reg_index, pack_register_hex( + endian, flipped_bits_int, byte_size=reg_byte_size), thread_id) + else: + P_request = "read packet: $P{:x}={}#00".format( + reg_index, pack_register_hex( + endian, flipped_bits_int, byte_size=reg_byte_size)) + + # Write the flipped value to the register. + self.reset_test_sequence() + self.test_sequence.add_log_lines([P_request, + {"direction": "send", + "regex": r"^\$(OK|E[0-9a-fA-F]+)#[0-9a-fA-F]{2}", + "capture": {1: "P_response"}}, + ], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Determine if the write succeeded. There are a handful of registers that can fail, or partially fail + # (e.g. flags, segment selectors, etc.) due to register value restrictions. Don't worry about them + # all flipping perfectly. + P_response = context.get("P_response") + self.assertIsNotNone(P_response) + if P_response == "OK": + successful_writes += 1 + else: + failed_writes += 1 + # print("reg (index={}, name={}) write FAILED (error: {})".format(reg_index, reg_info["name"], P_response)) + + # Read back the register value, ensure it matches the flipped + # value. + if P_response == "OK": + self.reset_test_sequence() + self.test_sequence.add_log_lines([ + p_request, + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + verify_p_response_raw = context.get("p_response") + self.assertIsNotNone(verify_p_response_raw) + verify_bits = unpack_register_hex_unsigned( + endian, verify_p_response_raw) + + if verify_bits != flipped_bits_int: + # Some registers, like mxcsrmask and others, will permute what's written. Adjust succeed/fail counts. + # print("reg (index={}, name={}): read verify FAILED: wrote {:x}, verify read back {:x}".format(reg_index, reg_info["name"], flipped_bits_int, verify_bits)) + successful_writes -= 1 + failed_writes += 1 + + return (successful_writes, failed_writes) + + def is_bit_flippable_register(self, reg_info): + if not reg_info: + return False + if not "set" in reg_info: + return False + if reg_info["set"] != "General Purpose Registers": + return False + if ("container-regs" in reg_info) and ( + len(reg_info["container-regs"]) > 0): + # Don't try to bit flip registers contained in another register. + return False + if re.match("^.s$", reg_info["name"]): + # This is a 2-letter register name that ends in "s", like a segment register. + # Don't try to bit flip these. + return False + if re.match("^(c|)psr$", reg_info["name"]): + # This is an ARM program status register; don't flip it. + return False + # Okay, this looks fine-enough. + return True + + def read_register_values(self, reg_infos, endian, thread_id=None): + self.assertIsNotNone(reg_infos) + values = {} + + for reg_info in reg_infos: + # We append a register index when load reg infos so we can work + # with subsets. + reg_index = reg_info.get("lldb_register_index") + self.assertIsNotNone(reg_index) + + # Handle thread suffix. + if thread_id: + p_request = "read packet: $p{:x};thread:{:x}#00".format( + reg_index, thread_id) + else: + p_request = "read packet: $p{:x}#00".format(reg_index) + + # Read it with p. + self.reset_test_sequence() + self.test_sequence.add_log_lines([ + p_request, + {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}, + ], True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Convert value from target endian to integral. + p_response = context.get("p_response") + self.assertIsNotNone(p_response) + self.assertTrue(len(p_response) > 0) + self.assertFalse(p_response[0] == "E") + + values[reg_index] = unpack_register_hex_unsigned( + endian, p_response) + + return values + + def add_vCont_query_packets(self): + self.test_sequence.add_log_lines(["read packet: $vCont?#49", + {"direction": "send", + "regex": r"^\$(vCont)?(.*)#[0-9a-fA-F]{2}$", + "capture": {2: "vCont_query_response"}}, + ], + True) + + def parse_vCont_query_response(self, context): + self.assertIsNotNone(context) + vCont_query_response = context.get("vCont_query_response") + + # Handle case of no vCont support at all - in which case the capture + # group will be none or zero length. + if not vCont_query_response or len(vCont_query_response) == 0: + return {} + + return {key: 1 for key in vCont_query_response.split( + ";") if key and len(key) > 0} + + def count_single_steps_until_true( + self, + thread_id, + predicate, + args, + max_step_count=100, + use_Hc_packet=True, + step_instruction="s"): + """Used by single step test that appears in a few different contexts.""" + single_step_count = 0 + + while single_step_count < max_step_count: + self.assertIsNotNone(thread_id) + + # Build the packet for the single step instruction. We replace + # {thread}, if present, with the thread_id. + step_packet = "read packet: ${}#00".format( + re.sub(r"{thread}", "{:x}".format(thread_id), step_instruction)) + # print("\nstep_packet created: {}\n".format(step_packet)) + + # Single step. + self.reset_test_sequence() + if use_Hc_packet: + self.test_sequence.add_log_lines( + [ # Set the continue thread. + "read packet: $Hc{0:x}#00".format(thread_id), + "send packet: $OK#00", + ], True) + self.test_sequence.add_log_lines([ + # Single step. + step_packet, + # "read packet: $vCont;s:{0:x}#00".format(thread_id), + # Expect a breakpoint stop report. + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", + "capture": {1: "stop_signo", + 2: "stop_thread_id"}}, + ], True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + self.assertIsNotNone(context.get("stop_signo")) + self.assertEqual(int(context.get("stop_signo"), 16), + lldbutil.get_signal_number('SIGTRAP')) + + single_step_count += 1 + + # See if the predicate is true. If so, we're done. + if predicate(args): + return (True, single_step_count) + + # The predicate didn't return true within the runaway step count. + return (False, single_step_count) + + def g_c1_c2_contents_are(self, args): + """Used by single step test that appears in a few different contexts.""" + g_c1_address = args["g_c1_address"] + g_c2_address = args["g_c2_address"] + expected_g_c1 = args["expected_g_c1"] + expected_g_c2 = args["expected_g_c2"] + + # Read g_c1 and g_c2 contents. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + ["read packet: $m{0:x},{1:x}#00".format(g_c1_address, 1), + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "g_c1_contents"}}, + "read packet: $m{0:x},{1:x}#00".format(g_c2_address, 1), + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "g_c2_contents"}}], + True) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Check if what we read from inferior memory is what we are expecting. + self.assertIsNotNone(context.get("g_c1_contents")) + self.assertIsNotNone(context.get("g_c2_contents")) + + return (seven.unhexlify(context.get("g_c1_contents")) == expected_g_c1) and ( + seven.unhexlify(context.get("g_c2_contents")) == expected_g_c2) + + def single_step_only_steps_one_instruction( + self, use_Hc_packet=True, step_instruction="s"): + """Used by single step test that appears in a few different contexts.""" + # Start up the inferior. + procs = self.prep_debug_monitor_and_inferior( + inferior_args=[ + "get-code-address-hex:swap_chars", + "get-data-address-hex:g_c1", + "get-data-address-hex:g_c2", + "sleep:1", + "call-function:swap_chars", + "sleep:5"]) + + # Run the process + self.test_sequence.add_log_lines( + [ # Start running after initial stop. + "read packet: $c#63", + # Match output line that prints the memory address of the function call entry point. + # Note we require launch-only testing so we can get inferior otuput. + {"type": "output_match", "regex": r"^code address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\n$", + "capture": {1: "function_address", 2: "g_c1_address", 3: "g_c2_address"}}, + # Now stop the inferior. + "read packet: {}".format(chr(3)), + # And wait for the stop notification. + {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}], + True) + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Grab the main thread id. + self.assertIsNotNone(context.get("stop_thread_id")) + main_thread_id = int(context.get("stop_thread_id"), 16) + + # Grab the function address. + self.assertIsNotNone(context.get("function_address")) + function_address = int(context.get("function_address"), 16) + + # Grab the data addresses. + self.assertIsNotNone(context.get("g_c1_address")) + g_c1_address = int(context.get("g_c1_address"), 16) + + self.assertIsNotNone(context.get("g_c2_address")) + g_c2_address = int(context.get("g_c2_address"), 16) + + # Set a breakpoint at the given address. + if self.getArchitecture() == "arm": + # TODO: Handle case when setting breakpoint in thumb code + BREAKPOINT_KIND = 4 + else: + BREAKPOINT_KIND = 1 + self.reset_test_sequence() + self.add_set_breakpoint_packets( + function_address, + do_continue=True, + breakpoint_kind=BREAKPOINT_KIND) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Remove the breakpoint. + self.reset_test_sequence() + self.add_remove_breakpoint_packets( + function_address, breakpoint_kind=BREAKPOINT_KIND) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Verify g_c1 and g_c2 match expected initial state. + args = {} + args["g_c1_address"] = g_c1_address + args["g_c2_address"] = g_c2_address + args["expected_g_c1"] = "0" + args["expected_g_c2"] = "1" + + self.assertTrue(self.g_c1_c2_contents_are(args)) + + # Verify we take only a small number of steps to hit the first state. + # Might need to work through function entry prologue code. + args["expected_g_c1"] = "1" + args["expected_g_c2"] = "1" + (state_reached, + step_count) = self.count_single_steps_until_true(main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=25, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction) + self.assertTrue(state_reached) + + # Verify we hit the next state. + args["expected_g_c1"] = "1" + args["expected_g_c2"] = "0" + (state_reached, + step_count) = self.count_single_steps_until_true(main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=5, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction) + self.assertTrue(state_reached) + expected_step_count = 1 + arch = self.getArchitecture() + + # MIPS required "3" (ADDIU, SB, LD) machine instructions for updation + # of variable value + if re.match("mips", arch): + expected_step_count = 3 + # S390X requires "2" (LARL, MVI) machine instructions for updation of + # variable value + if re.match("s390x", arch): + expected_step_count = 2 + self.assertEqual(step_count, expected_step_count) + + # Verify we hit the next state. + args["expected_g_c1"] = "0" + args["expected_g_c2"] = "0" + (state_reached, + step_count) = self.count_single_steps_until_true(main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=5, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction) + self.assertTrue(state_reached) + self.assertEqual(step_count, expected_step_count) + + # Verify we hit the next state. + args["expected_g_c1"] = "0" + args["expected_g_c2"] = "1" + (state_reached, + step_count) = self.count_single_steps_until_true(main_thread_id, + self.g_c1_c2_contents_are, + args, + max_step_count=5, + use_Hc_packet=use_Hc_packet, + step_instruction=step_instruction) + self.assertTrue(state_reached) + self.assertEqual(step_count, expected_step_count) + + def maybe_strict_output_regex(self, regex): + return '.*' + regex + \ + '.*' if lldbplatformutil.hasChattyStderr(self) else '^' + regex + '$' + + def install_and_create_launch_args(self): + exe_path = self.getBuildArtifact("a.out") + if not lldb.remote_platform: + return [exe_path] + remote_path = lldbutil.append_to_process_working_directory(self, + os.path.basename(exe_path)) + remote_file_spec = lldb.SBFileSpec(remote_path, False) + err = lldb.remote_platform.Install(lldb.SBFileSpec(exe_path, True), + remote_file_spec) + if err.Fail(): + raise Exception("remote_platform.Install('%s', '%s') failed: %s" % + (exe_path, remote_path, err)) + return [remote_path] diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/Makefile new file mode 100644 index 00000000000..536d2e8db48 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/Makefile @@ -0,0 +1,6 @@ +CFLAGS_EXTRAS := -D__STDC_LIMIT_MACROS -D__STDC_FORMAT_MACROS -std=c++11 +# LD_EXTRAS := -lpthread +CXX_SOURCES := main.cpp +MAKE_DSYM :=NO + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py new file mode 100644 index 00000000000..5292913aa42 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py @@ -0,0 +1,45 @@ + + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteAbort(gdbremote_testcase.GdbRemoteTestCaseBase): + mydir = TestBase.compute_mydir(__file__) + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def inferior_abort_received(self): + procs = self.prep_debug_monitor_and_inferior(inferior_args=["abort"]) + self.assertIsNotNone(procs) + + self.test_sequence.add_log_lines(["read packet: $vCont;c#a8", + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", + "capture": {1: "hex_exit_code"}}, + ], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + hex_exit_code = context.get("hex_exit_code") + self.assertIsNotNone(hex_exit_code) + self.assertEqual(int(hex_exit_code, 16), + lldbutil.get_signal_number('SIGABRT')) + + @debugserver_test + def test_inferior_abort_received_debugserver(self): + self.init_debugserver_test() + self.build() + self.inferior_abort_received() + + @skipIfWindows # No signal is sent on Windows. + @llgs_test + # std::abort() on <= API 16 raises SIGSEGV - b.android.com/179836 + @expectedFailureAndroid(api_levels=list(range(16 + 1))) + def test_inferior_abort_received_llgs(self): + self.init_llgs_test() + self.build() + self.inferior_abort_received() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py new file mode 100644 index 00000000000..e0ba3d7eb68 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py @@ -0,0 +1,45 @@ + + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteSegFault(gdbremote_testcase.GdbRemoteTestCaseBase): + mydir = TestBase.compute_mydir(__file__) + + GDB_REMOTE_STOP_CODE_BAD_ACCESS = 0x91 + + @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet + def inferior_seg_fault_received(self, expected_signo): + procs = self.prep_debug_monitor_and_inferior( + inferior_args=["segfault"]) + self.assertIsNotNone(procs) + + self.test_sequence.add_log_lines(["read packet: $vCont;c#a8", + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", + "capture": {1: "hex_exit_code"}}, + ], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + hex_exit_code = context.get("hex_exit_code") + self.assertIsNotNone(hex_exit_code) + self.assertEqual(int(hex_exit_code, 16), expected_signo) + + @debugserver_test + def test_inferior_seg_fault_received_debugserver(self): + self.init_debugserver_test() + self.build() + self.inferior_seg_fault_received(self.GDB_REMOTE_STOP_CODE_BAD_ACCESS) + + @skipIfWindows # No signal is sent on Windows. + @llgs_test + def test_inferior_seg_fault_received_llgs(self): + self.init_llgs_test() + self.build() + self.inferior_seg_fault_received(lldbutil.get_signal_number('SIGSEGV')) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/main.cpp new file mode 100644 index 00000000000..ced7f712508 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/main.cpp @@ -0,0 +1,31 @@ +#include <cstdlib> +#include <cstring> +#include <iostream> + +namespace { +const char *const SEGFAULT_COMMAND = "segfault"; +const char *const ABORT_COMMAND = "abort"; +} + +int main(int argc, char **argv) { + if (argc < 2) { + std::cout << "expected at least one command provided on the command line" + << std::endl; + } + + // Process command line args. + for (int i = 1; i < argc; ++i) { + const char *const command = argv[i]; + if (std::strstr(command, SEGFAULT_COMMAND)) { + // Perform a null pointer access. + int *const null_int_ptr = nullptr; + *null_int_ptr = 0xDEAD; + } else if (std::strstr(command, ABORT_COMMAND)) { + std::abort(); + } else { + std::cout << "Unsupported command: " << command << std::endl; + } + } + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/Makefile new file mode 100644 index 00000000000..5b5c1dcef78 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/Makefile @@ -0,0 +1,19 @@ +LIB_PREFIX := svr4lib +LD_EXTRAS := -L. -lsvr4lib_a -lsvr4lib_b\" +CXX_SOURCES := main.cpp +USE_LIBDL := 1 +MAKE_DSYM := NO + +a.out: svr4lib_a svr4lib_b_quote + +include Makefile.rules + +svr4lib_a: + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_NAME=svr4lib_a DYLIB_CXX_SOURCES=svr4lib_a.cpp \ + DYLIB_ONLY=YES + +svr4lib_b_quote: + $(MAKE) -f $(MAKEFILE_RULES) \ + DYLIB_NAME=svr4lib_b\\\" DYLIB_CXX_SOURCES=svr4lib_b_quote.cpp \ + DYLIB_ONLY=YES diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/TestGdbRemoteLibrariesSvr4Support.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/TestGdbRemoteLibrariesSvr4Support.py new file mode 100644 index 00000000000..2081d9f34c5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/TestGdbRemoteLibrariesSvr4Support.py @@ -0,0 +1,133 @@ +import xml.etree.ElementTree as ET + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class TestGdbRemoteLibrariesSvr4Support(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + FEATURE_NAME = "qXfer:libraries-svr4:read" + + def setup_test(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + env = {} + env[self.dylibPath] = self.getBuildDir() + self.prep_debug_monitor_and_inferior(inferior_env=env) + self.continue_process_and_wait_for_stop() + + def get_expected_libs(self): + return ["libsvr4lib_a.so", 'libsvr4lib_b".so'] + + def has_libraries_svr4_support(self): + self.add_qSupported_packets() + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + features = self.parse_qSupported_response(context) + return self.FEATURE_NAME in features and features[self.FEATURE_NAME] == "+" + + def get_libraries_svr4_data(self): + # Start up llgs and inferior, and check for libraries-svr4 support. + if not self.has_libraries_svr4_support(): + self.skipTest("libraries-svr4 not supported") + + # Grab the libraries-svr4 data. + self.reset_test_sequence() + self.test_sequence.add_log_lines( + [ + "read packet: $qXfer:libraries-svr4:read::0,ffff:#00", + { + "direction": "send", + "regex": re.compile( + r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", re.MULTILINE | re.DOTALL + ), + "capture": {1: "response_type", 2: "content_raw"}, + }, + ], + True, + ) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Ensure we end up with all libraries-svr4 data in one packet. + self.assertEqual(context.get("response_type"), "l") + + # Decode binary data. + content_raw = context.get("content_raw") + self.assertIsNotNone(content_raw) + return content_raw + + def get_libraries_svr4_xml(self): + libraries_svr4 = self.get_libraries_svr4_data() + xml_root = None + try: + xml_root = ET.fromstring(libraries_svr4) + except xml.etree.ElementTree.ParseError: + pass + self.assertIsNotNone(xml_root, "Malformed libraries-svr4 XML") + return xml_root + + def libraries_svr4_well_formed(self): + xml_root = self.get_libraries_svr4_xml() + self.assertEqual(xml_root.tag, "library-list-svr4") + for child in xml_root: + self.assertEqual(child.tag, "library") + self.assertItemsEqual(child.attrib.keys(), ["name", "lm", "l_addr", "l_ld"]) + + def libraries_svr4_has_correct_load_addr(self): + xml_root = self.get_libraries_svr4_xml() + for child in xml_root: + name = child.attrib.get("name") + base_name = os.path.basename(name) + if os.path.basename(name) not in self.get_expected_libs(): + continue + load_addr = int(child.attrib.get("l_addr"), 16) + self.reset_test_sequence() + self.add_query_memory_region_packets(load_addr) + context = self.expect_gdbremote_sequence() + mem_region = self.parse_memory_region_packet(context) + self.assertEqual(load_addr, int(mem_region.get("start", 0), 16)) + self.assertEqual( + os.path.realpath(name), os.path.realpath(mem_region.get("name", "")) + ) + + def libraries_svr4_libs_present(self): + xml_root = self.get_libraries_svr4_xml() + libraries_svr4_names = [] + for child in xml_root: + name = child.attrib.get("name") + libraries_svr4_names.append(os.path.realpath(name)) + for lib in self.get_expected_libs(): + self.assertIn(self.getBuildDir() + "/" + lib, libraries_svr4_names) + + @llgs_test + @skipUnlessPlatform(["linux", "android", "netbsd"]) + def test_supports_libraries_svr4(self): + self.setup_test() + self.assertTrue(self.has_libraries_svr4_support()) + + @llgs_test + @skipUnlessPlatform(["linux", "android", "netbsd"]) + @expectedFailureNetBSD + def test_libraries_svr4_well_formed(self): + self.setup_test() + self.libraries_svr4_well_formed() + + @llgs_test + @skipUnlessPlatform(["linux", "android", "netbsd"]) + @expectedFailureNetBSD + def test_libraries_svr4_load_addr(self): + self.setup_test() + self.libraries_svr4_has_correct_load_addr() + + @llgs_test + @skipUnlessPlatform(["linux", "android", "netbsd"]) + @expectedFailureNetBSD + def test_libraries_svr4_libs_present(self): + self.setup_test() + self.libraries_svr4_libs_present() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/main.cpp new file mode 100644 index 00000000000..b62ca71b561 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/main.cpp @@ -0,0 +1,15 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int main(int argc, char **argv) { + // Perform a null pointer access. + int *const null_int_ptr = nullptr; + *null_int_ptr = 0xDEAD; + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/svr4lib_a.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/svr4lib_a.cpp new file mode 100644 index 00000000000..47d4b979d92 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/svr4lib_a.cpp @@ -0,0 +1,9 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int svr4lib_a() { return 42; } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/svr4lib_b_quote.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/svr4lib_b_quote.cpp new file mode 100644 index 00000000000..bd8eb0068e9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/libraries-svr4/svr4lib_b_quote.cpp @@ -0,0 +1,9 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +int svr4lib_b_quote() { return 42; } diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py new file mode 100644 index 00000000000..815ba3491c1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py @@ -0,0 +1,950 @@ +"""Module for supporting unit testing of the lldb-server debug monitor exe. +""" + +from __future__ import division, print_function + + +import os +import os.path +import platform +import re +import six +import socket_packet_pump +import subprocess +from lldbsuite.test.lldbtest import * + +from six.moves import queue + + +def _get_debug_monitor_from_lldb(lldb_exe, debug_monitor_basename): + """Return the debug monitor exe path given the lldb exe path. + + This method attempts to construct a valid debug monitor exe name + from a given lldb exe name. It will return None if the synthesized + debug monitor name is not found to exist. + + The debug monitor exe path is synthesized by taking the directory + of the lldb exe, and replacing the portion of the base name that + matches "lldb" (case insensitive) and replacing with the value of + debug_monitor_basename. + + Args: + lldb_exe: the path to an lldb executable. + + debug_monitor_basename: the base name portion of the debug monitor + that will replace 'lldb'. + + Returns: + A path to the debug monitor exe if it is found to exist; otherwise, + returns None. + + """ + if not lldb_exe: + return None + + exe_dir = os.path.dirname(lldb_exe) + exe_base = os.path.basename(lldb_exe) + + # we'll rebuild the filename by replacing lldb with + # the debug monitor basename, keeping any prefix or suffix in place. + regex = re.compile(r"lldb", re.IGNORECASE) + new_base = regex.sub(debug_monitor_basename, exe_base) + + debug_monitor_exe = os.path.join(exe_dir, new_base) + if os.path.exists(debug_monitor_exe): + return debug_monitor_exe + + new_base = regex.sub( + 'LLDB.framework/Versions/A/Resources/' + + debug_monitor_basename, + exe_base) + debug_monitor_exe = os.path.join(exe_dir, new_base) + if os.path.exists(debug_monitor_exe): + return debug_monitor_exe + + return None + + +def get_lldb_server_exe(): + """Return the lldb-server exe path. + + Returns: + A path to the lldb-server exe if it is found to exist; otherwise, + returns None. + """ + if "LLDB_DEBUGSERVER_PATH" in os.environ: + return os.environ["LLDB_DEBUGSERVER_PATH"] + + return _get_debug_monitor_from_lldb( + lldbtest_config.lldbExec, "lldb-server") + + +def get_debugserver_exe(): + """Return the debugserver exe path. + + Returns: + A path to the debugserver exe if it is found to exist; otherwise, + returns None. + """ + if "LLDB_DEBUGSERVER_PATH" in os.environ: + return os.environ["LLDB_DEBUGSERVER_PATH"] + + return _get_debug_monitor_from_lldb( + lldbtest_config.lldbExec, "debugserver") + +_LOG_LINE_REGEX = re.compile(r'^(lldb-server|debugserver)\s+<\s*(\d+)>' + + '\s+(read|send)\s+packet:\s+(.+)$') + + +def _is_packet_lldb_gdbserver_input(packet_type, llgs_input_is_read): + """Return whether a given packet is input for lldb-gdbserver. + + Args: + packet_type: a string indicating 'send' or 'receive', from a + gdbremote packet protocol log. + + llgs_input_is_read: true if lldb-gdbserver input (content sent to + lldb-gdbserver) is listed as 'read' or 'send' in the packet + log entry. + + Returns: + True if the packet should be considered input for lldb-gdbserver; False + otherwise. + """ + if packet_type == 'read': + # when llgs is the read side, then a read packet is meant for + # input to llgs (when captured from the llgs/debugserver exe). + return llgs_input_is_read + elif packet_type == 'send': + # when llgs is the send side, then a send packet is meant to + # be input to llgs (when captured from the lldb exe). + return not llgs_input_is_read + else: + # don't understand what type of packet this is + raise "Unknown packet type: {}".format(packet_type) + + +def handle_O_packet(context, packet_contents, logger): + """Handle O packets.""" + if (not packet_contents) or (len(packet_contents) < 1): + return False + elif packet_contents[0] != "O": + return False + elif packet_contents == "OK": + return False + + new_text = gdbremote_hex_decode_string(packet_contents[1:]) + context["O_content"] += new_text + context["O_count"] += 1 + + if logger: + logger.debug( + "text: new \"{}\", cumulative: \"{}\"".format( + new_text, context["O_content"])) + + return True + +_STRIP_CHECKSUM_REGEX = re.compile(r'#[0-9a-fA-F]{2}$') +_STRIP_COMMAND_PREFIX_REGEX = re.compile(r"^\$") +_STRIP_COMMAND_PREFIX_M_REGEX = re.compile(r"^\$m") + + +def assert_packets_equal(asserter, actual_packet, expected_packet): + # strip off the checksum digits of the packet. When we're in + # no-ack mode, the # checksum is ignored, and should not be cause + # for a mismatched packet. + actual_stripped = _STRIP_CHECKSUM_REGEX.sub('', actual_packet) + expected_stripped = _STRIP_CHECKSUM_REGEX.sub('', expected_packet) + asserter.assertEqual(actual_stripped, expected_stripped) + + +def expect_lldb_gdbserver_replay( + asserter, + sock, + test_sequence, + pump_queues, + timeout_seconds, + logger=None): + """Replay socket communication with lldb-gdbserver and verify responses. + + Args: + asserter: the object providing assertEqual(first, second, msg=None), e.g. TestCase instance. + + sock: the TCP socket connected to the lldb-gdbserver exe. + + test_sequence: a GdbRemoteTestSequence instance that describes + the messages sent to the gdb remote and the responses + expected from it. + + timeout_seconds: any response taking more than this number of + seconds will cause an exception to be raised. + + logger: a Python logger instance. + + Returns: + The context dictionary from running the given gdbremote + protocol sequence. This will contain any of the capture + elements specified to any GdbRemoteEntry instances in + test_sequence. + + The context will also contain an entry, context["O_content"] + which contains the text from the inferior received via $O + packets. $O packets should not attempt to be matched + directly since they are not entirely deterministic as to + how many arrive and how much text is in each one. + + context["O_count"] will contain an integer of the number of + O packets received. + """ + + # Ensure we have some work to do. + if len(test_sequence.entries) < 1: + return {} + + context = {"O_count": 0, "O_content": ""} + with socket_packet_pump.SocketPacketPump(sock, pump_queues, logger) as pump: + # Grab the first sequence entry. + sequence_entry = test_sequence.entries.pop(0) + + # While we have an active sequence entry, send messages + # destined for the stub and collect/match/process responses + # expected from the stub. + while sequence_entry: + if sequence_entry.is_send_to_remote(): + # This is an entry to send to the remote debug monitor. + send_packet = sequence_entry.get_send_packet() + if logger: + if len(send_packet) == 1 and send_packet[0] == chr(3): + packet_desc = "^C" + else: + packet_desc = send_packet + logger.info( + "sending packet to remote: {}".format(packet_desc)) + sock.sendall(send_packet.encode()) + else: + # This is an entry expecting to receive content from the remote + # debug monitor. + + # We'll pull from (and wait on) the queue appropriate for the type of matcher. + # We keep separate queues for process output (coming from non-deterministic + # $O packet division) and for all other packets. + if sequence_entry.is_output_matcher(): + try: + # Grab next entry from the output queue. + content = pump_queues.output_queue().get(True, timeout_seconds) + except queue.Empty: + if logger: + logger.warning( + "timeout waiting for stub output (accumulated output:{})".format( + pump.get_accumulated_output())) + raise Exception( + "timed out while waiting for output match (accumulated output: {})".format( + pump.get_accumulated_output())) + else: + try: + content = pump_queues.packet_queue().get(True, timeout_seconds) + except queue.Empty: + if logger: + logger.warning( + "timeout waiting for packet match (receive buffer: {})".format( + pump.get_receive_buffer())) + raise Exception( + "timed out while waiting for packet match (receive buffer: {})".format( + pump.get_receive_buffer())) + + # Give the sequence entry the opportunity to match the content. + # Output matchers might match or pass after more output accumulates. + # Other packet types generally must match. + asserter.assertIsNotNone(content) + context = sequence_entry.assert_match( + asserter, content, context=context) + + # Move on to next sequence entry as needed. Some sequence entries support executing multiple + # times in different states (for looping over query/response + # packets). + if sequence_entry.is_consumed(): + if len(test_sequence.entries) > 0: + sequence_entry = test_sequence.entries.pop(0) + else: + sequence_entry = None + + # Fill in the O_content entries. + context["O_count"] = 1 + context["O_content"] = pump.get_accumulated_output() + + return context + + +def gdbremote_hex_encode_string(str): + output = '' + for c in str: + output += '{0:02x}'.format(ord(c)) + return output + + +def gdbremote_hex_decode_string(str): + return str.decode("hex") + + +def gdbremote_packet_encode_string(str): + checksum = 0 + for c in str: + checksum += ord(c) + return '$' + str + '#{0:02x}'.format(checksum % 256) + + +def build_gdbremote_A_packet(args_list): + """Given a list of args, create a properly-formed $A packet containing each arg. + """ + payload = "A" + + # build the arg content + arg_index = 0 + for arg in args_list: + # Comma-separate the args. + if arg_index > 0: + payload += ',' + + # Hex-encode the arg. + hex_arg = gdbremote_hex_encode_string(arg) + + # Build the A entry. + payload += "{},{},{}".format(len(hex_arg), arg_index, hex_arg) + + # Next arg index, please. + arg_index += 1 + + # return the packetized payload + return gdbremote_packet_encode_string(payload) + + +def parse_reg_info_response(response_packet): + if not response_packet: + raise Exception("response_packet cannot be None") + + # Strip off prefix $ and suffix #xx if present. + response_packet = _STRIP_COMMAND_PREFIX_REGEX.sub("", response_packet) + response_packet = _STRIP_CHECKSUM_REGEX.sub("", response_packet) + + # Build keyval pairs + values = {} + for kv in response_packet.split(";"): + if len(kv) < 1: + continue + (key, val) = kv.split(':') + values[key] = val + + return values + + +def parse_threadinfo_response(response_packet): + if not response_packet: + raise Exception("response_packet cannot be None") + + # Strip off prefix $ and suffix #xx if present. + response_packet = _STRIP_COMMAND_PREFIX_M_REGEX.sub("", response_packet) + response_packet = _STRIP_CHECKSUM_REGEX.sub("", response_packet) + + # Return list of thread ids + return [int(thread_id_hex, 16) for thread_id_hex in response_packet.split( + ",") if len(thread_id_hex) > 0] + + +def unpack_endian_binary_string(endian, value_string): + """Unpack a gdb-remote binary (post-unescaped, i.e. not escaped) response to an unsigned int given endianness of the inferior.""" + if not endian: + raise Exception("endian cannot be None") + if not value_string or len(value_string) < 1: + raise Exception("value_string cannot be None or empty") + + if endian == 'little': + value = 0 + i = 0 + while len(value_string) > 0: + value += (ord(value_string[0]) << i) + value_string = value_string[1:] + i += 8 + return value + elif endian == 'big': + value = 0 + while len(value_string) > 0: + value = (value << 8) + ord(value_string[0]) + value_string = value_string[1:] + return value + else: + # pdp is valid but need to add parse code once needed. + raise Exception("unsupported endian:{}".format(endian)) + + +def unpack_register_hex_unsigned(endian, value_string): + """Unpack a gdb-remote $p-style response to an unsigned int given endianness of inferior.""" + if not endian: + raise Exception("endian cannot be None") + if not value_string or len(value_string) < 1: + raise Exception("value_string cannot be None or empty") + + if endian == 'little': + value = 0 + i = 0 + while len(value_string) > 0: + value += (int(value_string[0:2], 16) << i) + value_string = value_string[2:] + i += 8 + return value + elif endian == 'big': + return int(value_string, 16) + else: + # pdp is valid but need to add parse code once needed. + raise Exception("unsupported endian:{}".format(endian)) + + +def pack_register_hex(endian, value, byte_size=None): + """Unpack a gdb-remote $p-style response to an unsigned int given endianness of inferior.""" + if not endian: + raise Exception("endian cannot be None") + + if endian == 'little': + # Create the litt-endian return value. + retval = "" + while value != 0: + retval = retval + "{:02x}".format(value & 0xff) + value = value >> 8 + if byte_size: + # Add zero-fill to the right/end (MSB side) of the value. + retval += "00" * (byte_size - len(retval) // 2) + return retval + + elif endian == 'big': + retval = "" + while value != 0: + retval = "{:02x}".format(value & 0xff) + retval + value = value >> 8 + if byte_size: + # Add zero-fill to the left/front (MSB side) of the value. + retval = ("00" * (byte_size - len(retval) // 2)) + retval + return retval + + else: + # pdp is valid but need to add parse code once needed. + raise Exception("unsupported endian:{}".format(endian)) + + +class GdbRemoteEntryBase(object): + + def is_output_matcher(self): + return False + + +class GdbRemoteEntry(GdbRemoteEntryBase): + + def __init__( + self, + is_send_to_remote=True, + exact_payload=None, + regex=None, + capture=None, + expect_captures=None): + """Create an entry representing one piece of the I/O to/from a gdb remote debug monitor. + + Args: + + is_send_to_remote: True if this entry is a message to be + sent to the gdbremote debug monitor; False if this + entry represents text to be matched against the reply + from the gdbremote debug monitor. + + exact_payload: if not None, then this packet is an exact + send (when sending to the remote) or an exact match of + the response from the gdbremote. The checksums are + ignored on exact match requests since negotiation of + no-ack makes the checksum content essentially + undefined. + + regex: currently only valid for receives from gdbremote. + When specified (and only if exact_payload is None), + indicates the gdbremote response must match the given + regex. Match groups in the regex can be used for two + different purposes: saving the match (see capture + arg), or validating that a match group matches a + previously established value (see expect_captures). It + is perfectly valid to have just a regex arg and to + specify neither capture or expect_captures args. This + arg only makes sense if exact_payload is not + specified. + + capture: if specified, is a dictionary of regex match + group indices (should start with 1) to variable names + that will store the capture group indicated by the + index. For example, {1:"thread_id"} will store capture + group 1's content in the context dictionary where + "thread_id" is the key and the match group value is + the value. The value stored off can be used later in a + expect_captures expression. This arg only makes sense + when regex is specified. + + expect_captures: if specified, is a dictionary of regex + match group indices (should start with 1) to variable + names, where the match group should match the value + existing in the context at the given variable name. + For example, {2:"thread_id"} indicates that the second + match group must match the value stored under the + context's previously stored "thread_id" key. This arg + only makes sense when regex is specified. + """ + self._is_send_to_remote = is_send_to_remote + self.exact_payload = exact_payload + self.regex = regex + self.capture = capture + self.expect_captures = expect_captures + + def is_send_to_remote(self): + return self._is_send_to_remote + + def is_consumed(self): + # For now, all packets are consumed after first use. + return True + + def get_send_packet(self): + if not self.is_send_to_remote(): + raise Exception( + "get_send_packet() called on GdbRemoteEntry that is not a send-to-remote packet") + if not self.exact_payload: + raise Exception( + "get_send_packet() called on GdbRemoteEntry but it doesn't have an exact payload") + return self.exact_payload + + def _assert_exact_payload_match(self, asserter, actual_packet): + assert_packets_equal(asserter, actual_packet, self.exact_payload) + return None + + def _assert_regex_match(self, asserter, actual_packet, context): + # Ensure the actual packet matches from the start of the actual packet. + match = self.regex.match(actual_packet) + if not match: + asserter.fail( + "regex '{}' failed to match against content '{}'".format( + self.regex.pattern, actual_packet)) + + if self.capture: + # Handle captures. + for group_index, var_name in list(self.capture.items()): + capture_text = match.group(group_index) + # It is okay for capture text to be None - which it will be if it is a group that can match nothing. + # The user must be okay with it since the regex itself matched + # above. + context[var_name] = capture_text + + if self.expect_captures: + # Handle comparing matched groups to context dictionary entries. + for group_index, var_name in list(self.expect_captures.items()): + capture_text = match.group(group_index) + if not capture_text: + raise Exception( + "No content to expect for group index {}".format(group_index)) + asserter.assertEqual(capture_text, context[var_name]) + + return context + + def assert_match(self, asserter, actual_packet, context=None): + # This only makes sense for matching lines coming from the + # remote debug monitor. + if self.is_send_to_remote(): + raise Exception( + "Attempted to match a packet being sent to the remote debug monitor, doesn't make sense.") + + # Create a new context if needed. + if not context: + context = {} + + # If this is an exact payload, ensure they match exactly, + # ignoring the packet checksum which is optional for no-ack + # mode. + if self.exact_payload: + self._assert_exact_payload_match(asserter, actual_packet) + return context + elif self.regex: + return self._assert_regex_match(asserter, actual_packet, context) + else: + raise Exception( + "Don't know how to match a remote-sent packet when exact_payload isn't specified.") + + +class MultiResponseGdbRemoteEntry(GdbRemoteEntryBase): + """Represents a query/response style packet. + + Assumes the first item is sent to the gdb remote. + An end sequence regex indicates the end of the query/response + packet sequence. All responses up through (but not including) the + end response are stored in a context variable. + + Settings accepted from params: + + next_query or query: required. The typical query packet without the $ prefix or #xx suffix. + If there is a special first packet to start the iteration query, see the + first_query key. + + first_query: optional. If the first query requires a special query command, specify + it with this key. Do not specify the $ prefix or #xx suffix. + + append_iteration_suffix: defaults to False. Specify True if the 0-based iteration + index should be appended as a suffix to the command. e.g. qRegisterInfo with + this key set true will generate query packets of qRegisterInfo0, qRegisterInfo1, + etc. + + end_regex: required. Specifies a compiled regex object that will match the full text + of any response that signals an end to the iteration. It must include the + initial $ and ending #xx and must match the whole packet. + + save_key: required. Specifies the key within the context where an array will be stored. + Each packet received from the gdb remote that does not match the end_regex will get + appended to the array stored within the context at that key. + + runaway_response_count: optional. Defaults to 10000. If this many responses are retrieved, + assume there is something wrong with either the response collection or the ending + detection regex and throw an exception. + """ + + def __init__(self, params): + self._next_query = params.get("next_query", params.get("query")) + if not self._next_query: + raise "either next_query or query key must be specified for MultiResponseGdbRemoteEntry" + + self._first_query = params.get("first_query", self._next_query) + self._append_iteration_suffix = params.get( + "append_iteration_suffix", False) + self._iteration = 0 + self._end_regex = params["end_regex"] + self._save_key = params["save_key"] + self._runaway_response_count = params.get( + "runaway_response_count", 10000) + self._is_send_to_remote = True + self._end_matched = False + + def is_send_to_remote(self): + return self._is_send_to_remote + + def get_send_packet(self): + if not self.is_send_to_remote(): + raise Exception( + "get_send_packet() called on MultiResponseGdbRemoteEntry that is not in the send state") + if self._end_matched: + raise Exception( + "get_send_packet() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.") + + # Choose the first or next query for the base payload. + if self._iteration == 0 and self._first_query: + payload = self._first_query + else: + payload = self._next_query + + # Append the suffix as needed. + if self._append_iteration_suffix: + payload += "%x" % self._iteration + + # Keep track of the iteration. + self._iteration += 1 + + # Now that we've given the query packet, flip the mode to + # receive/match. + self._is_send_to_remote = False + + # Return the result, converted to packet form. + return gdbremote_packet_encode_string(payload) + + def is_consumed(self): + return self._end_matched + + def assert_match(self, asserter, actual_packet, context=None): + # This only makes sense for matching lines coming from the remote debug + # monitor. + if self.is_send_to_remote(): + raise Exception( + "assert_match() called on MultiResponseGdbRemoteEntry but state is set to send a query packet.") + + if self._end_matched: + raise Exception( + "assert_match() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.") + + # Set up a context as needed. + if not context: + context = {} + + # Check if the packet matches the end condition. + match = self._end_regex.match(actual_packet) + if match: + # We're done iterating. + self._end_matched = True + return context + + # Not done iterating - save the packet. + context[self._save_key] = context.get(self._save_key, []) + context[self._save_key].append(actual_packet) + + # Check for a runaway response cycle. + if len(context[self._save_key]) >= self._runaway_response_count: + raise Exception( + "runaway query/response cycle detected: %d responses captured so far. Last response: %s" % + (len( + context[ + self._save_key]), context[ + self._save_key][ + -1])) + + # Flip the mode to send for generating the query. + self._is_send_to_remote = True + return context + + +class MatchRemoteOutputEntry(GdbRemoteEntryBase): + """Waits for output from the debug monitor to match a regex or time out. + + This entry type tries to match each time new gdb remote output is accumulated + using a provided regex. If the output does not match the regex within the + given timeframe, the command fails the playback session. If the regex does + match, any capture fields are recorded in the context. + + Settings accepted from params: + + regex: required. Specifies a compiled regex object that must either succeed + with re.match or re.search (see regex_mode below) within the given timeout + (see timeout_seconds below) or cause the playback to fail. + + regex_mode: optional. Available values: "match" or "search". If "match", the entire + stub output as collected so far must match the regex. If search, then the regex + must match starting somewhere within the output text accumulated thus far. + Default: "match" (i.e. the regex must match the entirety of the accumulated output + buffer, so unexpected text will generally fail the match). + + capture: optional. If specified, is a dictionary of regex match group indices (should start + with 1) to variable names that will store the capture group indicated by the + index. For example, {1:"thread_id"} will store capture group 1's content in the + context dictionary where "thread_id" is the key and the match group value is + the value. The value stored off can be used later in a expect_captures expression. + This arg only makes sense when regex is specified. + """ + + def __init__(self, regex=None, regex_mode="match", capture=None): + self._regex = regex + self._regex_mode = regex_mode + self._capture = capture + self._matched = False + + if not self._regex: + raise Exception("regex cannot be None") + + if not self._regex_mode in ["match", "search"]: + raise Exception( + "unsupported regex mode \"{}\": must be \"match\" or \"search\"".format( + self._regex_mode)) + + def is_output_matcher(self): + return True + + def is_send_to_remote(self): + # This is always a "wait for remote" command. + return False + + def is_consumed(self): + return self._matched + + def assert_match(self, asserter, accumulated_output, context): + # Validate args. + if not accumulated_output: + raise Exception("accumulated_output cannot be none") + if not context: + raise Exception("context cannot be none") + + # Validate that we haven't already matched. + if self._matched: + raise Exception( + "invalid state - already matched, attempting to match again") + + # If we don't have any content yet, we don't match. + if len(accumulated_output) < 1: + return context + + # Check if we match + if self._regex_mode == "match": + match = self._regex.match(accumulated_output) + elif self._regex_mode == "search": + match = self._regex.search(accumulated_output) + else: + raise Exception( + "Unexpected regex mode: {}".format( + self._regex_mode)) + + # If we don't match, wait to try again after next $O content, or time + # out. + if not match: + # print("re pattern \"{}\" did not match against \"{}\"".format(self._regex.pattern, accumulated_output)) + return context + + # We do match. + self._matched = True + # print("re pattern \"{}\" matched against \"{}\"".format(self._regex.pattern, accumulated_output)) + + # Collect up any captures into the context. + if self._capture: + # Handle captures. + for group_index, var_name in list(self._capture.items()): + capture_text = match.group(group_index) + if not capture_text: + raise Exception( + "No content for group index {}".format(group_index)) + context[var_name] = capture_text + + return context + + +class GdbRemoteTestSequence(object): + + _LOG_LINE_REGEX = re.compile(r'^.*(read|send)\s+packet:\s+(.+)$') + + def __init__(self, logger): + self.entries = [] + self.logger = logger + + def add_log_lines(self, log_lines, remote_input_is_read): + for line in log_lines: + if isinstance(line, str): + # Handle log line import + # if self.logger: + # self.logger.debug("processing log line: {}".format(line)) + match = self._LOG_LINE_REGEX.match(line) + if match: + playback_packet = match.group(2) + direction = match.group(1) + if _is_packet_lldb_gdbserver_input( + direction, remote_input_is_read): + # Handle as something to send to the remote debug monitor. + # if self.logger: + # self.logger.info("processed packet to send to remote: {}".format(playback_packet)) + self.entries.append( + GdbRemoteEntry( + is_send_to_remote=True, + exact_payload=playback_packet)) + else: + # Log line represents content to be expected from the remote debug monitor. + # if self.logger: + # self.logger.info("receiving packet from llgs, should match: {}".format(playback_packet)) + self.entries.append( + GdbRemoteEntry( + is_send_to_remote=False, + exact_payload=playback_packet)) + else: + raise Exception( + "failed to interpret log line: {}".format(line)) + elif isinstance(line, dict): + entry_type = line.get("type", "regex_capture") + if entry_type == "regex_capture": + # Handle more explicit control over details via dictionary. + direction = line.get("direction", None) + regex = line.get("regex", None) + capture = line.get("capture", None) + expect_captures = line.get("expect_captures", None) + + # Compile the regex. + if regex and (isinstance(regex, str)): + regex = re.compile(regex) + + if _is_packet_lldb_gdbserver_input( + direction, remote_input_is_read): + # Handle as something to send to the remote debug monitor. + # if self.logger: + # self.logger.info("processed dict sequence to send to remote") + self.entries.append( + GdbRemoteEntry( + is_send_to_remote=True, + regex=regex, + capture=capture, + expect_captures=expect_captures)) + else: + # Log line represents content to be expected from the remote debug monitor. + # if self.logger: + # self.logger.info("processed dict sequence to match receiving from remote") + self.entries.append( + GdbRemoteEntry( + is_send_to_remote=False, + regex=regex, + capture=capture, + expect_captures=expect_captures)) + elif entry_type == "multi_response": + self.entries.append(MultiResponseGdbRemoteEntry(line)) + elif entry_type == "output_match": + + regex = line.get("regex", None) + # Compile the regex. + if regex and (isinstance(regex, str)): + regex = re.compile(regex, re.DOTALL) + + regex_mode = line.get("regex_mode", "match") + capture = line.get("capture", None) + self.entries.append( + MatchRemoteOutputEntry( + regex=regex, + regex_mode=regex_mode, + capture=capture)) + else: + raise Exception("unknown entry type \"%s\"" % entry_type) + + +def process_is_running(pid, unknown_value=True): + """If possible, validate that the given pid represents a running process on the local system. + + Args: + + pid: an OS-specific representation of a process id. Should be an integral value. + + unknown_value: value used when we cannot determine how to check running local + processes on the OS. + + Returns: + + If we can figure out how to check running process ids on the given OS: + return True if the process is running, or False otherwise. + + If we don't know how to check running process ids on the given OS: + return the value provided by the unknown_value arg. + """ + if not isinstance(pid, six.integer_types): + raise Exception( + "pid must be an integral type (actual type: %s)" % str( + type(pid))) + + process_ids = [] + + if lldb.remote_platform: + # Don't know how to get list of running process IDs on a remote + # platform + return unknown_value + elif platform.system() in ['Darwin', 'Linux', 'FreeBSD', 'NetBSD']: + # Build the list of running process ids + output = subprocess.check_output( + "ps ax | awk '{ print $1; }'", shell=True).decode("utf-8") + text_process_ids = output.split('\n')[1:] + # Convert text pids to ints + process_ids = [int(text_pid) + for text_pid in text_process_ids if text_pid != ''] + elif platform.system() == 'Windows': + output = subprocess.check_output( + "for /f \"tokens=2 delims=,\" %F in ('tasklist /nh /fi \"PID ne 0\" /fo csv') do @echo %~F", shell=True).decode("utf-8") + text_process_ids = output.split('\n')[1:] + process_ids = [int(text_pid) + for text_pid in text_process_ids if text_pid != ''] + # elif {your_platform_here}: + # fill in process_ids as a list of int type process IDs running on + # the local system. + else: + # Don't know how to get list of running process IDs on this + # OS, so return the "don't know" value. + return unknown_value + + # Check if the pid is in the process_ids + return pid in process_ids + +if __name__ == '__main__': + EXE_PATH = get_lldb_server_exe() + if EXE_PATH: + print("lldb-server path detected: {}".format(EXE_PATH)) + else: + print("lldb-server could not be found") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/main.cpp new file mode 100644 index 00000000000..f1d46b85425 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/main.cpp @@ -0,0 +1,370 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <atomic> +#include <chrono> +#include <cstdlib> +#include <cstring> +#include <errno.h> +#include <inttypes.h> +#include <memory> +#include <mutex> +#if !defined(_WIN32) +#include <pthread.h> +#include <signal.h> +#include <unistd.h> +#endif +#include <setjmp.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include <thread> +#include <time.h> +#include <vector> + +#if defined(__APPLE__) +__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2) +int pthread_threadid_np(pthread_t, __uint64_t *); +#elif defined(__linux__) +#include <sys/syscall.h> +#elif defined(__NetBSD__) +#include <lwp.h> +#elif defined(_WIN32) +#include <windows.h> +#endif + +static const char *const RETVAL_PREFIX = "retval:"; +static const char *const SLEEP_PREFIX = "sleep:"; +static const char *const STDERR_PREFIX = "stderr:"; +static const char *const SET_MESSAGE_PREFIX = "set-message:"; +static const char *const PRINT_MESSAGE_COMMAND = "print-message:"; +static const char *const GET_DATA_ADDRESS_PREFIX = "get-data-address-hex:"; +static const char *const GET_STACK_ADDRESS_COMMAND = "get-stack-address-hex:"; +static const char *const GET_HEAP_ADDRESS_COMMAND = "get-heap-address-hex:"; + +static const char *const GET_CODE_ADDRESS_PREFIX = "get-code-address-hex:"; +static const char *const CALL_FUNCTION_PREFIX = "call-function:"; + +static const char *const THREAD_PREFIX = "thread:"; +static const char *const THREAD_COMMAND_NEW = "new"; +static const char *const THREAD_COMMAND_PRINT_IDS = "print-ids"; +static const char *const THREAD_COMMAND_SEGFAULT = "segfault"; + +static const char *const PRINT_PID_COMMAND = "print-pid"; + +static bool g_print_thread_ids = false; +static std::mutex g_print_mutex; +static bool g_threads_do_segfault = false; + +static std::mutex g_jump_buffer_mutex; +static jmp_buf g_jump_buffer; +static bool g_is_segfaulting = false; + +static char g_message[256]; + +static volatile char g_c1 = '0'; +static volatile char g_c2 = '1'; + +static void print_pid() { +#if defined(_WIN32) + fprintf(stderr, "PID: %d\n", ::GetCurrentProcessId()); +#else + fprintf(stderr, "PID: %d\n", getpid()); +#endif +} + +static void print_thread_id() { +// Put in the right magic here for your platform to spit out the thread id (tid) +// that debugserver/lldb-gdbserver would see as a TID. Otherwise, let the else +// clause print out the unsupported text so that the unit test knows to skip +// verifying thread ids. +#if defined(__APPLE__) + __uint64_t tid = 0; + pthread_threadid_np(pthread_self(), &tid); + printf("%" PRIx64, tid); +#elif defined(__linux__) + // This is a call to gettid() via syscall. + printf("%" PRIx64, static_cast<uint64_t>(syscall(__NR_gettid))); +#elif defined(__NetBSD__) + // Technically lwpid_t is 32-bit signed integer + printf("%" PRIx64, static_cast<uint64_t>(_lwp_self())); +#elif defined(_WIN32) + printf("%" PRIx64, static_cast<uint64_t>(::GetCurrentThreadId())); +#else + printf("{no-tid-support}"); +#endif +} + +static void signal_handler(int signo) { +#if defined(_WIN32) + // No signal support on Windows. +#else + const char *signal_name = nullptr; + switch (signo) { + case SIGUSR1: + signal_name = "SIGUSR1"; + break; + case SIGSEGV: + signal_name = "SIGSEGV"; + break; + default: + signal_name = nullptr; + } + + // Print notice that we received the signal on a given thread. + { + std::lock_guard<std::mutex> lock(g_print_mutex); + if (signal_name) + printf("received %s on thread id: ", signal_name); + else + printf("received signo %d (%s) on thread id: ", signo, strsignal(signo)); + print_thread_id(); + printf("\n"); + } + + // Reset the signal handler if we're one of the expected signal handlers. + switch (signo) { + case SIGSEGV: + if (g_is_segfaulting) { + // Fix up the pointer we're writing to. This needs to happen if nothing + // intercepts the SIGSEGV (i.e. if somebody runs this from the command + // line). + longjmp(g_jump_buffer, 1); + } + break; + case SIGUSR1: + if (g_is_segfaulting) { + // Fix up the pointer we're writing to. This is used to test gdb remote + // signal delivery. A SIGSEGV will be raised when the thread is created, + // switched out for a SIGUSR1, and then this code still needs to fix the + // seg fault. (i.e. if somebody runs this from the command line). + longjmp(g_jump_buffer, 1); + } + break; + } + + // Reset the signal handler. + sig_t sig_result = signal(signo, signal_handler); + if (sig_result == SIG_ERR) { + fprintf(stderr, "failed to set signal handler: errno=%d\n", errno); + exit(1); + } +#endif +} + +static void swap_chars() { + g_c1 = '1'; + g_c2 = '0'; + + g_c1 = '0'; + g_c2 = '1'; +} + +static void hello() { + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("hello, world\n"); +} + +static void *thread_func(void *arg) { + static std::atomic<int> s_thread_index(1); + const int this_thread_index = s_thread_index++; + if (g_print_thread_ids) { + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("thread %d id: ", this_thread_index); + print_thread_id(); + printf("\n"); + } + + if (g_threads_do_segfault) { + // Sleep for a number of seconds based on the thread index. + // TODO add ability to send commands to test exe so we can + // handle timing more precisely. This is clunky. All we're + // trying to do is add predictability as to the timing of + // signal generation by created threads. + int sleep_seconds = 2 * (this_thread_index - 1); + std::this_thread::sleep_for(std::chrono::seconds(sleep_seconds)); + + // Test creating a SEGV. + { + std::lock_guard<std::mutex> lock(g_jump_buffer_mutex); + g_is_segfaulting = true; + int *bad_p = nullptr; + if (setjmp(g_jump_buffer) == 0) { + // Force a seg fault signal on this thread. + *bad_p = 0; + } else { + // Tell the system we're no longer seg faulting. + // Used by the SIGUSR1 signal handler that we inject + // in place of the SIGSEGV so it only tries to + // recover from the SIGSEGV if this seg fault code + // was in play. + g_is_segfaulting = false; + } + } + + { + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("thread "); + print_thread_id(); + printf(": past SIGSEGV\n"); + } + } + + int sleep_seconds_remaining = 60; + std::this_thread::sleep_for(std::chrono::seconds(sleep_seconds_remaining)); + + return nullptr; +} + +int main(int argc, char **argv) { + lldb_enable_attach(); + + std::vector<std::thread> threads; + std::unique_ptr<uint8_t[]> heap_array_up; + int return_value = 0; + +#if !defined(_WIN32) + // Set the signal handler. + sig_t sig_result = signal(SIGALRM, signal_handler); + if (sig_result == SIG_ERR) { + fprintf(stderr, "failed to set SIGALRM signal handler: errno=%d\n", errno); + exit(1); + } + + sig_result = signal(SIGUSR1, signal_handler); + if (sig_result == SIG_ERR) { + fprintf(stderr, "failed to set SIGUSR1 handler: errno=%d\n", errno); + exit(1); + } + + sig_result = signal(SIGSEGV, signal_handler); + if (sig_result == SIG_ERR) { + fprintf(stderr, "failed to set SIGUSR1 handler: errno=%d\n", errno); + exit(1); + } +#endif + + // Process command line args. + for (int i = 1; i < argc; ++i) { + if (std::strstr(argv[i], STDERR_PREFIX)) { + // Treat remainder as text to go to stderr. + fprintf(stderr, "%s\n", (argv[i] + strlen(STDERR_PREFIX))); + } else if (std::strstr(argv[i], RETVAL_PREFIX)) { + // Treat as the return value for the program. + return_value = std::atoi(argv[i] + strlen(RETVAL_PREFIX)); + } else if (std::strstr(argv[i], SLEEP_PREFIX)) { + // Treat as the amount of time to have this process sleep (in seconds). + int sleep_seconds_remaining = std::atoi(argv[i] + strlen(SLEEP_PREFIX)); + + // Loop around, sleeping until all sleep time is used up. Note that + // signals will cause sleep to end early with the number of seconds + // remaining. + std::this_thread::sleep_for( + std::chrono::seconds(sleep_seconds_remaining)); + + } else if (std::strstr(argv[i], SET_MESSAGE_PREFIX)) { + // Copy the contents after "set-message:" to the g_message buffer. + // Used for reading inferior memory and verifying contents match + // expectations. + strncpy(g_message, argv[i] + strlen(SET_MESSAGE_PREFIX), + sizeof(g_message)); + + // Ensure we're null terminated. + g_message[sizeof(g_message) - 1] = '\0'; + + } else if (std::strstr(argv[i], PRINT_MESSAGE_COMMAND)) { + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("message: %s\n", g_message); + } else if (std::strstr(argv[i], GET_DATA_ADDRESS_PREFIX)) { + volatile void *data_p = nullptr; + + if (std::strstr(argv[i] + strlen(GET_DATA_ADDRESS_PREFIX), "g_message")) + data_p = &g_message[0]; + else if (std::strstr(argv[i] + strlen(GET_DATA_ADDRESS_PREFIX), "g_c1")) + data_p = &g_c1; + else if (std::strstr(argv[i] + strlen(GET_DATA_ADDRESS_PREFIX), "g_c2")) + data_p = &g_c2; + + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("data address: %p\n", data_p); + } else if (std::strstr(argv[i], GET_HEAP_ADDRESS_COMMAND)) { + // Create a byte array if not already present. + if (!heap_array_up) + heap_array_up.reset(new uint8_t[32]); + + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("heap address: %p\n", heap_array_up.get()); + + } else if (std::strstr(argv[i], GET_STACK_ADDRESS_COMMAND)) { + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("stack address: %p\n", &return_value); + } else if (std::strstr(argv[i], GET_CODE_ADDRESS_PREFIX)) { + void (*func_p)() = nullptr; + + if (std::strstr(argv[i] + strlen(GET_CODE_ADDRESS_PREFIX), "hello")) + func_p = hello; + else if (std::strstr(argv[i] + strlen(GET_CODE_ADDRESS_PREFIX), + "swap_chars")) + func_p = swap_chars; + + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("code address: %p\n", func_p); + } else if (std::strstr(argv[i], CALL_FUNCTION_PREFIX)) { + void (*func_p)() = nullptr; + + // Defaut to providing the address of main. + if (std::strcmp(argv[i] + strlen(CALL_FUNCTION_PREFIX), "hello") == 0) + func_p = hello; + else if (std::strcmp(argv[i] + strlen(CALL_FUNCTION_PREFIX), + "swap_chars") == 0) + func_p = swap_chars; + else { + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("unknown function: %s\n", + argv[i] + strlen(CALL_FUNCTION_PREFIX)); + } + if (func_p) + func_p(); + } else if (std::strstr(argv[i], THREAD_PREFIX)) { + // Check if we're creating a new thread. + if (std::strstr(argv[i] + strlen(THREAD_PREFIX), THREAD_COMMAND_NEW)) { + threads.push_back(std::thread(thread_func, nullptr)); + } else if (std::strstr(argv[i] + strlen(THREAD_PREFIX), + THREAD_COMMAND_PRINT_IDS)) { + // Turn on thread id announcing. + g_print_thread_ids = true; + + // And announce us. + { + std::lock_guard<std::mutex> lock(g_print_mutex); + printf("thread 0 id: "); + print_thread_id(); + printf("\n"); + } + } else if (std::strstr(argv[i] + strlen(THREAD_PREFIX), + THREAD_COMMAND_SEGFAULT)) { + g_threads_do_segfault = true; + } else { + // At this point we don't do anything else with threads. + // Later use thread index and send command to thread. + } + } else if (std::strstr(argv[i], PRINT_PID_COMMAND)) { + print_pid(); + } else { + // Treat the argument as text for stdout. + printf("%s\n", argv[i]); + } + } + + // If we launched any threads, join them + for (std::vector<std::thread>::iterator it = threads.begin(); + it != threads.end(); ++it) + it->join(); + + return return_value; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py new file mode 100644 index 00000000000..ff708310ca9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py @@ -0,0 +1,103 @@ + +import time + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestPlatformProcessConnect(gdbremote_testcase.GdbRemoteTestCaseBase): + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + super(TestPlatformProcessConnect, self).setUp() + self._initial_platform = lldb.DBG.GetSelectedPlatform() + + def tearDown(self): + lldb.DBG.SetSelectedPlatform(self._initial_platform) + super(TestPlatformProcessConnect, self).tearDown() + + @llgs_test + @no_debug_info_test + @skipIf(remote=False) + @expectedFailureAll(hostoslist=["windows"], triple='.*-android') + def test_platform_process_connect(self): + self.build() + self.init_llgs_test(False) + + working_dir = lldb.remote_platform.GetWorkingDirectory() + src = lldb.SBFileSpec(self.getBuildArtifact("a.out")) + dest = lldb.SBFileSpec(os.path.join(working_dir, "a.out")) + err = lldb.remote_platform.Put(src, dest) + if err.Fail(): + raise RuntimeError( + "Unable copy '%s' to '%s'.\n>>> %s" % + (f, wd, err.GetCString())) + + m = re.search("^(.*)://([^:/]*)", configuration.lldb_platform_url) + protocol = m.group(1) + hostname = m.group(2) + unix_protocol = protocol.startswith("unix-") + if unix_protocol: + p = re.search("^(.*)-connect", protocol) + path = lldbutil.join_remote_paths(configuration.lldb_platform_working_dir, + self.getBuildDirBasename(), "platform-%d.sock" % int(time.time())) + listen_url = "%s://%s" % (p.group(1), path) + else: + listen_url = "*:0" + + port_file = "%s/port" % working_dir + commandline_args = [ + "platform", + "--listen", + listen_url, + "--socket-file", + port_file, + "--", + "%s/a.out" % + working_dir, + "foo"] + self.spawnSubprocess( + self.debug_monitor_exe, + commandline_args, + install_remote=False) + self.addTearDownHook(self.cleanupSubprocesses) + + socket_id = lldbutil.wait_for_file_on_target(self, port_file) + + new_debugger = lldb.SBDebugger.Create() + new_debugger.SetAsync(False) + + def del_debugger(new_debugger=new_debugger): + del new_debugger + self.addTearDownHook(del_debugger) + + new_platform = lldb.SBPlatform(lldb.remote_platform.GetName()) + new_debugger.SetSelectedPlatform(new_platform) + new_interpreter = new_debugger.GetCommandInterpreter() + + if unix_protocol: + connect_url = "%s://%s%s" % (protocol, hostname, socket_id) + else: + connect_url = "%s://%s:%s" % (protocol, hostname, socket_id) + + command = "platform connect %s" % (connect_url) + result = lldb.SBCommandReturnObject() + new_interpreter.HandleCommand(command, result) + self.assertTrue( + result.Succeeded(), + "platform process connect failed: %s" % + result.GetOutput()) + + target = new_debugger.GetSelectedTarget() + process = target.GetProcess() + thread = process.GetThreadAtIndex(0) + + breakpoint = target.BreakpointCreateByName("main") + process.Continue() + + frame = thread.GetFrameAtIndex(0) + self.assertEqual(frame.GetFunction().GetName(), "main") + self.assertEqual(frame.FindVariable("argc").GetValueAsSigned(), 2) + process.Continue() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/main.cpp new file mode 100644 index 00000000000..c7ebe0759a4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/main.cpp @@ -0,0 +1,6 @@ +#include <cstdio> + +int main(int argc, char **argv) { + printf("argc: %d\n", argc); + return argv[0][0]; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/register-reading/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/register-reading/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/register-reading/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/register-reading/TestGdbRemoteGPacket.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/register-reading/TestGdbRemoteGPacket.py new file mode 100644 index 00000000000..a27cb01e938 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/register-reading/TestGdbRemoteGPacket.py @@ -0,0 +1,154 @@ + + +import gdbremote_testcase +import textwrap +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +def _extract_register_value(reg_info, reg_bank, byte_order, bytes_per_entry=8): + reg_offset = int(reg_info["offset"])*2 + reg_byte_size = int(2 * int(reg_info["bitsize"]) / 8) + # Create slice with the contents of the register. + reg_slice = reg_bank[reg_offset:reg_offset+reg_byte_size] + + reg_value = [] + # Wrap slice according to bytes_per_entry. + for entry in textwrap.wrap(reg_slice, 2 * bytes_per_entry): + # Invert the bytes order if target uses little-endian. + if byte_order == lldb.eByteOrderLittle: + entry = "".join(reversed([entry[i:i+2] for i in range(0, + len(entry),2)])) + reg_value.append("0x" + entry) + + return reg_value + + +class TestGdbRemoteGPacket(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def run_test_g_packet(self): + self.build() + self.prep_debug_monitor_and_inferior() + self.test_sequence.add_log_lines( + ["read packet: $g#67", + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "register_bank"}}], + True) + self.connect_to_debug_monitor() + context = self.expect_gdbremote_sequence() + register_bank = context.get("register_bank") + self.assertTrue(register_bank[0] != 'E') + + self.test_sequence.add_log_lines( + ["read packet: $G" + register_bank + "#00", + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "G_reply"}}], + True) + context = self.expect_gdbremote_sequence() + self.assertTrue(context.get("G_reply")[0] != 'E') + + @skipIfOutOfTreeDebugserver + @debugserver_test + @skipIfDarwinEmbedded + def test_g_packet_debugserver(self): + self.init_debugserver_test() + self.run_test_g_packet() + + @skipIf(archs=no_match(["x86_64"])) + def g_returns_correct_data(self, with_suffix): + procs = self.prep_debug_monitor_and_inferior() + + self.add_register_info_collection_packets() + if with_suffix: + self.add_thread_suffix_request_packets() + self.add_threadinfo_collection_packets() + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Gather register info. + reg_infos = self.parse_register_info_packets(context) + self.assertIsNotNone(reg_infos) + self.add_lldb_register_index(reg_infos) + # Index register info entries by name. + reg_infos = {info['name']: info for info in reg_infos} + + # Gather thread info. + if with_suffix: + threads = self.parse_threadinfo_packets(context) + self.assertIsNotNone(threads) + thread_id = threads[0] + self.assertIsNotNone(thread_id) + else: + thread_id = None + + # Send vCont packet to resume the inferior. + self.test_sequence.add_log_lines(["read packet: $vCont;c#a8", + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", + "capture": {1: "hex_exit_code"}}, + ], + True) + + # Send g packet to retrieve the register bank + if thread_id: + g_request = "read packet: $g;thread:{:x}#00".format(thread_id) + else: + g_request = "read packet: $g#00" + self.test_sequence.add_log_lines( + [g_request, + {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", + "capture": {1: "register_bank"}}], + True) + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + reg_bank = context.get("register_bank") + self.assertTrue(reg_bank[0] != 'E') + + byte_order = self.get_target_byte_order() + get_reg_value = lambda reg_name : _extract_register_value( + reg_infos[reg_name], reg_bank, byte_order) + + self.assertEqual(['0x0102030405060708'], get_reg_value('r8')) + self.assertEqual(['0x1112131415161718'], get_reg_value('r9')) + self.assertEqual(['0x2122232425262728'], get_reg_value('r10')) + self.assertEqual(['0x3132333435363738'], get_reg_value('r11')) + self.assertEqual(['0x4142434445464748'], get_reg_value('r12')) + self.assertEqual(['0x5152535455565758'], get_reg_value('r13')) + self.assertEqual(['0x6162636465666768'], get_reg_value('r14')) + self.assertEqual(['0x7172737475767778'], get_reg_value('r15')) + + self.assertEqual( + ['0x020406080a0c0e01', '0x030507090b0d0f00'], get_reg_value('xmm8')) + self.assertEqual( + ['0x121416181a1c1e11', '0x131517191b1d1f10'], get_reg_value('xmm9')) + self.assertEqual( + ['0x222426282a2c2e21', '0x232527292b2d2f20'], get_reg_value('xmm10')) + self.assertEqual( + ['0x323436383a3c3e31', '0x333537393b3d3f30'], get_reg_value('xmm11')) + self.assertEqual( + ['0x424446484a4c4e41', '0x434547494b4d4f40'], get_reg_value('xmm12')) + self.assertEqual( + ['0x525456585a5c5e51', '0x535557595b5d5f50'], get_reg_value('xmm13')) + self.assertEqual( + ['0x626466686a6c6e61', '0x636567696b6d6f60'], get_reg_value('xmm14')) + self.assertEqual( + ['0x727476787a7c7e71', '0x737577797b7d7f70'], get_reg_value('xmm15')) + + @expectedFailureNetBSD + @llgs_test + def test_g_returns_correct_data_with_suffix_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.g_returns_correct_data(True) + + @expectedFailureNetBSD + @llgs_test + def test_g_returns_correct_data_no_suffix_llgs(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + self.g_returns_correct_data(False) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/register-reading/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/register-reading/main.cpp new file mode 100644 index 00000000000..fca0c723bde --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/register-reading/main.cpp @@ -0,0 +1,54 @@ +#include <cstdint> + +int main() { +#if defined(__x86_64__) + struct alignas(16) xmm_t { + uint64_t a, b; + }; + uint64_t r8 = 0x0102030405060708; + uint64_t r9 = 0x1112131415161718; + uint64_t r10 = 0x2122232425262728; + uint64_t r11 = 0x3132333435363738; + uint64_t r12 = 0x4142434445464748; + uint64_t r13 = 0x5152535455565758; + uint64_t r14 = 0x6162636465666768; + uint64_t r15 = 0x7172737475767778; + + xmm_t xmm8 = {0x020406080A0C0E01, 0x030507090B0D0F00}; + xmm_t xmm9 = {0x121416181A1C1E11, 0x131517191B1D1F10}; + xmm_t xmm10 = {0x222426282A2C2E21, 0x232527292B2D2F20}; + xmm_t xmm11 = {0x323436383A3C3E31, 0x333537393B3D3F30}; + xmm_t xmm12 = {0x424446484A4C4E41, 0x434547494B4D4F40}; + xmm_t xmm13 = {0x525456585A5C5E51, 0x535557595B5D5F50}; + xmm_t xmm14 = {0x626466686A6C6E61, 0x636567696B6D6F60}; + xmm_t xmm15 = {0x727476787A7C7E71, 0x737577797B7D7F70}; + + asm volatile("movq %0, %%r8\n\t" + "movq %1, %%r9\n\t" + "movq %2, %%r10\n\t" + "movq %3, %%r11\n\t" + "movq %4, %%r12\n\t" + "movq %5, %%r13\n\t" + "movq %6, %%r14\n\t" + "movq %7, %%r15\n\t" + "\n\t" + "movaps %8, %%xmm8\n\t" + "movaps %9, %%xmm9\n\t" + "movaps %10, %%xmm10\n\t" + "movaps %11, %%xmm11\n\t" + "movaps %12, %%xmm12\n\t" + "movaps %13, %%xmm13\n\t" + "movaps %14, %%xmm14\n\t" + "movaps %15, %%xmm15\n\t" + "\n\t" + "int3" + : + : "g"(r8), "g"(r9), "g"(r10), "g"(r11), "g"(r12), "g"(r13), + "g"(r14), "g"(r15), "m"(xmm8), "m"(xmm9), "m"(xmm10), + "m"(xmm11), "m"(xmm12), "m"(xmm13), "m"(xmm14), "m"(xmm15) + : "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", + "%xmm8", "%xmm9", "%xmm10", "%xmm11", "%xmm12", "%xmm13", + "%xmm14", "%xmm15"); +#endif + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/signal-filtering/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/signal-filtering/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/signal-filtering/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/signal-filtering/TestGdbRemote_QPassSignals.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/signal-filtering/TestGdbRemote_QPassSignals.py new file mode 100644 index 00000000000..72e0d94d4de --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/signal-filtering/TestGdbRemote_QPassSignals.py @@ -0,0 +1,116 @@ +# This test makes sure that lldb-server supports and properly handles +# QPassSignals GDB protocol package. + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + +class TestGdbRemote_QPassSignals(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def expect_signal(self, expected_signo): + self.test_sequence.add_log_lines(["read packet: $vCont;c#a8", + {"direction": "send", + "regex": r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", + "capture": {1: "hex_exit_code"}}, + ], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + hex_exit_code = context.get("hex_exit_code") + self.assertIsNotNone(hex_exit_code) + self.assertEqual(int(hex_exit_code, 16), expected_signo) + + def expect_exit_code(self, exit_code): + self.test_sequence.add_log_lines( + ["read packet: $vCont;c#a8", + "send packet: $W{0:02x}#00".format(exit_code)], + True) + self.expect_gdbremote_sequence() + + + def ignore_signals(self, signals): + def signal_name_to_hex(signame): + return format(lldbutil.get_signal_number(signame), 'x') + signals_str = ";".join(map(signal_name_to_hex, signals)) + + self.test_sequence.add_log_lines(["read packet: $QPassSignals:" + + signals_str + " #00", + "send packet: $OK#00"], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + @llgs_test + @skipUnlessPlatform(["linux", "android"]) + def test_q_pass_signals(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + procs = self.prep_debug_monitor_and_inferior() + expected_signals = ["SIGSEGV", + "SIGALRM", "SIGFPE", "SIGBUS", "SIGINT", "SIGHUP"] + signals_to_ignore = ["SIGUSR1", "SIGUSR2"] + self.ignore_signals(signals_to_ignore) + for signal_name in expected_signals: + signo = lldbutil.get_signal_number(signal_name) + self.expect_signal(signo) + self.expect_exit_code(len(signals_to_ignore)) + + @llgs_test + @skipUnlessPlatform(["linux", "android"]) + def test_change_signals_at_runtime(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + procs = self.prep_debug_monitor_and_inferior() + expected_signals = ["SIGSEGV", "SIGUSR1", "SIGUSR2", + "SIGALRM", "SIGHUP"] + signals_to_ignore = ["SIGFPE", "SIGBUS", "SIGINT"] + + for signal_name in expected_signals: + signo = lldbutil.get_signal_number(signal_name) + self.expect_signal(signo) + if signal_name == "SIGALRM": + self.ignore_signals(signals_to_ignore) + self.expect_exit_code(len(signals_to_ignore)) + + @skipIfWindows # no signal support + @expectedFailureNetBSD + @llgs_test + def test_default_signals_behavior(self): + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + procs = self.prep_debug_monitor_and_inferior() + expected_signals = ["SIGSEGV", "SIGUSR1", "SIGUSR2", + "SIGALRM", "SIGFPE", "SIGBUS", "SIGINT", "SIGHUP"] + for signal_name in expected_signals: + signo = lldbutil.get_signal_number(signal_name) + self.expect_signal(signo) + self.expect_exit_code(0) + + + @llgs_test + @skipUnlessPlatform(["linux", "android"]) + def test_support_q_pass_signals(self): + self.init_llgs_test() + self.build() + + # Start up the stub and start/prep the inferior. + self.set_inferior_startup_launch() + procs = self.prep_debug_monitor_and_inferior() + self.add_qSupported_packets() + + # Run the packet stream. + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + # Retrieve the qSupported features and check QPassSignals+ + supported_dict = self.parse_qSupported_response(context) + self.assertEqual(supported_dict["QPassSignals"], "+") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/signal-filtering/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/signal-filtering/main.cpp new file mode 100644 index 00000000000..fe33c291958 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/signal-filtering/main.cpp @@ -0,0 +1,36 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include <signal.h> +#include <stdio.h> +#include <vector> + +static int signal_counter = 0; + +static void count_signal(int signo) { + ++signal_counter; + printf("Signal %d\n", signo); +} + +static void raise_signals() { + std::vector<int> signals( + {SIGSEGV, SIGUSR1, SIGUSR2, SIGALRM, SIGFPE, SIGBUS, SIGINT, SIGHUP}); + + for (int signal_num : signals) { + signal(signal_num, count_signal); + } + + for (int signal_num : signals) { + raise(signal_num); + } +} + +int main() { + raise_signals(); + return signal_counter; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py new file mode 100644 index 00000000000..958d6449b51 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py @@ -0,0 +1,198 @@ + +from __future__ import print_function + + +import re +import select +import threading +import traceback +import codecs + +from six.moves import queue +from lldbsuite.support import seven + + +def _handle_output_packet_string(packet_contents): + if (not packet_contents) or (len(packet_contents) < 1): + return None + elif packet_contents[0] != "O": + return None + elif packet_contents == "OK": + return None + else: + return seven.unhexlify(packet_contents[1:]) + + +def _dump_queue(the_queue): + while not the_queue.empty(): + print(codecs.encode(the_queue.get(True), "string_escape")) + print("\n") + + +class PumpQueues(object): + + def __init__(self): + self._output_queue = queue.Queue() + self._packet_queue = queue.Queue() + + def output_queue(self): + return self._output_queue + + def packet_queue(self): + return self._packet_queue + + def verify_queues_empty(self): + # Warn if there is any content left in any of the queues. + # That would represent unmatched packets. + if not self.output_queue().empty(): + print("warning: output queue entries still exist:") + _dump_queue(self.output_queue()) + print("from here:") + traceback.print_stack() + + if not self.packet_queue().empty(): + print("warning: packet queue entries still exist:") + _dump_queue(self.packet_queue()) + print("from here:") + traceback.print_stack() + + +class SocketPacketPump(object): + """A threaded packet reader that partitions packets into two streams. + + All incoming $O packet content is accumulated with the current accumulation + state put into the OutputQueue. + + All other incoming packets are placed in the packet queue. + + A select thread can be started and stopped, and runs to place packet + content into the two queues. + """ + + _GDB_REMOTE_PACKET_REGEX = re.compile(r'^\$([^\#]*)#[0-9a-fA-F]{2}') + + def __init__(self, pump_socket, pump_queues, logger=None): + if not pump_socket: + raise Exception("pump_socket cannot be None") + + self._thread = None + self._stop_thread = False + self._socket = pump_socket + self._logger = logger + self._receive_buffer = "" + self._accumulated_output = "" + self._pump_queues = pump_queues + + def __enter__(self): + """Support the python 'with' statement. + + Start the pump thread.""" + self.start_pump_thread() + return self + + def __exit__(self, exit_type, value, the_traceback): + """Support the python 'with' statement. + + Shut down the pump thread.""" + self.stop_pump_thread() + + def start_pump_thread(self): + if self._thread: + raise Exception("pump thread is already running") + self._stop_thread = False + self._thread = threading.Thread(target=self._run_method) + self._thread.start() + + def stop_pump_thread(self): + self._stop_thread = True + if self._thread: + self._thread.join() + + def _process_new_bytes(self, new_bytes): + if not new_bytes: + return + if len(new_bytes) < 1: + return + + # Add new bytes to our accumulated unprocessed packet bytes. + self._receive_buffer += new_bytes + + # Parse fully-formed packets into individual packets. + has_more = len(self._receive_buffer) > 0 + while has_more: + if len(self._receive_buffer) <= 0: + has_more = False + # handle '+' ack + elif self._receive_buffer[0] == "+": + self._pump_queues.packet_queue().put("+") + self._receive_buffer = self._receive_buffer[1:] + if self._logger: + self._logger.debug( + "parsed packet from stub: +\n" + + "new receive_buffer: {}".format( + self._receive_buffer)) + else: + packet_match = self._GDB_REMOTE_PACKET_REGEX.match( + self._receive_buffer) + if packet_match: + # Our receive buffer matches a packet at the + # start of the receive buffer. + new_output_content = _handle_output_packet_string( + packet_match.group(1)) + if new_output_content: + # This was an $O packet with new content. + self._accumulated_output += new_output_content + self._pump_queues.output_queue().put(self._accumulated_output) + else: + # Any packet other than $O. + self._pump_queues.packet_queue().put(packet_match.group(0)) + + # Remove the parsed packet from the receive + # buffer. + self._receive_buffer = self._receive_buffer[ + len(packet_match.group(0)):] + if self._logger: + self._logger.debug( + "parsed packet from stub: " + + packet_match.group(0)) + self._logger.debug( + "new receive_buffer: " + + self._receive_buffer) + else: + # We don't have enough in the receive bufferto make a full + # packet. Stop trying until we read more. + has_more = False + + def _run_method(self): + self._receive_buffer = "" + self._accumulated_output = "" + + if self._logger: + self._logger.info("socket pump starting") + + # Keep looping around until we're asked to stop the thread. + while not self._stop_thread: + can_read, _, _ = select.select([self._socket], [], [], 0) + if can_read and self._socket in can_read: + try: + new_bytes = seven.bitcast_to_string(self._socket.recv(4096)) + if self._logger and new_bytes and len(new_bytes) > 0: + self._logger.debug( + "pump received bytes: {}".format(new_bytes)) + except: + # Likely a closed socket. Done with the pump thread. + if self._logger: + self._logger.debug( + "socket read failed, stopping pump read thread\n" + + traceback.format_exc(3)) + break + self._process_new_bytes(new_bytes) + + if self._logger: + self._logger.info("socket pump exiting") + + def get_accumulated_output(self): + return self._accumulated_output + + def get_receive_buffer(self): + return self._receive_buffer diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py new file mode 100644 index 00000000000..6f07b2f9e28 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py @@ -0,0 +1,62 @@ + + +import unittest2 +import re + +from lldbgdbserverutils import * + + +class TestLldbGdbServerUtils(unittest2.TestCase): + + def test_entry_exact_payload_match(self): + entry = GdbRemoteEntry(is_send_to_remote=False, exact_payload="$OK#9a") + entry.assert_match(self, "$OK#9a") + + def test_entry_exact_payload_match_ignores_checksum(self): + entry = GdbRemoteEntry(is_send_to_remote=False, exact_payload="$OK#9a") + entry.assert_match(self, "$OK#00") + + def test_entry_creates_context(self): + entry = GdbRemoteEntry(is_send_to_remote=False, exact_payload="$OK#9a") + context = entry.assert_match(self, "$OK#9a") + self.assertIsNotNone(context) + + def test_entry_regex_matches(self): + entry = GdbRemoteEntry( + is_send_to_remote=False, + regex=re.compile(r"^\$QC([0-9a-fA-F]+)#"), + capture={ + 1: "thread_id"}) + context = entry.assert_match(self, "$QC980#00") + + def test_entry_regex_saves_match(self): + entry = GdbRemoteEntry( + is_send_to_remote=False, + regex=re.compile(r"^\$QC([0-9a-fA-F]+)#"), + capture={ + 1: "thread_id"}) + context = entry.assert_match(self, "$QC980#00") + self.assertEqual(context["thread_id"], "980") + + def test_entry_regex_expect_captures_success(self): + context = {"thread_id": "980"} + entry = GdbRemoteEntry( + is_send_to_remote=False, + regex=re.compile(r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+)"), + expect_captures={ + 2: "thread_id"}) + entry.assert_match(self, "$T11thread:980;", context=context) + + def test_entry_regex_expect_captures_raises_on_fail(self): + context = {"thread_id": "980"} + entry = GdbRemoteEntry( + is_send_to_remote=False, + regex=re.compile(r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+)"), + expect_captures={ + 2: "thread_id"}) + try: + entry.assert_match(self, "$T11thread:970;", context=context) + self.fail() + except AssertionError: + # okay + return None diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/thread-name/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/thread-name/Makefile new file mode 100644 index 00000000000..de4ec12b13c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/thread-name/Makefile @@ -0,0 +1,4 @@ +ENABLE_THREADS := YES +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/thread-name/TestGdbRemoteThreadName.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/thread-name/TestGdbRemoteThreadName.py new file mode 100644 index 00000000000..9ec40c11742 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/thread-name/TestGdbRemoteThreadName.py @@ -0,0 +1,41 @@ + +import gdbremote_testcase +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class TestGdbRemoteThreadName(gdbremote_testcase.GdbRemoteTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def run_and_check_name(self, expected_name): + self.test_sequence.add_log_lines(["read packet: $vCont;c#a8", + {"direction": "send", + "regex": + r"^\$T([0-9a-fA-F]{2})([^#]+)#[0-9a-fA-F]{2}$", + "capture": { + 1: "signal", + 2: "key_vals_text"}}, + ], + True) + + context = self.expect_gdbremote_sequence() + self.assertIsNotNone(context) + + sigint = lldbutil.get_signal_number("SIGINT") + self.assertEqual(sigint, int(context.get("signal"), 16)) + kv_dict = self.parse_key_val_dict(context.get("key_vals_text")) + self.assertEqual(expected_name, kv_dict.get("name")) + + @skipIfWindows # the test is not updated for Windows. + @llgs_test + def test(self): + """ Make sure lldb-server can retrieve inferior thread name""" + self.init_llgs_test() + self.build() + self.set_inferior_startup_launch() + procs = self.prep_debug_monitor_and_inferior() + + self.run_and_check_name("hello world") + self.run_and_check_name("goodbye world") diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/thread-name/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/thread-name/main.cpp new file mode 100644 index 00000000000..86f0ecf76c7 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-server/thread-name/main.cpp @@ -0,0 +1,24 @@ +#include <pthread.h> +#include <signal.h> + +void set_thread_name(const char *name) { +#if defined(__APPLE__) + ::pthread_setname_np(name); +#elif defined(__FreeBSD__) + ::pthread_set_name_np(::pthread_self(), name); +#elif defined(__OpenBSD__) + ::pthread_set_name_np(::pthread_self(), name); +#elif defined(__linux__) + ::pthread_setname_np(::pthread_self(), name); +#elif defined(__NetBSD__) + ::pthread_setname_np(::pthread_self(), "%s", const_cast<char *>(name)); +#endif +} + +int main() { + set_thread_name("hello world"); + raise(SIGINT); + set_thread_name("goodbye world"); + raise(SIGINT); + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/.categories b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/.categories new file mode 100644 index 00000000000..ce2cfd048e3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/.categories @@ -0,0 +1 @@ +lldb-vscode diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/TestVSCode_attach.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/TestVSCode_attach.py new file mode 100644 index 00000000000..835bd0b86ef --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/TestVSCode_attach.py @@ -0,0 +1,189 @@ +""" +Test lldb-vscode setBreakpoints request +""" + + +import unittest2 +import vscode +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import lldbvscode_testcase +import os +import shutil +import subprocess +import tempfile +import threading +import time + + +def spawn_and_wait(program, delay): + if delay: + time.sleep(delay) + process = subprocess.Popen([program], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + process.wait() + + +class TestVSCode_attach(lldbvscode_testcase.VSCodeTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def set_and_hit_breakpoint(self, continueToExit=True): + source = 'main.c' + breakpoint1_line = line_number(source, '// breakpoint 1') + lines = [breakpoint1_line] + # Set breakoint in the thread function so we can step the threads + breakpoint_ids = self.set_source_breakpoints(source, lines) + self.assertEqual(len(breakpoint_ids), len(lines), + "expect correct number of breakpoints") + self.continue_to_breakpoints(breakpoint_ids) + if continueToExit: + self.continue_to_exit() + + + @skipIfWindows + @skipIfNetBSD # Hangs on NetBSD as well + def test_by_pid(self): + ''' + Tests attaching to a process by process ID. + ''' + self.build_and_create_debug_adaptor() + program = self.getBuildArtifact("a.out") + self.process = subprocess.Popen([program], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + self.attach(pid=self.process.pid) + self.set_and_hit_breakpoint(continueToExit=True) + + @skipIfWindows + @skipIfNetBSD # Hangs on NetBSD as well + def test_by_name(self): + ''' + Tests attaching to a process by process name. + ''' + self.build_and_create_debug_adaptor() + orig_program = self.getBuildArtifact("a.out") + # Since we are going to attach by process name, we need a unique + # process name that has minimal chance to match a process that is + # already running. To do this we use tempfile.mktemp() to give us a + # full path to a location where we can copy our executable. We then + # run this copy to ensure we don't get the error "more that one + # process matches 'a.out'". + program = tempfile.mktemp() + shutil.copyfile(orig_program, program) + shutil.copymode(orig_program, program) + + # Use a file as a synchronization point between test and inferior. + pid_file_path = lldbutil.append_to_process_working_directory(self, + "pid_file_%d" % (int(time.time()))) + + def cleanup(): + if os.path.exists(program): + os.unlink(program) + self.run_platform_command("rm %s" % (pid_file_path)) + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + popen = self.spawnSubprocess(program, [pid_file_path]) + self.addTearDownHook(self.cleanupSubprocesses) + + pid = lldbutil.wait_for_file_on_target(self, pid_file_path) + + self.attach(program=program) + self.set_and_hit_breakpoint(continueToExit=True) + + @skipUnlessDarwin + @skipIfDarwin + @skipIfNetBSD # Hangs on NetBSD as well + def test_by_name_waitFor(self): + ''' + Tests attaching to a process by process name and waiting for the + next instance of a process to be launched, ingoring all current + ones. + ''' + self.build_and_create_debug_adaptor() + program = self.getBuildArtifact("a.out") + self.spawn_thread = threading.Thread(target=spawn_and_wait, + args=(program, 1.0,)) + self.spawn_thread.start() + self.attach(program=program, waitFor=True) + self.set_and_hit_breakpoint(continueToExit=True) + + @skipIfWindows + @skipIfDarwin + @skipIfNetBSD # Hangs on NetBSD as well + def test_commands(self): + ''' + Tests the "initCommands", "preRunCommands", "stopCommands", + "exitCommands", and "attachCommands" that can be passed during + attach. + + "initCommands" are a list of LLDB commands that get executed + before the targt is created. + "preRunCommands" are a list of LLDB commands that get executed + after the target has been created and before the launch. + "stopCommands" are a list of LLDB commands that get executed each + time the program stops. + "exitCommands" are a list of LLDB commands that get executed when + the process exits + "attachCommands" are a list of LLDB commands that get executed and + must have a valid process in the selected target in LLDB after + they are done executing. This allows custom commands to create any + kind of debug session. + ''' + self.build_and_create_debug_adaptor() + program = self.getBuildArtifact("a.out") + # Here we just create a target and launch the process as a way to test + # if we are able to use attach commands to create any kind of a target + # and use it for debugging + attachCommands = [ + 'target create -d "%s"' % (program), + 'process launch' + ] + initCommands = ['target list', 'platform list'] + preRunCommands = ['image list a.out', 'image dump sections a.out'] + stopCommands = ['frame variable', 'bt'] + exitCommands = ['expr 2+3', 'expr 3+4'] + self.attach(program=program, + attachCommands=attachCommands, + initCommands=initCommands, + preRunCommands=preRunCommands, + stopCommands=stopCommands, + exitCommands=exitCommands) + + # Get output from the console. This should contain both the + # "initCommands" and the "preRunCommands". + output = self.get_console() + # Verify all "initCommands" were found in console output + self.verify_commands('initCommands', output, initCommands) + # Verify all "preRunCommands" were found in console output + self.verify_commands('preRunCommands', output, preRunCommands) + + functions = ['main'] + breakpoint_ids = self.set_function_breakpoints(functions) + self.assertTrue(len(breakpoint_ids) == len(functions), + "expect one breakpoint") + self.continue_to_breakpoints(breakpoint_ids) + output = self.get_console(timeout=1.0) + self.verify_commands('stopCommands', output, stopCommands) + + # Continue after launch and hit the "pause()" call and stop the target. + # Get output from the console. This should contain both the + # "stopCommands" that were run after we stop. + self.vscode.request_continue() + time.sleep(0.5) + self.vscode.request_pause() + self.vscode.wait_for_stopped() + output = self.get_console(timeout=1.0) + self.verify_commands('stopCommands', output, stopCommands) + + # Continue until the program exits + self.continue_to_exit() + # Get output from the console. This should contain both the + # "exitCommands" that were run after the second breakpoint was hit + output = self.get_console(timeout=1.0) + self.verify_commands('exitCommands', output, exitCommands) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/main.c new file mode 100644 index 00000000000..64d86583ada --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/attach/main.c @@ -0,0 +1,20 @@ +#include <stdio.h> +#include <unistd.h> + +int main(int argc, char const *argv[]) { + lldb_enable_attach(); + + if (argc >= 2) { + // Create the synchronization token. + FILE *f = fopen(argv[1], "wx"); + if (!f) + return 1; + fputs("\n", f); + fflush(f); + fclose(f); + } + + printf("pid = %i\n", getpid()); + sleep(10); + return 0; // breakpoint 1 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setBreakpoints.py new file mode 100644 index 00000000000..8b13b9b161f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setBreakpoints.py @@ -0,0 +1,205 @@ +""" +Test lldb-vscode setBreakpoints request +""" + + +import unittest2 +import vscode +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import lldbvscode_testcase +import os + + +class TestVSCode_setBreakpoints(lldbvscode_testcase.VSCodeTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfWindows + def test_set_and_clear(self): + '''Tests setting and clearing source file and line breakpoints. + This packet is a bit tricky on the debug adaptor side since there + is no "clearBreakpoints" packet. Source file and line breakpoints + are set by sending a "setBreakpoints" packet with a source file + specified and zero or more source lines. If breakpoints have been + set in the source file before, any exising breakpoints must remain + set, and any new breakpoints must be created, and any breakpoints + that were in previous requests and are not in the current request + must be removed. This function tests this setting and clearing + and makes sure things happen correctly. It doesn't test hitting + breakpoints and the functionality of each breakpoint, like + 'conditions' and 'hitCondition' settings.''' + source_basename = 'main.cpp' + source_path = os.path.join(os.getcwd(), source_basename) + first_line = line_number('main.cpp', 'break 12') + second_line = line_number('main.cpp', 'break 13') + third_line = line_number('main.cpp', 'break 14') + lines = [first_line, second_line, third_line] + + # Visual Studio Code Debug Adaptors have no way to specify the file + # without launching or attaching to a process, so we must start a + # process in order to be able to set breakpoints. + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + + # Set 3 breakoints and verify that they got set correctly + response = self.vscode.request_setBreakpoints(source_path, lines) + line_to_id = {} + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(lines), + "expect %u source breakpoints" % (len(lines))) + for breakpoint in breakpoints: + line = breakpoint['line'] + # Store the "id" of the breakpoint that was set for later + line_to_id[line] = breakpoint['id'] + self.assertTrue(line in lines, "line expected in lines array") + self.assertTrue(breakpoint['verified'], + "expect breakpoint verified") + + # There is no breakpoint delete packet, clients just send another + # setBreakpoints packet with the same source file with fewer lines. + # Below we remove the second line entry and call the setBreakpoints + # function again. We want to verify that any breakpoints that were set + # before still have the same "id". This means we didn't clear the + # breakpoint and set it again at the same location. We also need to + # verify that the second line location was actually removed. + lines.remove(second_line) + # Set 2 breakoints and verify that the previous breakoints that were + # set above are still set. + response = self.vscode.request_setBreakpoints(source_path, lines) + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(lines), + "expect %u source breakpoints" % (len(lines))) + for breakpoint in breakpoints: + line = breakpoint['line'] + # Verify the same breakpoints are still set within LLDB by + # making sure the breakpoint ID didn't change + self.assertTrue(line_to_id[line] == breakpoint['id'], + "verify previous breakpoints stayed the same") + self.assertTrue(line in lines, "line expected in lines array") + self.assertTrue(breakpoint['verified'], + "expect breakpoint still verified") + + # Now get the full list of breakpoints set in the target and verify + # we have only 2 breakpoints set. The response above could have told + # us about 2 breakpoints, but we want to make sure we don't have the + # third one still set in the target + response = self.vscode.request_testGetTargetBreakpoints() + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(lines), + "expect %u source breakpoints" % (len(lines))) + for breakpoint in breakpoints: + line = breakpoint['line'] + # Verify the same breakpoints are still set within LLDB by + # making sure the breakpoint ID didn't change + self.assertTrue(line_to_id[line] == breakpoint['id'], + "verify previous breakpoints stayed the same") + self.assertTrue(line in lines, "line expected in lines array") + self.assertTrue(breakpoint['verified'], + "expect breakpoint still verified") + + # Now clear all breakpoints for the source file by passing down an + # empty lines array + lines = [] + response = self.vscode.request_setBreakpoints(source_path, lines) + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(lines), + "expect %u source breakpoints" % (len(lines))) + + # Verify with the target that all breakpoints have been cleared + response = self.vscode.request_testGetTargetBreakpoints() + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(lines), + "expect %u source breakpoints" % (len(lines))) + + # Now set a breakpoint again in the same source file and verify it + # was added. + lines = [second_line] + response = self.vscode.request_setBreakpoints(source_path, lines) + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(lines), + "expect %u source breakpoints" % (len(lines))) + for breakpoint in breakpoints: + line = breakpoint['line'] + self.assertTrue(line in lines, "line expected in lines array") + self.assertTrue(breakpoint['verified'], + "expect breakpoint still verified") + + # Now get the full list of breakpoints set in the target and verify + # we have only 2 breakpoints set. The response above could have told + # us about 2 breakpoints, but we want to make sure we don't have the + # third one still set in the target + response = self.vscode.request_testGetTargetBreakpoints() + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(lines), + "expect %u source breakpoints" % (len(lines))) + for breakpoint in breakpoints: + line = breakpoint['line'] + self.assertTrue(line in lines, "line expected in lines array") + self.assertTrue(breakpoint['verified'], + "expect breakpoint still verified") + + @skipIfWindows + def test_functionality(self): + '''Tests hitting breakpoints and the functionality of a single + breakpoint, like 'conditions' and 'hitCondition' settings.''' + source_basename = 'main.cpp' + source_path = os.path.join(os.getcwd(), source_basename) + loop_line = line_number('main.cpp', '// break loop') + + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + # Set a breakpoint at the loop line with no condition and no + # hitCondition + breakpoint_ids = self.set_source_breakpoints(source_path, [loop_line]) + self.assertTrue(len(breakpoint_ids) == 1, "expect one breakpoint") + self.vscode.request_continue() + + # Verify we hit the breakpoint we just set + self.verify_breakpoint_hit(breakpoint_ids) + + # Make sure i is zero at first breakpoint + i = int(self.vscode.get_local_variable_value('i')) + self.assertTrue(i == 0, 'i != 0 after hitting breakpoint') + + # Update the condition on our breakpoint + new_breakpoint_ids = self.set_source_breakpoints(source_path, + [loop_line], + condition="i==4") + self.assertTrue(breakpoint_ids == new_breakpoint_ids, + "existing breakpoint should have its condition " + "updated") + + self.continue_to_breakpoints(breakpoint_ids) + i = int(self.vscode.get_local_variable_value('i')) + self.assertTrue(i == 4, + 'i != 4 showing conditional works') + + new_breakpoint_ids = self.set_source_breakpoints(source_path, + [loop_line], + hitCondition="2") + + self.assertTrue(breakpoint_ids == new_breakpoint_ids, + "existing breakpoint should have its condition " + "updated") + + # Continue with a hitContidtion of 2 and expect it to skip 1 value + self.continue_to_breakpoints(breakpoint_ids) + i = int(self.vscode.get_local_variable_value('i')) + self.assertTrue(i == 6, + 'i != 6 showing hitCondition works') + + # continue after hitting our hitCondition and make sure it only goes + # up by 1 + self.continue_to_breakpoints(breakpoint_ids) + i = int(self.vscode.get_local_variable_value('i')) + self.assertTrue(i == 7, + 'i != 7 showing post hitCondition hits every time') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setExceptionBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setExceptionBreakpoints.py new file mode 100644 index 00000000000..d20a3434188 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setExceptionBreakpoints.py @@ -0,0 +1,47 @@ +""" +Test lldb-vscode setBreakpoints request +""" + + +import unittest2 +import vscode +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import lldbvscode_testcase + + +class TestVSCode_setExceptionBreakpoints( + lldbvscode_testcase.VSCodeTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfWindows + @expectedFailureNetBSD + def test_functionality(self): + '''Tests setting and clearing exception breakpoints. + This packet is a bit tricky on the debug adaptor side since there + is no "clear exception breakpoints" packet. Exception breakpoints + are set by sending a "setExceptionBreakpoints" packet with zero or + more exception filters. If exception breakpoints have been set + before, any exising breakpoints must remain set, and any new + breakpoints must be created, and any breakpoints that were in + previous requests and are not in the current request must be + removed. This exception tests this setting and clearing and makes + sure things happen correctly. It doesn't test hitting breakpoints + and the functionality of each breakpoint, like 'conditions' and + x'hitCondition' settings. + ''' + # Visual Studio Code Debug Adaptors have no way to specify the file + # without launching or attaching to a process, so we must start a + # process in order to be able to set breakpoints. + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + + filters = ['cpp_throw', 'cpp_catch'] + response = self.vscode.request_setExceptionBreakpoints(filters) + if response: + self.assertTrue(response['success']) + + self.continue_to_exception_breakpoint('C++ Throw') + self.continue_to_exception_breakpoint('C++ Catch') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py new file mode 100644 index 00000000000..2c62bf80fcf --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/TestVSCode_setFunctionBreakpoints.py @@ -0,0 +1,159 @@ +""" +Test lldb-vscode setBreakpoints request +""" + + +import unittest2 +import vscode +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import lldbvscode_testcase + + +class TestVSCode_setFunctionBreakpoints( + lldbvscode_testcase.VSCodeTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfWindows + def test_set_and_clear(self): + '''Tests setting and clearing function breakpoints. + This packet is a bit tricky on the debug adaptor side since there + is no "clearFunction Breakpoints" packet. Function breakpoints + are set by sending a "setFunctionBreakpoints" packet with zero or + more function names. If function breakpoints have been set before, + any exising breakpoints must remain set, and any new breakpoints + must be created, and any breakpoints that were in previous requests + and are not in the current request must be removed. This function + tests this setting and clearing and makes sure things happen + correctly. It doesn't test hitting breakpoints and the functionality + of each breakpoint, like 'conditions' and 'hitCondition' settings. + ''' + # Visual Studio Code Debug Adaptors have no way to specify the file + # without launching or attaching to a process, so we must start a + # process in order to be able to set breakpoints. + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + bp_id_12 = None + functions = ['twelve'] + # Set a function breakpoint at 'twelve' + response = self.vscode.request_setFunctionBreakpoints(functions) + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(functions), + "expect %u source breakpoints" % (len(functions))) + for breakpoint in breakpoints: + bp_id_12 = breakpoint['id'] + self.assertTrue(breakpoint['verified'], + "expect breakpoint verified") + + # Add an extra name and make sure we have two breakpoints after this + functions.append('thirteen') + response = self.vscode.request_setFunctionBreakpoints(functions) + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(functions), + "expect %u source breakpoints" % (len(functions))) + for breakpoint in breakpoints: + self.assertTrue(breakpoint['verified'], + "expect breakpoint verified") + + # There is no breakpoint delete packet, clients just send another + # setFunctionBreakpoints packet with the different function names. + functions.remove('thirteen') + response = self.vscode.request_setFunctionBreakpoints(functions) + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(functions), + "expect %u source breakpoints" % (len(functions))) + for breakpoint in breakpoints: + bp_id = breakpoint['id'] + self.assertTrue(bp_id == bp_id_12, + 'verify "twelve" breakpoint ID is same') + self.assertTrue(breakpoint['verified'], + "expect breakpoint still verified") + + # Now get the full list of breakpoints set in the target and verify + # we have only 1 breakpoints set. The response above could have told + # us about 1 breakpoints, but we want to make sure we don't have the + # second one still set in the target + response = self.vscode.request_testGetTargetBreakpoints() + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(functions), + "expect %u source breakpoints" % (len(functions))) + for breakpoint in breakpoints: + bp_id = breakpoint['id'] + self.assertTrue(bp_id == bp_id_12, + 'verify "twelve" breakpoint ID is same') + self.assertTrue(breakpoint['verified'], + "expect breakpoint still verified") + + # Now clear all breakpoints for the source file by passing down an + # empty lines array + functions = [] + response = self.vscode.request_setFunctionBreakpoints(functions) + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(functions), + "expect %u source breakpoints" % (len(functions))) + + # Verify with the target that all breakpoints have been cleared + response = self.vscode.request_testGetTargetBreakpoints() + if response: + breakpoints = response['body']['breakpoints'] + self.assertTrue(len(breakpoints) == len(functions), + "expect %u source breakpoints" % (len(functions))) + + @skipIfWindows + def test_functionality(self): + '''Tests hitting breakpoints and the functionality of a single + breakpoint, like 'conditions' and 'hitCondition' settings.''' + + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + # Set a breakpoint on "twelve" with no condition and no hitCondition + functions = ['twelve'] + breakpoint_ids = self.set_function_breakpoints(functions) + + self.assertTrue(len(breakpoint_ids) == len(functions), + "expect one breakpoint") + + # Verify we hit the breakpoint we just set + self.continue_to_breakpoints(breakpoint_ids) + + # Make sure i is zero at first breakpoint + i = int(self.vscode.get_local_variable_value('i')) + self.assertTrue(i == 0, 'i != 0 after hitting breakpoint') + + # Update the condition on our breakpoint + new_breakpoint_ids = self.set_function_breakpoints(functions, + condition="i==4") + self.assertTrue(breakpoint_ids == new_breakpoint_ids, + "existing breakpoint should have its condition " + "updated") + + self.continue_to_breakpoints(breakpoint_ids) + i = int(self.vscode.get_local_variable_value('i')) + self.assertTrue(i == 4, + 'i != 4 showing conditional works') + new_breakpoint_ids = self.set_function_breakpoints(functions, + hitCondition="2") + + self.assertTrue(breakpoint_ids == new_breakpoint_ids, + "existing breakpoint should have its condition " + "updated") + + # Continue with a hitContidtion of 2 and expect it to skip 1 value + self.continue_to_breakpoints(breakpoint_ids) + i = int(self.vscode.get_local_variable_value('i')) + self.assertTrue(i == 6, + 'i != 6 showing hitCondition works') + + # continue after hitting our hitCondition and make sure it only goes + # up by 1 + self.continue_to_breakpoints(breakpoint_ids) + i = int(self.vscode.get_local_variable_value('i')) + self.assertTrue(i == 7, + 'i != 7 showing post hitCondition hits every time') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/main.cpp new file mode 100644 index 00000000000..e859b04e3a9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/breakpoint/main.cpp @@ -0,0 +1,27 @@ +#include <stdio.h> +#include <stdexcept> + +int twelve(int i) { + return 12 + i; // break 12 +} + +int thirteen(int i) { + return 13 + i; // break 13 +} + +namespace a { + int fourteen(int i) { + return 14 + i; // break 14 + } +} +int main(int argc, char const *argv[]) { + for (int i=0; i<10; ++i) { + int x = twelve(i) + thirteen(i) + a::fourteen(i); // break loop + } + try { + throw std::invalid_argument( "throwing exception for testing" ); + } catch (...) { + puts("caught exception..."); + } + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/completions/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/completions/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/completions/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/completions/TestVSCode_completions.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/completions/TestVSCode_completions.py new file mode 100644 index 00000000000..d1d92346e43 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/completions/TestVSCode_completions.py @@ -0,0 +1,115 @@ +""" +Test lldb-vscode completions request +""" + + +import lldbvscode_testcase +import unittest2 +import vscode +from lldbsuite.test import lldbutil +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * + + +class TestVSCode_variables(lldbvscode_testcase.VSCodeTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def verify_completions(self, actual_list, expected_list, not_expected_list=[]): + for expected_item in expected_list: + self.assertTrue(expected_item in actual_list) + + for not_expected_item in not_expected_list: + self.assertFalse(not_expected_item in actual_list) + + @skipIfWindows + @skipIfDarwin # Skip this test for now until we can figure out why tings aren't working on build bots + def test_completions(self): + """ + Tests the completion request at different breakpoints + """ + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + source = "main.cpp" + breakpoint1_line = line_number(source, "// breakpoint 1") + breakpoint2_line = line_number(source, "// breakpoint 2") + breakpoint_ids = self.set_source_breakpoints( + source, [breakpoint1_line, breakpoint2_line] + ) + self.continue_to_next_stop() + + # shouldn't see variables inside main + self.verify_completions( + self.vscode.get_completions("var"), + [ + { + "text": "var", + "label": "var -- vector<basic_string<char, char_traits<char>, allocator<char> >, allocator<basic_string<char, char_traits<char>, allocator<char> > > > &", + } + ], + [{"text": "var1", "label": "var1 -- int &"}], + ) + + # should see global keywords but not variables inside main + self.verify_completions( + self.vscode.get_completions("str"), + [{"text": "struct", "label": "struct"}], + [{"text": "str1", "label": "str1 -- std::string &"}], + ) + + self.continue_to_next_stop() + + # should see variables from main but not from the other function + self.verify_completions( + self.vscode.get_completions("var"), + [ + {"text": "var1", "label": "var1 -- int &"}, + {"text": "var2", "label": "var2 -- int &"}, + ], + [ + { + "text": "var", + "label": "var -- vector<basic_string<char, char_traits<char>, allocator<char> >, allocator<basic_string<char, char_traits<char>, allocator<char> > > > &", + } + ], + ) + + self.verify_completions( + self.vscode.get_completions("str"), + [ + {"text": "struct", "label": "struct"}, + {"text": "str1", "label": "str1 -- string &"}, + ], + ) + + # should complete arbitrary commands including word starts + self.verify_completions( + self.vscode.get_completions("`log enable "), + [{"text": "gdb-remote", "label": "gdb-remote"}], + ) + + # should complete expressions with quotes inside + self.verify_completions( + self.vscode.get_completions('`expr " "; typed'), + [{"text": "typedef", "label": "typedef"}], + ) + + # should complete an incomplete quoted token + self.verify_completions( + self.vscode.get_completions('`setting "se'), + [ + { + "text": "set", + "label": "set -- Set the value of the specified debugger setting.", + } + ], + ) + self.verify_completions( + self.vscode.get_completions("`'comm"), + [ + { + "text": "command", + "label": "command -- Commands for managing custom LLDB commands.", + } + ], + ) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/completions/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/completions/main.cpp new file mode 100644 index 00000000000..14a8815a524 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/completions/main.cpp @@ -0,0 +1,16 @@ +#include <string> +#include <vector> + +int fun(std::vector<std::string> var) { + return var.size(); // breakpoint 1 +} + +int main(int argc, char const *argv[]) { + int var1 = 0; + int var2 = 1; + std::string str1 = "a"; + std::string str2 = "b"; + std::vector<std::string> vec; + fun(vec); + return 0; // breakpoint 2 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py new file mode 100644 index 00000000000..76c806426c0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/TestVSCode_launch.py @@ -0,0 +1,384 @@ +""" +Test lldb-vscode setBreakpoints request +""" + + +import unittest2 +import vscode +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import lldbvscode_testcase +import os + + +class TestVSCode_launch(lldbvscode_testcase.VSCodeTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfWindows + @skipIfDarwin # Flaky + def test_default(self): + ''' + Tests the default launch of a simple program. No arguments, + environment, or anything else is specified. + ''' + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + self.continue_to_exit() + # Now get the STDOUT and verify our program argument is correct + output = self.get_stdout() + self.assertTrue(output and len(output) > 0, + "expect program output") + lines = output.splitlines() + self.assertTrue(program in lines[0], + "make sure program path is in first argument") + + @skipIfWindows + def test_stopOnEntry(self): + ''' + Tests the default launch of a simple program that stops at the + entry point instead of continuing. + ''' + program = self.getBuildArtifact("a.out") + self.build_and_launch(program, stopOnEntry=True) + self.set_function_breakpoints(['main']) + stopped_events = self.continue_to_next_stop() + for stopped_event in stopped_events: + if 'body' in stopped_event: + body = stopped_event['body'] + if 'reason' in body: + reason = body['reason'] + self.assertTrue( + reason != 'breakpoint', + 'verify stop isn\'t "main" breakpoint') + + @skipIfWindows + def test_cwd(self): + ''' + Tests the default launch of a simple program with a current working + directory. + ''' + program = self.getBuildArtifact("a.out") + program_parent_dir = os.path.realpath( + os.path.dirname(os.path.dirname(program))) + self.build_and_launch(program, + cwd=program_parent_dir) + self.continue_to_exit() + # Now get the STDOUT and verify our program argument is correct + output = self.get_stdout() + self.assertTrue(output and len(output) > 0, + "expect program output") + lines = output.splitlines() + found = False + for line in lines: + if line.startswith('cwd = \"'): + quote_path = '"%s"' % (program_parent_dir) + found = True + self.assertTrue(quote_path in line, + "working directory '%s' not in '%s'" % ( + program_parent_dir, line)) + self.assertTrue(found, "verified program working directory") + + @skipIfWindows + def test_debuggerRoot(self): + ''' + Tests the "debuggerRoot" will change the working directory of + the lldb-vscode debug adaptor. + ''' + program = self.getBuildArtifact("a.out") + program_parent_dir = os.path.realpath( + os.path.dirname(os.path.dirname(program))) + commands = ['platform shell echo cwd = $PWD'] + self.build_and_launch(program, + debuggerRoot=program_parent_dir, + initCommands=commands) + output = self.get_console() + self.assertTrue(output and len(output) > 0, + "expect console output") + lines = output.splitlines() + prefix = 'cwd = ' + found = False + for line in lines: + if line.startswith(prefix): + found = True + self.assertTrue(program_parent_dir == line[len(prefix):], + "lldb-vscode working dir '%s' == '%s'" % ( + program_parent_dir, line[6:])) + self.assertTrue(found, "verified lldb-vscode working directory") + self.continue_to_exit() + + @skipIfWindows + def test_sourcePath(self): + ''' + Tests the "sourcePath" will set the target.source-map. + ''' + program = self.getBuildArtifact("a.out") + program_dir = os.path.dirname(program) + self.build_and_launch(program, + sourcePath=program_dir) + output = self.get_console() + self.assertTrue(output and len(output) > 0, + "expect console output") + lines = output.splitlines() + prefix = '(lldb) settings set target.source-map "." ' + found = False + for line in lines: + if line.startswith(prefix): + found = True + quoted_path = '"%s"' % (program_dir) + self.assertTrue(quoted_path == line[len(prefix):], + "lldb-vscode working dir %s == %s" % ( + quoted_path, line[6:])) + self.assertTrue(found, 'found "sourcePath" in console output') + self.continue_to_exit() + + @skipIfWindows + def test_disableSTDIO(self): + ''' + Tests the default launch of a simple program with STDIO disabled. + ''' + program = self.getBuildArtifact("a.out") + self.build_and_launch(program, + disableSTDIO=True) + self.continue_to_exit() + # Now get the STDOUT and verify our program argument is correct + output = self.get_stdout() + self.assertTrue(output is None or len(output) == 0, + "expect no program output") + + @skipIfWindows + @skipIfLinux # shell argument expansion doesn't seem to work on Linux + @expectedFailureNetBSD + def test_shellExpandArguments_enabled(self): + ''' + Tests the default launch of a simple program with shell expansion + enabled. + ''' + program = self.getBuildArtifact("a.out") + program_dir = os.path.dirname(program) + glob = os.path.join(program_dir, '*.out') + self.build_and_launch(program, args=[glob], shellExpandArguments=True) + self.continue_to_exit() + # Now get the STDOUT and verify our program argument is correct + output = self.get_stdout() + self.assertTrue(output and len(output) > 0, + "expect no program output") + lines = output.splitlines() + for line in lines: + quote_path = '"%s"' % (program) + if line.startswith("arg[1] ="): + self.assertTrue(quote_path in line, + 'verify "%s" expanded to "%s"' % ( + glob, program)) + + @skipIfWindows + def test_shellExpandArguments_disabled(self): + ''' + Tests the default launch of a simple program with shell expansion + disabled. + ''' + program = self.getBuildArtifact("a.out") + program_dir = os.path.dirname(program) + glob = os.path.join(program_dir, '*.out') + self.build_and_launch(program, + args=[glob], + shellExpandArguments=False) + self.continue_to_exit() + # Now get the STDOUT and verify our program argument is correct + output = self.get_stdout() + self.assertTrue(output and len(output) > 0, + "expect no program output") + lines = output.splitlines() + for line in lines: + quote_path = '"%s"' % (glob) + if line.startswith("arg[1] ="): + self.assertTrue(quote_path in line, + 'verify "%s" stayed to "%s"' % ( + glob, glob)) + + @skipIfWindows + def test_args(self): + ''' + Tests launch of a simple program with arguments + ''' + program = self.getBuildArtifact("a.out") + args = ["one", "with space", "'with single quotes'", + '"with double quotes"'] + self.build_and_launch(program, + args=args) + self.continue_to_exit() + + # Now get the STDOUT and verify our arguments got passed correctly + output = self.get_stdout() + self.assertTrue(output and len(output) > 0, + "expect program output") + lines = output.splitlines() + # Skip the first argument that contains the program name + lines.pop(0) + # Make sure arguments we specified are correct + for (i, arg) in enumerate(args): + quoted_arg = '"%s"' % (arg) + self.assertTrue(quoted_arg in lines[i], + 'arg[%i] "%s" not in "%s"' % (i+1, quoted_arg, lines[i])) + + @skipIfWindows + def test_environment(self): + ''' + Tests launch of a simple program with environment variables + ''' + program = self.getBuildArtifact("a.out") + env = ["NO_VALUE", "WITH_VALUE=BAR", "EMPTY_VALUE=", + "SPACE=Hello World"] + self.build_and_launch(program, + env=env) + self.continue_to_exit() + + # Now get the STDOUT and verify our arguments got passed correctly + output = self.get_stdout() + self.assertTrue(output and len(output) > 0, + "expect program output") + lines = output.splitlines() + # Skip the all arguments so we have only environment vars left + while len(lines) and lines[0].startswith("arg["): + lines.pop(0) + # Make sure each environment variable in "env" is actually set in the + # program environment that was printed to STDOUT + for var in env: + found = False + for program_var in lines: + if var in program_var: + found = True + break + self.assertTrue(found, + '"%s" must exist in program environment (%s)' % ( + var, lines)) + + @skipIfWindows + def test_commands(self): + ''' + Tests the "initCommands", "preRunCommands", "stopCommands" and + "exitCommands" that can be passed during launch. + + "initCommands" are a list of LLDB commands that get executed + before the targt is created. + "preRunCommands" are a list of LLDB commands that get executed + after the target has been created and before the launch. + "stopCommands" are a list of LLDB commands that get executed each + time the program stops. + "exitCommands" are a list of LLDB commands that get executed when + the process exits + ''' + program = self.getBuildArtifact("a.out") + initCommands = ['target list', 'platform list'] + preRunCommands = ['image list a.out', 'image dump sections a.out'] + stopCommands = ['frame variable', 'bt'] + exitCommands = ['expr 2+3', 'expr 3+4'] + self.build_and_launch(program, + initCommands=initCommands, + preRunCommands=preRunCommands, + stopCommands=stopCommands, + exitCommands=exitCommands) + + # Get output from the console. This should contain both the + # "initCommands" and the "preRunCommands". + output = self.get_console() + # Verify all "initCommands" were found in console output + self.verify_commands('initCommands', output, initCommands) + # Verify all "preRunCommands" were found in console output + self.verify_commands('preRunCommands', output, preRunCommands) + + source = 'main.c' + first_line = line_number(source, '// breakpoint 1') + second_line = line_number(source, '// breakpoint 2') + lines = [first_line, second_line] + + # Set 2 breakoints so we can verify that "stopCommands" get run as the + # breakpoints get hit + breakpoint_ids = self.set_source_breakpoints(source, lines) + self.assertTrue(len(breakpoint_ids) == len(lines), + "expect correct number of breakpoints") + + # Continue after launch and hit the first breakpoint. + # Get output from the console. This should contain both the + # "stopCommands" that were run after the first breakpoint was hit + self.continue_to_breakpoints(breakpoint_ids) + output = self.get_console(timeout=1.0) + self.verify_commands('stopCommands', output, stopCommands) + + # Continue again and hit the second breakpoint. + # Get output from the console. This should contain both the + # "stopCommands" that were run after the second breakpoint was hit + self.continue_to_breakpoints(breakpoint_ids) + output = self.get_console(timeout=1.0) + self.verify_commands('stopCommands', output, stopCommands) + + # Continue until the program exits + self.continue_to_exit() + # Get output from the console. This should contain both the + # "exitCommands" that were run after the second breakpoint was hit + output = self.get_console(timeout=1.0) + self.verify_commands('exitCommands', output, exitCommands) + + @skipIfWindows + def test_extra_launch_commands(self): + ''' + Tests the "luanchCommands" with extra launching settings + ''' + self.build_and_create_debug_adaptor() + program = self.getBuildArtifact("a.out") + + source = 'main.c' + first_line = line_number(source, '// breakpoint 1') + second_line = line_number(source, '// breakpoint 2') + # Set target binary and 2 breakoints + # then we can varify the "launchCommands" get run + # also we can verify that "stopCommands" get run as the + # breakpoints get hit + launchCommands = [ + 'target create "%s"' % (program), + 'br s -f main.c -l %d' % first_line, + 'br s -f main.c -l %d' % second_line, + 'process launch --stop-at-entry' + ] + + initCommands = ['target list', 'platform list'] + preRunCommands = ['image list a.out', 'image dump sections a.out'] + stopCommands = ['frame variable', 'bt'] + exitCommands = ['expr 2+3', 'expr 3+4'] + self.launch(program, + initCommands=initCommands, + preRunCommands=preRunCommands, + stopCommands=stopCommands, + exitCommands=exitCommands, + launchCommands=launchCommands) + + # Get output from the console. This should contain both the + # "initCommands" and the "preRunCommands". + output = self.get_console() + # Verify all "initCommands" were found in console output + self.verify_commands('initCommands', output, initCommands) + # Verify all "preRunCommands" were found in console output + self.verify_commands('preRunCommands', output, preRunCommands) + + # Verify all "launchCommands" were founc in console output + # After execution, program should launch + self.verify_commands('launchCommands', output, launchCommands) + # Verify the "stopCommands" here + self.continue_to_next_stop() + output = self.get_console(timeout=1.0) + self.verify_commands('stopCommands', output, stopCommands) + + # Continue and hit the second breakpoint. + # Get output from the console. This should contain both the + # "stopCommands" that were run after the first breakpoint was hit + self.continue_to_next_stop() + output = self.get_console(timeout=1.0) + self.verify_commands('stopCommands', output, stopCommands) + + # Continue until the program exits + self.continue_to_exit() + # Get output from the console. This should contain both the + # "exitCommands" that were run after the second breakpoint was hit + output = self.get_console(timeout=1.0) + self.verify_commands('exitCommands', output, exitCommands) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/main.c new file mode 100644 index 00000000000..aed2af9828f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/launch/main.c @@ -0,0 +1,15 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +int main(int argc, char const *argv[], char const *envp[]) { + for (int i=0; i<argc; ++i) + printf("arg[%i] = \"%s\"\n", i, argv[i]); + for (int i=0; envp[i]; ++i) + printf("env[%i] = \"%s\"\n", i, envp[i]); + char *cwd = getcwd(NULL, 0); + printf("cwd = \"%s\"\n", cwd); // breakpoint 1 + free(cwd); + cwd = NULL; + return 0; // breakpoint 2 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py new file mode 100644 index 00000000000..199b80c8f6f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/lldbvscode_testcase.py @@ -0,0 +1,319 @@ + +from lldbsuite.test.lldbtest import * +import os +import vscode + + +class VSCodeTestCaseBase(TestBase): + + NO_DEBUG_INFO_TESTCASE = True + + def create_debug_adaptor(self): + '''Create the Visual Studio Code debug adaptor''' + self.assertTrue(os.path.exists(self.lldbVSCodeExec), + 'lldb-vscode must exist') + self.vscode = vscode.DebugAdaptor( + executable=self.lldbVSCodeExec, init_commands=self.setUpCommands()) + + def build_and_create_debug_adaptor(self): + self.build() + self.create_debug_adaptor() + + def set_source_breakpoints(self, source_path, lines, condition=None, + hitCondition=None): + '''Sets source breakpoints and returns an array of strings containing + the breakpoint location IDs ("1.1", "1.2") for each breakpoint + that was set. + ''' + response = self.vscode.request_setBreakpoints( + source_path, lines, condition=condition, hitCondition=hitCondition) + if response is None: + return [] + breakpoints = response['body']['breakpoints'] + breakpoint_ids = [] + for breakpoint in breakpoints: + response_id = breakpoint['id'] + bp_id = response_id >> 32 + bp_loc_id = response_id & 0xffffffff + breakpoint_ids.append('%i.%i' % (bp_id, bp_loc_id)) + return breakpoint_ids + + def set_function_breakpoints(self, functions, condition=None, + hitCondition=None): + '''Sets breakpoints by function name given an array of function names + and returns an array of strings containing the breakpoint location + IDs ("1.1", "1.2") for each breakpoint that was set. + ''' + response = self.vscode.request_setFunctionBreakpoints( + functions, condition=condition, hitCondition=hitCondition) + if response is None: + return [] + breakpoints = response['body']['breakpoints'] + breakpoint_ids = [] + for breakpoint in breakpoints: + response_id = breakpoint['id'] + bp_id = response_id >> 32 + bp_loc_id = response_id & 0xffffffff + breakpoint_ids.append('%i.%i' % (bp_id, bp_loc_id)) + return breakpoint_ids + + def verify_breakpoint_hit(self, breakpoint_ids): + '''Wait for the process we are debugging to stop, and verify we hit + any breakpoint location in the "breakpoint_ids" array. + "breakpoint_ids" should be a list of breakpoint location ID strings + (["1.1", "2.1"]). The return value from + self.set_source_breakpoints() can be passed to this function''' + stopped_events = self.vscode.wait_for_stopped() + for stopped_event in stopped_events: + if 'body' in stopped_event: + body = stopped_event['body'] + if 'reason' not in body: + continue + if body['reason'] != 'breakpoint': + continue + if 'description' not in body: + continue + # Description is "breakpoint 1.1", so look for any location id + # ("1.1") in the description field as verification that one of + # the breakpoint locations was hit + description = body['description'] + for breakpoint_id in breakpoint_ids: + if breakpoint_id in description: + return True + return False + + def verify_exception_breakpoint_hit(self, filter_label): + '''Wait for the process we are debugging to stop, and verify the stop + reason is 'exception' and that the description matches + 'filter_label' + ''' + stopped_events = self.vscode.wait_for_stopped() + for stopped_event in stopped_events: + if 'body' in stopped_event: + body = stopped_event['body'] + if 'reason' not in body: + continue + if body['reason'] != 'exception': + continue + if 'description' not in body: + continue + description = body['description'] + if filter_label == description: + return True + return False + + def verify_commands(self, flavor, output, commands): + self.assertTrue(output and len(output) > 0, "expect console output") + lines = output.splitlines() + prefix = '(lldb) ' + for cmd in commands: + found = False + for line in lines: + if line.startswith(prefix) and cmd in line: + found = True + break + self.assertTrue(found, + "verify '%s' found in console output for '%s'" % ( + cmd, flavor)) + + def get_dict_value(self, d, key_path): + '''Verify each key in the key_path array is in contained in each + dictionary within "d". Assert if any key isn't in the + corresponding dictionary. This is handy for grabbing values from VS + Code response dictionary like getting + response['body']['stackFrames'] + ''' + value = d + for key in key_path: + if key in value: + value = value[key] + else: + self.assertTrue(key in value, + 'key "%s" from key_path "%s" not in "%s"' % ( + key, key_path, d)) + return value + + def get_stackFrames_and_totalFramesCount(self, threadId=None, startFrame=None, + levels=None, dump=False): + response = self.vscode.request_stackTrace(threadId=threadId, + startFrame=startFrame, + levels=levels, + dump=dump) + if response: + stackFrames = self.get_dict_value(response, ['body', 'stackFrames']) + totalFrames = self.get_dict_value(response, ['body', 'totalFrames']) + self.assertTrue(totalFrames > 0, + 'verify totalFrames count is provided by extension that supports ' + 'async frames loading') + return (stackFrames, totalFrames) + return (None, 0) + + def get_stackFrames(self, threadId=None, startFrame=None, levels=None, + dump=False): + (stackFrames, totalFrames) = self.get_stackFrames_and_totalFramesCount( + threadId=threadId, + startFrame=startFrame, + levels=levels, + dump=dump) + return stackFrames + + def get_source_and_line(self, threadId=None, frameIndex=0): + stackFrames = self.get_stackFrames(threadId=threadId, + startFrame=frameIndex, + levels=1) + if stackFrames is not None: + stackFrame = stackFrames[0] + ['source', 'path'] + if 'source' in stackFrame: + source = stackFrame['source'] + if 'path' in source: + if 'line' in stackFrame: + return (source['path'], stackFrame['line']) + return ('', 0) + + def get_stdout(self, timeout=0.0): + return self.vscode.get_output('stdout', timeout=timeout) + + def get_console(self, timeout=0.0): + return self.vscode.get_output('console', timeout=timeout) + + def get_local_as_int(self, name, threadId=None): + value = self.vscode.get_local_variable_value(name, threadId=threadId) + if value.startswith('0x'): + return int(value, 16) + elif value.startswith('0'): + return int(value, 8) + else: + return int(value) + + def set_local(self, name, value, id=None): + '''Set a top level local variable only.''' + return self.vscode.request_setVariable(1, name, str(value), id=id) + + def set_global(self, name, value, id=None): + '''Set a top level global variable only.''' + return self.vscode.request_setVariable(2, name, str(value), id=id) + + def stepIn(self, threadId=None, waitForStop=True): + self.vscode.request_stepIn(threadId=threadId) + if waitForStop: + return self.vscode.wait_for_stopped() + return None + + def stepOver(self, threadId=None, waitForStop=True): + self.vscode.request_next(threadId=threadId) + if waitForStop: + return self.vscode.wait_for_stopped() + return None + + def stepOut(self, threadId=None, waitForStop=True): + self.vscode.request_stepOut(threadId=threadId) + if waitForStop: + return self.vscode.wait_for_stopped() + return None + + def continue_to_next_stop(self): + self.vscode.request_continue() + return self.vscode.wait_for_stopped() + + def continue_to_breakpoints(self, breakpoint_ids): + self.vscode.request_continue() + self.verify_breakpoint_hit(breakpoint_ids) + + def continue_to_exception_breakpoint(self, filter_label): + self.vscode.request_continue() + self.assertTrue(self.verify_exception_breakpoint_hit(filter_label), + 'verify we got "%s"' % (filter_label)) + + def continue_to_exit(self, exitCode=0): + self.vscode.request_continue() + stopped_events = self.vscode.wait_for_stopped() + self.assertTrue(len(stopped_events) == 1, + "expecting single 'exited' event") + self.assertTrue(stopped_events[0]['event'] == 'exited', + 'make sure program ran to completion') + self.assertTrue(stopped_events[0]['body']['exitCode'] == exitCode, + 'exitCode == %i' % (exitCode)) + + def attach(self, program=None, pid=None, waitFor=None, trace=None, + initCommands=None, preRunCommands=None, stopCommands=None, + exitCommands=None, attachCommands=None): + '''Build the default Makefile target, create the VSCode debug adaptor, + and attach to the process. + ''' + # Make sure we disconnect and terminate the VSCode debug adaptor even + # if we throw an exception during the test case. + def cleanup(): + self.vscode.request_disconnect(terminateDebuggee=True) + self.vscode.terminate() + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + # Initialize and launch the program + self.vscode.request_initialize() + response = self.vscode.request_attach( + program=program, pid=pid, waitFor=waitFor, trace=trace, + initCommands=initCommands, preRunCommands=preRunCommands, + stopCommands=stopCommands, exitCommands=exitCommands, + attachCommands=attachCommands) + if not (response and response['success']): + self.assertTrue(response['success'], + 'attach failed (%s)' % (response['message'])) + + def launch(self, program=None, args=None, cwd=None, env=None, + stopOnEntry=False, disableASLR=True, + disableSTDIO=False, shellExpandArguments=False, + trace=False, initCommands=None, preRunCommands=None, + stopCommands=None, exitCommands=None,sourcePath= None, + debuggerRoot=None, launchCommands=None): + '''Sending launch request to vscode + ''' + + # Make sure we disconnect and terminate the VSCode debug adapter, + # if we throw an exception during the test case + def cleanup(): + self.vscode.request_disconnect(terminateDebuggee=True) + self.vscode.terminate() + + # Execute the cleanup function during test case tear down. + self.addTearDownHook(cleanup) + + # Initialize and launch the program + self.vscode.request_initialize() + response = self.vscode.request_launch( + program, + args=args, + cwd=cwd, + env=env, + stopOnEntry=stopOnEntry, + disableASLR=disableASLR, + disableSTDIO=disableSTDIO, + shellExpandArguments=shellExpandArguments, + trace=trace, + initCommands=initCommands, + preRunCommands=preRunCommands, + stopCommands=stopCommands, + exitCommands=exitCommands, + sourcePath=sourcePath, + debuggerRoot=debuggerRoot, + launchCommands=launchCommands) + if not (response and response['success']): + self.assertTrue(response['success'], + 'launch failed (%s)' % (response['message'])) + + def build_and_launch(self, program, args=None, cwd=None, env=None, + stopOnEntry=False, disableASLR=True, + disableSTDIO=False, shellExpandArguments=False, + trace=False, initCommands=None, preRunCommands=None, + stopCommands=None, exitCommands=None, + sourcePath=None, debuggerRoot=None): + '''Build the default Makefile target, create the VSCode debug adaptor, + and launch the process. + ''' + self.build_and_create_debug_adaptor() + self.assertTrue(os.path.exists(program), 'executable must exist') + + self.launch(program, args, cwd, env, stopOnEntry, disableASLR, + disableSTDIO, shellExpandArguments, trace, + initCommands, preRunCommands, stopCommands, exitCommands, + sourcePath, debuggerRoot) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/stackTrace/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/stackTrace/Makefile new file mode 100644 index 00000000000..10495940055 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/stackTrace/Makefile @@ -0,0 +1,3 @@ +C_SOURCES := main.c + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/stackTrace/TestVSCode_stackTrace.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/stackTrace/TestVSCode_stackTrace.py new file mode 100644 index 00000000000..817e40ecbf6 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/stackTrace/TestVSCode_stackTrace.py @@ -0,0 +1,163 @@ +""" +Test lldb-vscode setBreakpoints request +""" + + +import unittest2 +import vscode +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import lldbvscode_testcase +import os + + +class TestVSCode_stackTrace(lldbvscode_testcase.VSCodeTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + name_key_path = ['name'] + source_key_path = ['source', 'path'] + line_key_path = ['line'] + + def verify_stackFrames(self, start_idx, stackFrames): + frame_idx = start_idx + for stackFrame in stackFrames: + # Don't care about frame above main + if frame_idx > 20: + return + self.verify_stackFrame(frame_idx, stackFrame) + frame_idx += 1 + + def verify_stackFrame(self, frame_idx, stackFrame): + frame_name = self.get_dict_value(stackFrame, self.name_key_path) + frame_source = self.get_dict_value(stackFrame, self.source_key_path) + frame_line = self.get_dict_value(stackFrame, self.line_key_path) + if frame_idx == 0: + expected_line = self.recurse_end + expected_name = 'recurse' + elif frame_idx < 20: + expected_line = self.recurse_call + expected_name = 'recurse' + else: + expected_line = self.recurse_invocation + expected_name = 'main' + self.assertTrue(frame_name == expected_name, + 'frame #%i name "%s" == "%s"' % ( + frame_idx, frame_name, expected_name)) + self.assertTrue(frame_source == self.source_path, + 'frame #%i source "%s" == "%s"' % ( + frame_idx, frame_source, self.source_path)) + self.assertTrue(frame_line == expected_line, + 'frame #%i line %i == %i' % (frame_idx, frame_line, + expected_line)) + + @skipIfWindows + def test_stackTrace(self): + ''' + Tests the 'stackTrace' packet and all its variants. + ''' + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + source = 'main.c' + self.source_path = os.path.join(os.getcwd(), source) + self.recurse_end = line_number(source, 'recurse end') + self.recurse_call = line_number(source, 'recurse call') + self.recurse_invocation = line_number(source, 'recurse invocation') + + lines = [self.recurse_end] + + # Set breakoint at a point of deepest recuusion + breakpoint_ids = self.set_source_breakpoints(source, lines) + self.assertTrue(len(breakpoint_ids) == len(lines), + "expect correct number of breakpoints") + + self.continue_to_breakpoints(breakpoint_ids) + startFrame = 0 + # Verify we get all stack frames with no arguments + (stackFrames, totalFrames) = self.get_stackFrames_and_totalFramesCount() + frameCount = len(stackFrames) + self.assertTrue(frameCount >= 20, + 'verify we get at least 20 frames for all frames') + self.assertTrue(totalFrames == frameCount, + 'verify we get correct value for totalFrames count') + self.verify_stackFrames(startFrame, stackFrames) + + # Verify all stack frames by specifying startFrame = 0 and levels not + # specified + stackFrames = self.get_stackFrames(startFrame=startFrame) + self.assertTrue(frameCount == len(stackFrames), + ('verify same number of frames with startFrame=%i') % ( + startFrame)) + self.verify_stackFrames(startFrame, stackFrames) + + # Verify all stack frames by specifying startFrame = 0 and levels = 0 + levels = 0 + stackFrames = self.get_stackFrames(startFrame=startFrame, + levels=levels) + self.assertTrue(frameCount == len(stackFrames), + ('verify same number of frames with startFrame=%i and' + ' levels=%i') % (startFrame, levels)) + self.verify_stackFrames(startFrame, stackFrames) + + # Get only the first stack frame by sepcifying startFrame = 0 and + # levels = 1 + levels = 1 + stackFrames = self.get_stackFrames(startFrame=startFrame, + levels=levels) + self.assertTrue(levels == len(stackFrames), + ('verify one frame with startFrame=%i and' + ' levels=%i') % (startFrame, levels)) + self.verify_stackFrames(startFrame, stackFrames) + + # Get only the first 3 stack frames by sepcifying startFrame = 0 and + # levels = 3 + levels = 3 + stackFrames = self.get_stackFrames(startFrame=startFrame, + levels=levels) + self.assertTrue(levels == len(stackFrames), + ('verify %i frames with startFrame=%i and' + ' levels=%i') % (levels, startFrame, levels)) + self.verify_stackFrames(startFrame, stackFrames) + + # Get only the first 15 stack frames by sepcifying startFrame = 5 and + # levels = 16 + startFrame = 5 + levels = 16 + stackFrames = self.get_stackFrames(startFrame=startFrame, + levels=levels) + self.assertTrue(levels == len(stackFrames), + ('verify %i frames with startFrame=%i and' + ' levels=%i') % (levels, startFrame, levels)) + self.verify_stackFrames(startFrame, stackFrames) + + # Verify we cap things correctly when we ask for too many frames + startFrame = 5 + levels = 1000 + (stackFrames, totalFrames) = self.get_stackFrames_and_totalFramesCount( + startFrame=startFrame, + levels=levels) + self.assertTrue(len(stackFrames) == frameCount - startFrame, + ('verify less than 1000 frames with startFrame=%i and' + ' levels=%i') % (startFrame, levels)) + self.assertTrue(totalFrames == frameCount, + 'verify we get correct value for totalFrames count ' + 'when requested frames not from 0 index') + self.verify_stackFrames(startFrame, stackFrames) + + # Verify level=0 works with non-zerp start frame + startFrame = 5 + levels = 0 + stackFrames = self.get_stackFrames(startFrame=startFrame, + levels=levels) + self.assertTrue(len(stackFrames) == frameCount - startFrame, + ('verify less than 1000 frames with startFrame=%i and' + ' levels=%i') % (startFrame, levels)) + self.verify_stackFrames(startFrame, stackFrames) + + # Verify we get not frames when startFrame is too high + startFrame = 1000 + levels = 1 + stackFrames = self.get_stackFrames(startFrame=startFrame, + levels=levels) + self.assertTrue(0 == len(stackFrames), + 'verify zero frames with startFrame out of bounds') diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/stackTrace/main.c b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/stackTrace/main.c new file mode 100644 index 00000000000..85b41c49281 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/stackTrace/main.c @@ -0,0 +1,13 @@ +#include <stdio.h> +#include <unistd.h> + +int recurse(int x) { + if (x <= 1) + return 1; // recurse end + return recurse(x-1) + x; // recurse call +} + +int main(int argc, char const *argv[]) { + recurse(20); // recurse invocation + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/step/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/step/Makefile new file mode 100644 index 00000000000..b7f3072e28c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/step/Makefile @@ -0,0 +1,5 @@ +ENABLE_THREADS := YES + +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/step/TestVSCode_step.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/step/TestVSCode_step.py new file mode 100644 index 00000000000..2431464f8c8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/step/TestVSCode_step.py @@ -0,0 +1,75 @@ +""" +Test lldb-vscode setBreakpoints request +""" + + +import unittest2 +import vscode +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import lldbvscode_testcase + + +class TestVSCode_step(lldbvscode_testcase.VSCodeTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + @skipIfWindows + def test_step(self): + ''' + Tests the stepping in/out/over in threads. + ''' + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + source = 'main.cpp' + # source_path = os.path.join(os.getcwd(), source) + breakpoint1_line = line_number(source, '// breakpoint 1') + lines = [breakpoint1_line] + # Set breakoint in the thread function so we can step the threads + breakpoint_ids = self.set_source_breakpoints(source, lines) + self.assertEqual(len(breakpoint_ids), len(lines), + "expect correct number of breakpoints") + self.continue_to_breakpoints(breakpoint_ids) + threads = self.vscode.get_threads() + for thread in threads: + if 'reason' in thread: + reason = thread['reason'] + if reason == 'breakpoint': + # We have a thread that is stopped at our breakpoint. + # Get the value of "x" and get the source file and line. + # These will help us determine if we are stepping + # correctly. If we step a thread correctly we will verify + # the correct falue for x as it progresses through the + # program. + tid = thread['id'] + x1 = self.get_local_as_int('x', threadId=tid) + (src1, line1) = self.get_source_and_line(threadId=tid) + + # Now step into the "recurse()" function call again and + # verify, using the new value of "x" and the source file + # and line if we stepped correctly + self.stepIn(threadId=tid, waitForStop=True) + x2 = self.get_local_as_int('x', threadId=tid) + (src2, line2) = self.get_source_and_line(threadId=tid) + self.assertEqual(x1, x2 + 1, 'verify step in variable') + self.assertLess(line2, line1, 'verify step in line') + self.assertEqual(src1, src2, 'verify step in source') + + # Now step out and verify + self.stepOut(threadId=tid, waitForStop=True) + x3 = self.get_local_as_int('x', threadId=tid) + (src3, line3) = self.get_source_and_line(threadId=tid) + self.assertEqual(x1, x3, 'verify step out variable') + self.assertGreaterEqual(line3, line1, 'verify step out line') + self.assertEqual(src1, src3, 'verify step in source') + + # Step over and verify + self.stepOver(threadId=tid, waitForStop=True) + x4 = self.get_local_as_int('x', threadId=tid) + (src4, line4) = self.get_source_and_line(threadId=tid) + self.assertEqual(x4, x3, 'verify step over variable') + self.assertGreater(line4, line3, 'verify step over line') + self.assertEqual(src1, src4, 'verify step over source') + # only step one thread that is at the breakpoint and stop + break diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/step/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/step/main.cpp new file mode 100644 index 00000000000..3027551972f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/step/main.cpp @@ -0,0 +1,10 @@ +int function(int x) { + if ((x % 2) == 0) + return function(x-1) + x; // breakpoint 1 + else + return x; +} + +int main(int argc, char const *argv[]) { + return function(2); +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/variables/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/variables/Makefile new file mode 100644 index 00000000000..99998b20bcb --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/variables/Makefile @@ -0,0 +1,3 @@ +CXX_SOURCES := main.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/variables/TestVSCode_variables.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/variables/TestVSCode_variables.py new file mode 100644 index 00000000000..55c4fd000b2 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/variables/TestVSCode_variables.py @@ -0,0 +1,222 @@ +""" +Test lldb-vscode setBreakpoints request +""" + +from __future__ import print_function + +import unittest2 +import vscode +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil +import lldbvscode_testcase + + +def make_buffer_verify_dict(start_idx, count, offset=0): + verify_dict = {} + for i in range(start_idx, start_idx + count): + verify_dict['[%i]' % (i)] = {'type': 'int', 'value': str(i+offset)} + return verify_dict + + +class TestVSCode_variables(lldbvscode_testcase.VSCodeTestCaseBase): + + mydir = TestBase.compute_mydir(__file__) + + def verify_values(self, verify_dict, actual, varref_dict=None): + if 'equals' in verify_dict: + verify = verify_dict['equals'] + for key in verify: + verify_value = verify[key] + actual_value = actual[key] + self.assertTrue(verify_value == actual_value, + '"%s" keys don\'t match (%s != %s)' % ( + key, actual_value, verify_value)) + if 'startswith' in verify_dict: + verify = verify_dict['startswith'] + for key in verify: + verify_value = verify[key] + actual_value = actual[key] + startswith = actual_value.startswith(verify_value) + self.assertTrue(startswith, + ('"%s" value "%s" doesn\'t start with' + ' "%s")') % ( + key, actual_value, + verify_value)) + hasVariablesReference = 'variablesReference' in actual + varRef = None + if hasVariablesReference: + # Remember variable references in case we want to test further + # by using the evaluate name. + varRef = actual['variablesReference'] + if varRef != 0 and varref_dict is not None: + varref_dict[actual['evaluateName']] = varRef + if ('hasVariablesReference' in verify_dict and + verify_dict['hasVariablesReference']): + self.assertTrue(hasVariablesReference, + "verify variable reference") + if 'children' in verify_dict: + self.assertTrue(hasVariablesReference and varRef is not None and + varRef != 0, + ("children verify values specified for " + "variable without children")) + + response = self.vscode.request_variables(varRef) + self.verify_variables(verify_dict['children'], + response['body']['variables'], + varref_dict) + + def verify_variables(self, verify_dict, variables, varref_dict=None): + for variable in variables: + name = variable['name'] + self.assertTrue(name in verify_dict, + 'variable "%s" in verify dictionary' % (name)) + self.verify_values(verify_dict[name], variable, varref_dict) + + @skipIfWindows + def test_scopes_variables_setVariable_evaluate(self): + ''' + Tests the "scopes", "variables", "setVariable", and "evaluate" + packets. + ''' + program = self.getBuildArtifact("a.out") + self.build_and_launch(program) + source = 'main.cpp' + breakpoint1_line = line_number(source, '// breakpoint 1') + lines = [breakpoint1_line] + # Set breakpoint in the thread function so we can step the threads + breakpoint_ids = self.set_source_breakpoints(source, lines) + self.assertTrue(len(breakpoint_ids) == len(lines), + "expect correct number of breakpoints") + self.continue_to_breakpoints(breakpoint_ids) + locals = self.vscode.get_local_variables() + globals = self.vscode.get_global_variables() + buffer_children = make_buffer_verify_dict(0, 32) + verify_locals = { + 'argc': { + 'equals': {'type': 'int', 'value': '1'} + }, + 'argv': { + 'equals': {'type': 'const char **'}, + 'startswith': {'value': '0x'}, + 'hasVariablesReference': True + }, + 'pt': { + 'equals': {'type': 'PointType'}, + 'hasVariablesReference': True, + 'children': { + 'x': {'equals': {'type': 'int', 'value': '11'}}, + 'y': {'equals': {'type': 'int', 'value': '22'}}, + 'buffer': {'children': buffer_children} + } + } + } + verify_globals = { + 's_local': { + 'equals': {'type': 'float', 'value': '2.25'} + }, + '::g_global': { + 'equals': {'type': 'int', 'value': '123'} + }, + 's_global': { + 'equals': {'type': 'int', 'value': '234'} + }, + } + varref_dict = {} + self.verify_variables(verify_locals, locals, varref_dict) + self.verify_variables(verify_globals, globals, varref_dict) + # pprint.PrettyPrinter(indent=4).pprint(varref_dict) + # We need to test the functionality of the "variables" request as it + # has optional parameters like "start" and "count" to limit the number + # of variables that are fetched + varRef = varref_dict['pt.buffer'] + response = self.vscode.request_variables(varRef) + self.verify_variables(buffer_children, response['body']['variables']) + # Verify setting start=0 in the arguments still gets all children + response = self.vscode.request_variables(varRef, start=0) + self.verify_variables(buffer_children, response['body']['variables']) + # Verify setting count=0 in the arguments still gets all children. + # If count is zero, it means to get all children. + response = self.vscode.request_variables(varRef, count=0) + self.verify_variables(buffer_children, response['body']['variables']) + # Verify setting count to a value that is too large in the arguments + # still gets all children, and no more + response = self.vscode.request_variables(varRef, count=1000) + self.verify_variables(buffer_children, response['body']['variables']) + # Verify setting the start index and count gets only the children we + # want + response = self.vscode.request_variables(varRef, start=5, count=5) + self.verify_variables(make_buffer_verify_dict(5, 5), + response['body']['variables']) + # Verify setting the start index to a value that is out of range + # results in an empty list + response = self.vscode.request_variables(varRef, start=32, count=1) + self.assertTrue(len(response['body']['variables']) == 0, + 'verify we get no variable back for invalid start') + + # Test evaluate + expressions = { + 'pt.x': { + 'equals': {'result': '11', 'type': 'int'}, + 'hasVariablesReference': False + }, + 'pt.buffer[2]': { + 'equals': {'result': '2', 'type': 'int'}, + 'hasVariablesReference': False + }, + 'pt': { + 'equals': {'type': 'PointType'}, + 'startswith': {'result': 'PointType @ 0x'}, + 'hasVariablesReference': True + }, + 'pt.buffer': { + 'equals': {'type': 'int [32]'}, + 'startswith': {'result': 'int [32] @ 0x'}, + 'hasVariablesReference': True + }, + 'argv': { + 'equals': {'type': 'const char **'}, + 'startswith': {'result': '0x'}, + 'hasVariablesReference': True + }, + 'argv[0]': { + 'equals': {'type': 'const char *'}, + 'startswith': {'result': '0x'}, + 'hasVariablesReference': True + }, + '2+3': { + 'equals': {'result': '5', 'type': 'int'}, + 'hasVariablesReference': False + }, + } + for expression in expressions: + response = self.vscode.request_evaluate(expression) + self.verify_values(expressions[expression], response['body']) + + # Test setting variables + self.set_local('argc', 123) + argc = self.get_local_as_int('argc') + self.assertTrue(argc == 123, + 'verify argc was set to 123 (123 != %i)' % (argc)) + + self.set_local('argv', 0x1234) + argv = self.get_local_as_int('argv') + self.assertTrue(argv == 0x1234, + 'verify argv was set to 0x1234 (0x1234 != %#x)' % ( + argv)) + + # Set a variable value whose name is synthetic, like a variable index + # and verify the value by reading it + self.vscode.request_setVariable(varRef, "[0]", 100) + response = self.vscode.request_variables(varRef, start=0, count=1) + self.verify_variables(make_buffer_verify_dict(0, 1, 100), + response['body']['variables']) + + # Set a variable value whose name is a real child value, like "pt.x" + # and verify the value by reading it + varRef = varref_dict['pt'] + self.vscode.request_setVariable(varRef, "x", 111) + response = self.vscode.request_variables(varRef, start=0, count=1) + value = response['body']['variables'][0]['value'] + self.assertTrue(value == '111', + 'verify pt.x got set to 111 (111 != %s)' % (value)) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/variables/main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/variables/main.cpp new file mode 100644 index 00000000000..0223bd0a75e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/variables/main.cpp @@ -0,0 +1,18 @@ + +#define BUFFER_SIZE 32 +struct PointType { + int x; + int y; + int buffer[BUFFER_SIZE]; +}; + +int g_global = 123; +static int s_global = 234; + +int main(int argc, char const *argv[]) { + static float s_local = 2.25; + PointType pt = { 11,22, {0}}; + for (int i=0; i<BUFFER_SIZE; ++i) + pt.buffer[i] = i; + return s_global - g_global - pt.y; // breakpoint 1 +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py new file mode 100644 index 00000000000..1110ad36c0f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/tools/lldb-vscode/vscode.py @@ -0,0 +1,1114 @@ +#!/usr/bin/env python + +import binascii +import json +import optparse +import os +import pprint +import socket +import string +import subprocess +import sys +import threading + + +def dump_memory(base_addr, data, num_per_line, outfile): + + data_len = len(data) + hex_string = binascii.hexlify(data) + addr = base_addr + ascii_str = '' + i = 0 + while i < data_len: + outfile.write('0x%8.8x: ' % (addr + i)) + bytes_left = data_len - i + if bytes_left >= num_per_line: + curr_data_len = num_per_line + else: + curr_data_len = bytes_left + hex_start_idx = i * 2 + hex_end_idx = hex_start_idx + curr_data_len * 2 + curr_hex_str = hex_string[hex_start_idx:hex_end_idx] + # 'curr_hex_str' now contains the hex byte string for the + # current line with no spaces between bytes + t = iter(curr_hex_str) + # Print hex bytes separated by space + outfile.write(' '.join(a + b for a, b in zip(t, t))) + # Print two spaces + outfile.write(' ') + # Calculate ASCII string for bytes into 'ascii_str' + ascii_str = '' + for j in range(i, i + curr_data_len): + ch = data[j] + if ch in string.printable and ch not in string.whitespace: + ascii_str += '%c' % (ch) + else: + ascii_str += '.' + # Print ASCII representation and newline + outfile.write(ascii_str) + i = i + curr_data_len + outfile.write('\n') + + +def read_packet(f, verbose=False, trace_file=None): + '''Decode a JSON packet that starts with the content length and is + followed by the JSON bytes from a file 'f'. Returns None on EOF. + ''' + line = f.readline().decode("utf-8") + if len(line) == 0: + return None # EOF. + + # Watch for line that starts with the prefix + prefix = 'Content-Length: ' + if line.startswith(prefix): + # Decode length of JSON bytes + if verbose: + print('content: "%s"' % (line)) + length = int(line[len(prefix):]) + if verbose: + print('length: "%u"' % (length)) + # Skip empty line + line = f.readline() + if verbose: + print('empty: "%s"' % (line)) + # Read JSON bytes + json_str = f.read(length) + if verbose: + print('json: "%s"' % (json_str)) + if trace_file: + trace_file.write('from adaptor:\n%s\n' % (json_str)) + # Decode the JSON bytes into a python dictionary + return json.loads(json_str) + + return None + + +def packet_type_is(packet, packet_type): + return 'type' in packet and packet['type'] == packet_type + + +def read_packet_thread(vs_comm): + done = False + while not done: + packet = read_packet(vs_comm.recv, trace_file=vs_comm.trace_file) + # `packet` will be `None` on EOF. We want to pass it down to + # handle_recv_packet anyway so the main thread can handle unexpected + # termination of lldb-vscode and stop waiting for new packets. + done = not vs_comm.handle_recv_packet(packet) + + +class DebugCommunication(object): + + def __init__(self, recv, send, init_commands): + self.trace_file = None + self.send = send + self.recv = recv + self.recv_packets = [] + self.recv_condition = threading.Condition() + self.recv_thread = threading.Thread(target=read_packet_thread, + args=(self,)) + self.process_event_body = None + self.exit_status = None + self.initialize_body = None + self.thread_stop_reasons = {} + self.sequence = 1 + self.threads = None + self.recv_thread.start() + self.output_condition = threading.Condition() + self.output = {} + self.configuration_done_sent = False + self.frame_scopes = {} + self.init_commands = init_commands + + @classmethod + def encode_content(cls, s): + return ("Content-Length: %u\r\n\r\n%s" % (len(s), s)).encode("utf-8") + + @classmethod + def validate_response(cls, command, response): + if command['command'] != response['command']: + raise ValueError('command mismatch in response') + if command['seq'] != response['request_seq']: + raise ValueError('seq mismatch in response') + + def get_output(self, category, timeout=0.0, clear=True): + self.output_condition.acquire() + output = None + if category in self.output: + output = self.output[category] + if clear: + del self.output[category] + elif timeout != 0.0: + self.output_condition.wait(timeout) + if category in self.output: + output = self.output[category] + if clear: + del self.output[category] + self.output_condition.release() + return output + + def enqueue_recv_packet(self, packet): + self.recv_condition.acquire() + self.recv_packets.append(packet) + self.recv_condition.notify() + self.recv_condition.release() + + def handle_recv_packet(self, packet): + '''Called by the read thread that is waiting for all incoming packets + to store the incoming packet in "self.recv_packets" in a thread safe + way. This function will then signal the "self.recv_condition" to + indicate a new packet is available. Returns True if the caller + should keep calling this function for more packets. + ''' + # If EOF, notify the read thread by enqueing a None. + if not packet: + self.enqueue_recv_packet(None) + return False + + # Check the packet to see if is an event packet + keepGoing = True + packet_type = packet['type'] + if packet_type == 'event': + event = packet['event'] + body = None + if 'body' in packet: + body = packet['body'] + # Handle the event packet and cache information from these packets + # as they come in + if event == 'output': + # Store any output we receive so clients can retrieve it later. + category = body['category'] + output = body['output'] + self.output_condition.acquire() + if category in self.output: + self.output[category] += output + else: + self.output[category] = output + self.output_condition.notify() + self.output_condition.release() + # no need to add 'output' packets to our packets list + return keepGoing + elif event == 'process': + # When a new process is attached or launched, remember the + # details that are available in the body of the event + self.process_event_body = body + elif event == 'stopped': + # Each thread that stops with a reason will send a + # 'stopped' event. We need to remember the thread stop + # reasons since the 'threads' command doesn't return + # that information. + self._process_stopped() + tid = body['threadId'] + self.thread_stop_reasons[tid] = body + elif packet_type == 'response': + if packet['command'] == 'disconnect': + keepGoing = False + self.enqueue_recv_packet(packet) + return keepGoing + + def send_packet(self, command_dict, set_sequence=True): + '''Take the "command_dict" python dictionary and encode it as a JSON + string and send the contents as a packet to the VSCode debug + adaptor''' + # Set the sequence ID for this command automatically + if set_sequence: + command_dict['seq'] = self.sequence + self.sequence += 1 + # Encode our command dictionary as a JSON string + json_str = json.dumps(command_dict, separators=(',', ':')) + if self.trace_file: + self.trace_file.write('to adaptor:\n%s\n' % (json_str)) + length = len(json_str) + if length > 0: + # Send the encoded JSON packet and flush the 'send' file + self.send.write(self.encode_content(json_str)) + self.send.flush() + + def recv_packet(self, filter_type=None, filter_event=None, timeout=None): + '''Get a JSON packet from the VSCode debug adaptor. This function + assumes a thread that reads packets is running and will deliver + any received packets by calling handle_recv_packet(...). This + function will wait for the packet to arrive and return it when + it does.''' + while True: + try: + self.recv_condition.acquire() + packet = None + while True: + for (i, curr_packet) in enumerate(self.recv_packets): + if not curr_packet: + raise EOFError + packet_type = curr_packet['type'] + if filter_type is None or packet_type in filter_type: + if (filter_event is None or + (packet_type == 'event' and + curr_packet['event'] in filter_event)): + packet = self.recv_packets.pop(i) + break + if packet: + break + # Sleep until packet is received + len_before = len(self.recv_packets) + self.recv_condition.wait(timeout) + len_after = len(self.recv_packets) + if len_before == len_after: + return None # Timed out + return packet + except EOFError: + return None + finally: + self.recv_condition.release() + + return None + + def send_recv(self, command): + '''Send a command python dictionary as JSON and receive the JSON + response. Validates that the response is the correct sequence and + command in the reply. Any events that are received are added to the + events list in this object''' + self.send_packet(command) + done = False + while not done: + response = self.recv_packet(filter_type='response') + if response is None: + desc = 'no response for "%s"' % (command['command']) + raise ValueError(desc) + self.validate_response(command, response) + return response + return None + + def wait_for_event(self, filter=None, timeout=None): + while True: + return self.recv_packet(filter_type='event', filter_event=filter, + timeout=timeout) + return None + + def wait_for_stopped(self, timeout=None): + stopped_events = [] + stopped_event = self.wait_for_event(filter=['stopped', 'exited'], + timeout=timeout) + exited = False + while stopped_event: + stopped_events.append(stopped_event) + # If we exited, then we are done + if stopped_event['event'] == 'exited': + self.exit_status = stopped_event['body']['exitCode'] + exited = True + break + # Otherwise we stopped and there might be one or more 'stopped' + # events for each thread that stopped with a reason, so keep + # checking for more 'stopped' events and return all of them + stopped_event = self.wait_for_event(filter='stopped', timeout=0.25) + if exited: + self.threads = [] + return stopped_events + + def wait_for_exited(self): + event_dict = self.wait_for_event('exited') + if event_dict is None: + raise ValueError("didn't get stopped event") + return event_dict + + def get_initialize_value(self, key): + '''Get a value for the given key if it there is a key/value pair in + the "initialize" request response body. + ''' + if self.initialize_body and key in self.initialize_body: + return self.initialize_body[key] + return None + + def get_threads(self): + if self.threads is None: + self.request_threads() + return self.threads + + def get_thread_id(self, threadIndex=0): + '''Utility function to get the first thread ID in the thread list. + If the thread list is empty, then fetch the threads. + ''' + if self.threads is None: + self.request_threads() + if self.threads and threadIndex < len(self.threads): + return self.threads[threadIndex]['id'] + return None + + def get_stackFrame(self, frameIndex=0, threadId=None): + '''Get a single "StackFrame" object from a "stackTrace" request and + return the "StackFrame as a python dictionary, or None on failure + ''' + if threadId is None: + threadId = self.get_thread_id() + if threadId is None: + print('invalid threadId') + return None + response = self.request_stackTrace(threadId, startFrame=frameIndex, + levels=1) + if response: + return response['body']['stackFrames'][0] + print('invalid response') + return None + + def get_completions(self, text): + response = self.request_completions(text) + return response['body']['targets'] + + def get_scope_variables(self, scope_name, frameIndex=0, threadId=None): + stackFrame = self.get_stackFrame(frameIndex=frameIndex, + threadId=threadId) + if stackFrame is None: + return [] + frameId = stackFrame['id'] + if frameId in self.frame_scopes: + frame_scopes = self.frame_scopes[frameId] + else: + scopes_response = self.request_scopes(frameId) + frame_scopes = scopes_response['body']['scopes'] + self.frame_scopes[frameId] = frame_scopes + for scope in frame_scopes: + if scope['name'] == scope_name: + varRef = scope['variablesReference'] + variables_response = self.request_variables(varRef) + if variables_response: + if 'body' in variables_response: + body = variables_response['body'] + if 'variables' in body: + vars = body['variables'] + return vars + return [] + + def get_global_variables(self, frameIndex=0, threadId=None): + return self.get_scope_variables('Globals', frameIndex=frameIndex, + threadId=threadId) + + def get_local_variables(self, frameIndex=0, threadId=None): + return self.get_scope_variables('Locals', frameIndex=frameIndex, + threadId=threadId) + + def get_local_variable(self, name, frameIndex=0, threadId=None): + locals = self.get_local_variables(frameIndex=frameIndex, + threadId=threadId) + for local in locals: + if 'name' in local and local['name'] == name: + return local + return None + + def get_local_variable_value(self, name, frameIndex=0, threadId=None): + variable = self.get_local_variable(name, frameIndex=frameIndex, + threadId=threadId) + if variable and 'value' in variable: + return variable['value'] + return None + + def replay_packets(self, replay_file_path): + f = open(replay_file_path, 'r') + mode = 'invalid' + set_sequence = False + command_dict = None + while mode != 'eof': + if mode == 'invalid': + line = f.readline() + if line.startswith('to adapter:'): + mode = 'send' + elif line.startswith('from adapter:'): + mode = 'recv' + elif mode == 'send': + command_dict = read_packet(f) + # Skip the end of line that follows the JSON + f.readline() + if command_dict is None: + raise ValueError('decode packet failed from replay file') + print('Sending:') + pprint.PrettyPrinter(indent=2).pprint(command_dict) + # raw_input('Press ENTER to send:') + self.send_packet(command_dict, set_sequence) + mode = 'invalid' + elif mode == 'recv': + print('Replay response:') + replay_response = read_packet(f) + # Skip the end of line that follows the JSON + f.readline() + pprint.PrettyPrinter(indent=2).pprint(replay_response) + actual_response = self.recv_packet() + if actual_response: + type = actual_response['type'] + print('Actual response:') + if type == 'response': + self.validate_response(command_dict, actual_response) + pprint.PrettyPrinter(indent=2).pprint(actual_response) + else: + print("error: didn't get a valid response") + mode = 'invalid' + + def request_attach(self, program=None, pid=None, waitFor=None, trace=None, + initCommands=None, preRunCommands=None, + stopCommands=None, exitCommands=None, + attachCommands=None): + args_dict = {} + if pid is not None: + args_dict['pid'] = pid + if program is not None: + args_dict['program'] = program + if waitFor is not None: + args_dict['waitFor'] = waitFor + if trace: + args_dict['trace'] = trace + args_dict['initCommands'] = self.init_commands + if initCommands: + args_dict['initCommands'].extend(initCommands) + if preRunCommands: + args_dict['preRunCommands'] = preRunCommands + if stopCommands: + args_dict['stopCommands'] = stopCommands + if exitCommands: + args_dict['exitCommands'] = exitCommands + if attachCommands: + args_dict['attachCommands'] = attachCommands + command_dict = { + 'command': 'attach', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_configurationDone(self): + command_dict = { + 'command': 'configurationDone', + 'type': 'request', + 'arguments': {} + } + response = self.send_recv(command_dict) + if response: + self.configuration_done_sent = True + return response + + def _process_stopped(self): + self.threads = None + self.frame_scopes = {} + + def request_continue(self, threadId=None): + if self.exit_status is not None: + raise ValueError('request_continue called after process exited') + # If we have launched or attached, then the first continue is done by + # sending the 'configurationDone' request + if not self.configuration_done_sent: + return self.request_configurationDone() + args_dict = {} + if threadId is None: + threadId = self.get_thread_id() + args_dict['threadId'] = threadId + command_dict = { + 'command': 'continue', + 'type': 'request', + 'arguments': args_dict + } + response = self.send_recv(command_dict) + # Caller must still call wait_for_stopped. + return response + + def request_disconnect(self, terminateDebuggee=None): + args_dict = {} + if terminateDebuggee is not None: + if terminateDebuggee: + args_dict['terminateDebuggee'] = True + else: + args_dict['terminateDebuggee'] = False + command_dict = { + 'command': 'disconnect', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_evaluate(self, expression, frameIndex=0, threadId=None): + stackFrame = self.get_stackFrame(frameIndex=frameIndex, + threadId=threadId) + if stackFrame is None: + return [] + args_dict = { + 'expression': expression, + 'frameId': stackFrame['id'], + } + command_dict = { + 'command': 'evaluate', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_initialize(self): + command_dict = { + 'command': 'initialize', + 'type': 'request', + 'arguments': { + 'adapterID': 'lldb-native', + 'clientID': 'vscode', + 'columnsStartAt1': True, + 'linesStartAt1': True, + 'locale': 'en-us', + 'pathFormat': 'path', + 'supportsRunInTerminalRequest': True, + 'supportsVariablePaging': True, + 'supportsVariableType': True + } + } + response = self.send_recv(command_dict) + if response: + if 'body' in response: + self.initialize_body = response['body'] + return response + + def request_launch(self, program, args=None, cwd=None, env=None, + stopOnEntry=False, disableASLR=True, + disableSTDIO=False, shellExpandArguments=False, + trace=False, initCommands=None, preRunCommands=None, + stopCommands=None, exitCommands=None, sourcePath=None, + debuggerRoot=None, launchCommands=None): + args_dict = { + 'program': program + } + if args: + args_dict['args'] = args + if cwd: + args_dict['cwd'] = cwd + if env: + args_dict['env'] = env + if stopOnEntry: + args_dict['stopOnEntry'] = stopOnEntry + if disableASLR: + args_dict['disableASLR'] = disableASLR + if disableSTDIO: + args_dict['disableSTDIO'] = disableSTDIO + if shellExpandArguments: + args_dict['shellExpandArguments'] = shellExpandArguments + if trace: + args_dict['trace'] = trace + args_dict['initCommands'] = self.init_commands + if initCommands: + args_dict['initCommands'].extend(initCommands) + if preRunCommands: + args_dict['preRunCommands'] = preRunCommands + if stopCommands: + args_dict['stopCommands'] = stopCommands + if exitCommands: + args_dict['exitCommands'] = exitCommands + if sourcePath: + args_dict['sourcePath'] = sourcePath + if debuggerRoot: + args_dict['debuggerRoot'] = debuggerRoot + if launchCommands: + args_dict['launchCommands'] = launchCommands + command_dict = { + 'command': 'launch', + 'type': 'request', + 'arguments': args_dict + } + response = self.send_recv(command_dict) + + # Wait for a 'process' and 'initialized' event in any order + self.wait_for_event(filter=['process', 'initialized']) + self.wait_for_event(filter=['process', 'initialized']) + return response + + def request_next(self, threadId): + if self.exit_status is not None: + raise ValueError('request_continue called after process exited') + args_dict = {'threadId': threadId} + command_dict = { + 'command': 'next', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_stepIn(self, threadId): + if self.exit_status is not None: + raise ValueError('request_continue called after process exited') + args_dict = {'threadId': threadId} + command_dict = { + 'command': 'stepIn', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_stepOut(self, threadId): + if self.exit_status is not None: + raise ValueError('request_continue called after process exited') + args_dict = {'threadId': threadId} + command_dict = { + 'command': 'stepOut', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_pause(self, threadId=None): + if self.exit_status is not None: + raise ValueError('request_continue called after process exited') + if threadId is None: + threadId = self.get_thread_id() + args_dict = {'threadId': threadId} + command_dict = { + 'command': 'pause', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_scopes(self, frameId): + args_dict = {'frameId': frameId} + command_dict = { + 'command': 'scopes', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_setBreakpoints(self, file_path, line_array, condition=None, + hitCondition=None): + (dir, base) = os.path.split(file_path) + breakpoints = [] + for line in line_array: + bp = {'line': line} + if condition is not None: + bp['condition'] = condition + if hitCondition is not None: + bp['hitCondition'] = hitCondition + breakpoints.append(bp) + source_dict = { + 'name': base, + 'path': file_path + } + args_dict = { + 'source': source_dict, + 'breakpoints': breakpoints, + 'lines': '%s' % (line_array), + 'sourceModified': False, + } + command_dict = { + 'command': 'setBreakpoints', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_setExceptionBreakpoints(self, filters): + args_dict = {'filters': filters} + command_dict = { + 'command': 'setExceptionBreakpoints', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_setFunctionBreakpoints(self, names, condition=None, + hitCondition=None): + breakpoints = [] + for name in names: + bp = {'name': name} + if condition is not None: + bp['condition'] = condition + if hitCondition is not None: + bp['hitCondition'] = hitCondition + breakpoints.append(bp) + args_dict = {'breakpoints': breakpoints} + command_dict = { + 'command': 'setFunctionBreakpoints', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_completions(self, text): + args_dict = { + 'text': text, + 'column': len(text) + } + command_dict = { + 'command': 'completions', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_stackTrace(self, threadId=None, startFrame=None, levels=None, + dump=False): + if threadId is None: + threadId = self.get_thread_id() + args_dict = {'threadId': threadId} + if startFrame is not None: + args_dict['startFrame'] = startFrame + if levels is not None: + args_dict['levels'] = levels + command_dict = { + 'command': 'stackTrace', + 'type': 'request', + 'arguments': args_dict + } + response = self.send_recv(command_dict) + if dump: + for (idx, frame) in enumerate(response['body']['stackFrames']): + name = frame['name'] + if 'line' in frame and 'source' in frame: + source = frame['source'] + if 'sourceReference' not in source: + if 'name' in source: + source_name = source['name'] + line = frame['line'] + print("[%3u] %s @ %s:%u" % (idx, name, source_name, + line)) + continue + print("[%3u] %s" % (idx, name)) + return response + + def request_threads(self): + '''Request a list of all threads and combine any information from any + "stopped" events since those contain more information about why a + thread actually stopped. Returns an array of thread dictionaries + with information about all threads''' + command_dict = { + 'command': 'threads', + 'type': 'request', + 'arguments': {} + } + response = self.send_recv(command_dict) + body = response['body'] + # Fill in "self.threads" correctly so that clients that call + # self.get_threads() or self.get_thread_id(...) can get information + # on threads when the process is stopped. + if 'threads' in body: + self.threads = body['threads'] + for thread in self.threads: + # Copy the thread dictionary so we can add key/value pairs to + # it without affecfting the original info from the "threads" + # command. + tid = thread['id'] + if tid in self.thread_stop_reasons: + thread_stop_info = self.thread_stop_reasons[tid] + copy_keys = ['reason', 'description', 'text'] + for key in copy_keys: + if key in thread_stop_info: + thread[key] = thread_stop_info[key] + else: + self.threads = None + return response + + def request_variables(self, variablesReference, start=None, count=None): + args_dict = {'variablesReference': variablesReference} + if start is not None: + args_dict['start'] = start + if count is not None: + args_dict['count'] = count + command_dict = { + 'command': 'variables', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_setVariable(self, containingVarRef, name, value, id=None): + args_dict = { + 'variablesReference': containingVarRef, + 'name': name, + 'value': str(value) + } + if id is not None: + args_dict['id'] = id + command_dict = { + 'command': 'setVariable', + 'type': 'request', + 'arguments': args_dict + } + return self.send_recv(command_dict) + + def request_testGetTargetBreakpoints(self): + '''A request packet used in the LLDB test suite to get all currently + set breakpoint infos for all breakpoints currently set in the + target. + ''' + command_dict = { + 'command': '_testGetTargetBreakpoints', + 'type': 'request', + 'arguments': {} + } + return self.send_recv(command_dict) + + def terminate(self): + self.send.close() + # self.recv.close() + + +class DebugAdaptor(DebugCommunication): + def __init__(self, executable=None, port=None, init_commands=[]): + self.process = None + if executable is not None: + self.process = subprocess.Popen([executable], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + DebugCommunication.__init__(self, self.process.stdout, + self.process.stdin, init_commands) + elif port is not None: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect(('127.0.0.1', port)) + DebugCommunication.__init__(self, s.makefile('r'), s.makefile('w'), + init_commands) + + def get_pid(self): + if self.process: + return self.process.pid + return -1 + + def terminate(self): + super(DebugAdaptor, self).terminate() + if self.process is not None: + self.process.terminate() + self.process.wait() + self.process = None + + +def attach_options_specified(options): + if options.pid is not None: + return True + if options.waitFor: + return True + if options.attach: + return True + if options.attachCmds: + return True + return False + + +def run_vscode(dbg, args, options): + dbg.request_initialize() + if attach_options_specified(options): + response = dbg.request_attach(program=options.program, + pid=options.pid, + waitFor=options.waitFor, + attachCommands=options.attachCmds, + initCommands=options.initCmds, + preRunCommands=options.preRunCmds, + stopCommands=options.stopCmds, + exitCommands=options.exitCmds) + else: + response = dbg.request_launch(options.program, + args=args, + env=options.envs, + cwd=options.workingDir, + debuggerRoot=options.debuggerRoot, + sourcePath=options.sourcePath, + initCommands=options.initCmds, + preRunCommands=options.preRunCmds, + stopCommands=options.stopCmds, + exitCommands=options.exitCmds) + + if response['success']: + if options.sourceBreakpoints: + source_to_lines = {} + for file_line in options.sourceBreakpoints: + (path, line) = file_line.split(':') + if len(path) == 0 or len(line) == 0: + print('error: invalid source with line "%s"' % + (file_line)) + + else: + if path in source_to_lines: + source_to_lines[path].append(int(line)) + else: + source_to_lines[path] = [int(line)] + for source in source_to_lines: + dbg.request_setBreakpoints(source, source_to_lines[source]) + if options.funcBreakpoints: + dbg.request_setFunctionBreakpoints(options.funcBreakpoints) + dbg.request_configurationDone() + dbg.wait_for_stopped() + else: + if 'message' in response: + print(response['message']) + dbg.request_disconnect(terminateDebuggee=True) + + +def main(): + parser = optparse.OptionParser( + description=('A testing framework for the Visual Studio Code Debug ' + 'Adaptor protocol')) + + parser.add_option( + '--vscode', + type='string', + dest='vscode_path', + help=('The path to the command line program that implements the ' + 'Visual Studio Code Debug Adaptor protocol.'), + default=None) + + parser.add_option( + '--program', + type='string', + dest='program', + help='The path to the program to debug.', + default=None) + + parser.add_option( + '--workingDir', + type='string', + dest='workingDir', + default=None, + help='Set the working directory for the process we launch.') + + parser.add_option( + '--sourcePath', + type='string', + dest='sourcePath', + default=None, + help=('Set the relative source root for any debug info that has ' + 'relative paths in it.')) + + parser.add_option( + '--debuggerRoot', + type='string', + dest='debuggerRoot', + default=None, + help=('Set the working directory for lldb-vscode for any object files ' + 'with relative paths in the Mach-o debug map.')) + + parser.add_option( + '-r', '--replay', + type='string', + dest='replay', + help=('Specify a file containing a packet log to replay with the ' + 'current Visual Studio Code Debug Adaptor executable.'), + default=None) + + parser.add_option( + '-g', '--debug', + action='store_true', + dest='debug', + default=False, + help='Pause waiting for a debugger to attach to the debug adaptor') + + parser.add_option( + '--port', + type='int', + dest='port', + help="Attach a socket to a port instead of using STDIN for VSCode", + default=None) + + parser.add_option( + '--pid', + type='int', + dest='pid', + help="The process ID to attach to", + default=None) + + parser.add_option( + '--attach', + action='store_true', + dest='attach', + default=False, + help=('Specify this option to attach to a process by name. The ' + 'process name is the basanme of the executable specified with ' + 'the --program option.')) + + parser.add_option( + '-f', '--function-bp', + type='string', + action='append', + dest='funcBreakpoints', + help=('Specify the name of a function to break at. ' + 'Can be specified more than once.'), + default=[]) + + parser.add_option( + '-s', '--source-bp', + type='string', + action='append', + dest='sourceBreakpoints', + default=[], + help=('Specify source breakpoints to set in the format of ' + '<source>:<line>. ' + 'Can be specified more than once.')) + + parser.add_option( + '--attachCommand', + type='string', + action='append', + dest='attachCmds', + default=[], + help=('Specify a LLDB command that will attach to a process. ' + 'Can be specified more than once.')) + + parser.add_option( + '--initCommand', + type='string', + action='append', + dest='initCmds', + default=[], + help=('Specify a LLDB command that will be executed before the target ' + 'is created. Can be specified more than once.')) + + parser.add_option( + '--preRunCommand', + type='string', + action='append', + dest='preRunCmds', + default=[], + help=('Specify a LLDB command that will be executed after the target ' + 'has been created. Can be specified more than once.')) + + parser.add_option( + '--stopCommand', + type='string', + action='append', + dest='stopCmds', + default=[], + help=('Specify a LLDB command that will be executed each time the' + 'process stops. Can be specified more than once.')) + + parser.add_option( + '--exitCommand', + type='string', + action='append', + dest='exitCmds', + default=[], + help=('Specify a LLDB command that will be executed when the process ' + 'exits. Can be specified more than once.')) + + parser.add_option( + '--env', + type='string', + action='append', + dest='envs', + default=[], + help=('Specify environment variables to pass to the launched ' + 'process.')) + + parser.add_option( + '--waitFor', + action='store_true', + dest='waitFor', + default=False, + help=('Wait for the next process to be launched whose name matches ' + 'the basename of the program specified with the --program ' + 'option')) + + (options, args) = parser.parse_args(sys.argv[1:]) + + if options.vscode_path is None and options.port is None: + print('error: must either specify a path to a Visual Studio Code ' + 'Debug Adaptor vscode executable path using the --vscode ' + 'option, or a port to attach to for an existing lldb-vscode ' + 'using the --port option') + return + dbg = DebugAdaptor(executable=options.vscode_path, port=options.port) + if options.debug: + raw_input('Waiting for debugger to attach pid "%i"' % ( + dbg.get_pid())) + if options.replay: + dbg.replay_packets(options.replay) + else: + run_vscode(dbg, args, options) + dbg.terminate() + + +if __name__ == '__main__': + main() diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/AbstractBase.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/AbstractBase.py new file mode 100644 index 00000000000..2ced1393772 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/AbstractBase.py @@ -0,0 +1,297 @@ +""" +Abstract base class of basic types provides a generic type tester method. +""" + +from __future__ import print_function + +import os +import re +import lldb +from lldbsuite.test.lldbtest import * +import lldbsuite.test.lldbutil as lldbutil + + +def Msg(var, val, using_frame_variable): + return "'%s %s' matches the output (from compiled code): %s" % ( + 'frame variable --show-types' if using_frame_variable else 'expression', var, val) + + +class GenericTester(TestBase): + + # This is the pattern by design to match the " var = 'value'" output from + # printf() stmts (see basic_type.cpp). + pattern = re.compile(" (\*?a[^=]*) = '([^=]*)'$") + + # Assert message. + DATA_TYPE_GROKKED = "Data type from expr parser output is parsed correctly" + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # We'll use the test method name as the exe_name. + # There are a bunch of test cases under test/types and we don't want the + # module cacheing subsystem to be confused with executable name "a.out" + # used for all the test cases. + self.exe_name = self.testMethodName + self.golden_filename = self.getBuildArtifact("golden-output.txt") + + def tearDown(self): + """Cleanup the test byproducts.""" + #print("Removing golden-output.txt...") + if os.path.exists(self.golden_filename): + os.remove(self.golden_filename) + TestBase.tearDown(self) + + #==========================================================================# + # Functions build_and_run() and build_and_run_expr() are generic functions # + # which are called from the Test*Types*.py test cases. The API client is # + # responsible for supplying two mandatory arguments: the source file, e.g.,# + # 'int.cpp', and the atoms, e.g., set(['unsigned', 'long long']) to the # + # functions. There are also three optional keyword arguments of interest, # + # as follows: # + # # + # bc -> blockCaptured (defaulted to False) # + # True: testing vars of various basic types from inside a block # + # False: testing vars of various basic types from a function # + # qd -> quotedDisplay (defaulted to False) # + # True: the output from 'frame var' or 'expr var' contains a pair # + # of single quotes around the value # + # False: no single quotes are to be found around the value of # + # variable # + #==========================================================================# + + def build_and_run(self, source, atoms, bc=False, qd=False): + self.build_and_run_with_source_atoms_expr( + source, atoms, expr=False, bc=bc, qd=qd) + + def build_and_run_expr(self, source, atoms, bc=False, qd=False): + self.build_and_run_with_source_atoms_expr( + source, atoms, expr=True, bc=bc, qd=qd) + + def build_and_run_with_source_atoms_expr( + self, source, atoms, expr, bc=False, qd=False): + # See also Makefile and basic_type.cpp:177. + if bc: + d = {'CXX_SOURCES': source, 'EXE': self.exe_name, + 'CFLAGS_EXTRAS': '-DTEST_BLOCK_CAPTURED_VARS'} + else: + d = {'CXX_SOURCES': source, 'EXE': self.exe_name} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + if expr: + self.generic_type_expr_tester( + self.exe_name, atoms, blockCaptured=bc, quotedDisplay=qd) + else: + self.generic_type_tester( + self.exe_name, + atoms, + blockCaptured=bc, + quotedDisplay=qd) + + def process_launch_o(self, localPath): + # process launch command output redirect always goes to host the + # process is running on + if lldb.remote_platform: + # process launch -o requires a path that is valid on the target + self.assertIsNotNone(lldb.remote_platform.GetWorkingDirectory()) + remote_path = lldbutil.append_to_process_working_directory(self, + "lldb-stdout-redirect.txt") + self.runCmd( + 'process launch -- {remote}'.format(remote=remote_path)) + # copy remote_path to local host + self.runCmd('platform get-file {remote} "{local}"'.format( + remote=remote_path, local=self.golden_filename)) + else: + self.runCmd( + 'process launch -o "{local}"'.format(local=self.golden_filename)) + + def generic_type_tester( + self, + exe_name, + atoms, + quotedDisplay=False, + blockCaptured=False): + """Test that variables with basic types are displayed correctly.""" + self.runCmd("file %s" % self.getBuildArtifact(exe_name), + CURRENT_EXECUTABLE_SET) + + # First, capture the golden output emitted by the oracle, i.e., the + # series of printf statements. + + self.process_launch_o(self.golden_filename) + + with open(self.golden_filename) as f: + go = f.read() + + # This golden list contains a list of (variable, value) pairs extracted + # from the golden output. + gl = [] + + # Scan the golden output line by line, looking for the pattern: + # + # variable = 'value' + # + for line in go.split(os.linesep): + # We'll ignore variables of array types from inside a block. + if blockCaptured and '[' in line: + continue + match = self.pattern.search(line) + if match: + var, val = match.group(1), match.group(2) + gl.append((var, val)) + #print("golden list:", gl) + + # This test uses a #include of "basic_type.cpp" so we need to enable + # always setting inlined breakpoints. + self.runCmd('settings set target.inline-breakpoint-strategy always') + # And add hooks to restore the settings during tearDown(). + self.addTearDownHook(lambda: self.runCmd( + "settings set target.inline-breakpoint-strategy headers")) + + # Bring the program to the point where we can issue a series of + # 'frame variable --show-types' command. + if blockCaptured: + break_line = line_number( + "basic_type.cpp", + "// Break here to test block captured variables.") + else: + break_line = line_number( + "basic_type.cpp", + "// Here is the line we will break on to check variables.") + lldbutil.run_break_set_by_file_and_line( + self, + "basic_type.cpp", + break_line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, + substrs=[" at basic_type.cpp:%d" % break_line, + "stop reason = breakpoint"]) + + #self.runCmd("frame variable --show-types") + + # Now iterate through the golden list, comparing against the output from + # 'frame variable --show-types var'. + for var, val in gl: + self.runCmd("frame variable --show-types %s" % var) + output = self.res.GetOutput() + + # The input type is in a canonical form as a set of named atoms. + # The display type string must contain each and every element. + # + # Example: + # runCmd: frame variable --show-types a_array_bounded[0] + # output: (char) a_array_bounded[0] = 'a' + # + try: + dt = re.match("^\((.*)\)", output).group(1) + except: + self.fail(self.DATA_TYPE_GROKKED) + + # Expect the display type string to contain each and every atoms. + self.expect( + dt, "Display type: '%s' must contain the type atoms: '%s'" % + (dt, atoms), exe=False, substrs=list(atoms)) + + # The (var, val) pair must match, too. + nv = ("%s = '%s'" if quotedDisplay else "%s = %s") % (var, val) + self.expect(output, Msg(var, val, True), exe=False, + substrs=[nv]) + + def generic_type_expr_tester( + self, + exe_name, + atoms, + quotedDisplay=False, + blockCaptured=False): + """Test that variable expressions with basic types are evaluated correctly.""" + + self.runCmd("file %s" % self.getBuildArtifact(exe_name), + CURRENT_EXECUTABLE_SET) + + # First, capture the golden output emitted by the oracle, i.e., the + # series of printf statements. + + self.process_launch_o(self.golden_filename) + + with open(self.golden_filename) as f: + go = f.read() + + # This golden list contains a list of (variable, value) pairs extracted + # from the golden output. + gl = [] + + # Scan the golden output line by line, looking for the pattern: + # + # variable = 'value' + # + for line in go.split(os.linesep): + # We'll ignore variables of array types from inside a block. + if blockCaptured and '[' in line: + continue + match = self.pattern.search(line) + if match: + var, val = match.group(1), match.group(2) + gl.append((var, val)) + #print("golden list:", gl) + + # This test uses a #include of "basic_type.cpp" so we need to enable + # always setting inlined breakpoints. + self.runCmd('settings set target.inline-breakpoint-strategy always') + # And add hooks to restore the settings during tearDown(). + self.addTearDownHook(lambda: self.runCmd( + "settings set target.inline-breakpoint-strategy headers")) + + # Bring the program to the point where we can issue a series of + # 'expr' command. + if blockCaptured: + break_line = line_number( + "basic_type.cpp", + "// Break here to test block captured variables.") + else: + break_line = line_number( + "basic_type.cpp", + "// Here is the line we will break on to check variables.") + lldbutil.run_break_set_by_file_and_line( + self, + "basic_type.cpp", + break_line, + num_expected_locations=1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + self.expect("process status", STOPPED_DUE_TO_BREAKPOINT, + substrs=[" at basic_type.cpp:%d" % break_line, + "stop reason = breakpoint"]) + + #self.runCmd("frame variable --show-types") + + # Now iterate through the golden list, comparing against the output from + # 'expr var'. + for var, val in gl: + self.runCmd("expression %s" % var) + output = self.res.GetOutput() + + # The input type is in a canonical form as a set of named atoms. + # The display type string must contain each and every element. + # + # Example: + # runCmd: expr a + # output: (double) $0 = 1100.12 + # + try: + dt = re.match("^\((.*)\) \$[0-9]+ = ", output).group(1) + except: + self.fail(self.DATA_TYPE_GROKKED) + + # Expect the display type string to contain each and every atoms. + self.expect( + dt, "Display type: '%s' must contain the type atoms: '%s'" % + (dt, atoms), exe=False, substrs=list(atoms)) + + # The val part must match, too. + valPart = ("'%s'" if quotedDisplay else "%s") % val + self.expect(output, Msg(var, val, False), exe=False, + substrs=[valPart]) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/HideTestFailures.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/HideTestFailures.py new file mode 100644 index 00000000000..91b1383b72f --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/HideTestFailures.py @@ -0,0 +1,78 @@ +""" +Test that variables of integer basic types are displayed correctly. +""" + + + +import AbstractBase +import lldb +from lldbsuite.test.lldbtest import * + +# rdar://problem/9649573 +# Capture the lldb and gdb-remote log files for test failures when run +# with no "-w" option + + +class DebugIntegerTypesFailures(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + # If we're lucky, test_long_type_with_dsym fails. + # Let's turn on logging just for that. + try: + if "test_long_type_with_dsym" in self.id(): + self.runCmd( + "log enable -n -f %s lldb commands event process state" % + os.environ["DEBUG_LLDB_LOG"]) + self.runCmd( + "log enable -n -f %s gdb-remote packets process" % + os.environ["DEBUG_GDB_REMOTE_LOG"]) + except: + pass + + def tearDown(self): + # If we're lucky, test_long_type_with_dsym fails. + # Let's turn off logging just for that. + if "test_long_type_with_dsym" in self.id(): + self.runCmd("log disable lldb") + self.runCmd("log disable gdb-remote") + # Call super's tearDown(). + TestBase.tearDown(self) + + def test_char_type(self): + """Test that char-type variables are displayed correctly.""" + d = {'CXX_SOURCES': 'char.cpp'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.generic_type_tester(set(['char']), quotedDisplay=True) + + def test_short_type(self): + """Test that short-type variables are displayed correctly.""" + d = {'CXX_SOURCES': 'short.cpp'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.generic_type_tester(set(['short'])) + + def test_int_type(self): + """Test that int-type variables are displayed correctly.""" + d = {'CXX_SOURCES': 'int.cpp'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.generic_type_tester(set(['int'])) + + def test_long_type(self): + """Test that long-type variables are displayed correctly.""" + d = {'CXX_SOURCES': 'long.cpp'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.generic_type_tester(set(['long'])) + + def test_long_long_type(self): + """Test that 'long long'-type variables are displayed correctly.""" + d = {'CXX_SOURCES': 'long_long.cpp'} + self.build(dictionary=d) + self.setTearDownCleanup(dictionary=d) + self.generic_type_tester(set(['long long'])) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/Makefile b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/Makefile new file mode 100644 index 00000000000..d48ed7688a4 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/Makefile @@ -0,0 +1,5 @@ +# Example: +# +# CXX_SOURCES := int.cpp + +include Makefile.rules diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestCharType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestCharType.py new file mode 100644 index 00000000000..bc568702c66 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestCharType.py @@ -0,0 +1,32 @@ +""" +Test that variables of type char are displayed correctly. +""" + +import AbstractBase + +from lldbsuite.test.decorators import * + + +class CharTypeTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + def test_char_type(self): + """Test that char-type variables are displayed correctly.""" + self.build_and_run('char.cpp', set(['char']), qd=True) + + @skipUnlessDarwin + def test_char_type_from_block(self): + """Test that char-type variables are displayed correctly from a block.""" + self.build_and_run('char.cpp', set(['char']), bc=True, qd=True) + + def test_unsigned_char_type(self): + """Test that 'unsigned_char'-type variables are displayed correctly.""" + self.build_and_run( + 'unsigned_char.cpp', set(['unsigned', 'char']), qd=True) + + @skipUnlessDarwin + def test_unsigned_char_type_from_block(self): + """Test that 'unsigned char'-type variables are displayed correctly from a block.""" + self.build_and_run( + 'unsigned_char.cpp', set(['unsigned', 'char']), bc=True, qd=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestCharTypeExpr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestCharTypeExpr.py new file mode 100644 index 00000000000..63ddc1451b9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestCharTypeExpr.py @@ -0,0 +1,32 @@ +""" +Test that variable expressions of type char are evaluated correctly. +""" + +import AbstractBase + +from lldbsuite.test.decorators import * + + +class CharTypeExprTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + def test_char_type(self): + """Test that char-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('char.cpp', set(['char']), qd=True) + + @skipUnlessDarwin + def test_char_type_from_block(self): + """Test that char-type variables are displayed correctly from a block.""" + self.build_and_run_expr('char.cpp', set(['char']), bc=True, qd=True) + + def test_unsigned_char_type(self): + """Test that 'unsigned_char'-type variable expressions are evaluated correctly.""" + self.build_and_run_expr( + 'unsigned_char.cpp', set(['unsigned', 'char']), qd=True) + + @skipUnlessDarwin + def test_unsigned_char_type_from_block(self): + """Test that 'unsigned char'-type variables are displayed correctly from a block.""" + self.build_and_run_expr( + 'unsigned_char.cpp', set(['unsigned', 'char']), bc=True, qd=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestDoubleTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestDoubleTypes.py new file mode 100644 index 00000000000..adce103cb08 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestDoubleTypes.py @@ -0,0 +1,26 @@ +""" +Test that variables of floating point types are displayed correctly. +""" + + + +import AbstractBase + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DoubleTypesTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + def test_double_type(self): + """Test that double-type variables are displayed correctly.""" + self.build_and_run('double.cpp', set(['double'])) + + @skipUnlessDarwin + def test_double_type_from_block(self): + """Test that double-type variables are displayed correctly from a block.""" + self.build_and_run('double.cpp', set(['double']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestDoubleTypesExpr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestDoubleTypesExpr.py new file mode 100644 index 00000000000..20c54100021 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestDoubleTypesExpr.py @@ -0,0 +1,30 @@ +""" +Test that variable expressions of floating point types are evaluated correctly. +""" + + + +import AbstractBase + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class DoubleTypesExprTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + # rdar://problem/8493023 + # test/types failures for Test*TypesExpr.py: element offset computed wrong + # and sign error? + + def test_double_type(self): + """Test that double-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('double.cpp', set(['double'])) + + @skipUnlessDarwin + def test_double_type_from_block(self): + """Test that double-type variables are displayed correctly from a block.""" + self.build_and_run_expr('double.cpp', set(['double']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestFloatTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestFloatTypes.py new file mode 100644 index 00000000000..73775522658 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestFloatTypes.py @@ -0,0 +1,26 @@ +""" +Test that variables of floating point types are displayed correctly. +""" + + + +import AbstractBase + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class FloatTypesTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + def test_float_type(self): + """Test that float-type variables are displayed correctly.""" + self.build_and_run('float.cpp', set(['float'])) + + @skipUnlessDarwin + def test_float_type_from_block(self): + """Test that float-type variables are displayed correctly from a block.""" + self.build_and_run('float.cpp', set(['float']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py new file mode 100644 index 00000000000..ceb257e3dab --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py @@ -0,0 +1,30 @@ +""" +Test that variable expressions of floating point types are evaluated correctly. +""" + + + +import AbstractBase + +import lldb +from lldbsuite.test.decorators import * +from lldbsuite.test.lldbtest import * +from lldbsuite.test import lldbutil + + +class FloatTypesExprTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + # rdar://problem/8493023 + # test/types failures for Test*TypesExpr.py: element offset computed wrong + # and sign error? + + def test_float_type(self): + """Test that float-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('float.cpp', set(['float'])) + + @skipUnlessDarwin + def test_float_type_from_block(self): + """Test that float-type variables are displayed correctly from a block.""" + self.build_and_run_expr('float.cpp', set(['float']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestIntegerType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestIntegerType.py new file mode 100644 index 00000000000..549b37af3e8 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestIntegerType.py @@ -0,0 +1,31 @@ +""" +Test that variables of type integer are displayed correctly. +""" + +import AbstractBase + +from lldbsuite.test.decorators import * + + +class IntegerTypesTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + def test_int_type(self): + """Test that int-type variables are displayed correctly.""" + self.build_and_run('int.cpp', set(['int'])) + + @skipUnlessDarwin + def test_int_type_from_block(self): + """Test that int-type variables are displayed correctly from a block.""" + self.build_and_run('int.cpp', set(['int'])) + + def test_unsigned_int_type(self): + """Test that 'unsigned_int'-type variables are displayed correctly.""" + self.build_and_run('unsigned_int.cpp', set(['unsigned', 'int'])) + + @skipUnlessDarwin + def test_unsigned_int_type_from_block(self): + """Test that 'unsigned int'-type variables are displayed correctly from a block.""" + self.build_and_run( + 'unsigned_int.cpp', set(['unsigned', 'int']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypeExpr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypeExpr.py new file mode 100644 index 00000000000..0b258dbaa67 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestIntegerTypeExpr.py @@ -0,0 +1,37 @@ +""" +Test that variable expressions of type integer are evaluated correctly. +""" + +import AbstractBase + +from lldbsuite.test.decorators import * + + +class IntegerTypeExprTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + @skipUnlessDarwin + def test_unsigned_short_type_from_block(self): + """Test that 'unsigned short'-type variables are displayed correctly from a block.""" + self.build_and_run_expr( + 'unsigned_short.cpp', set(['unsigned', 'short']), bc=True) + + def test_int_type(self): + """Test that int-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('int.cpp', set(['int'])) + + @skipUnlessDarwin + def test_int_type_from_block(self): + """Test that int-type variables are displayed correctly from a block.""" + self.build_and_run_expr('int.cpp', set(['int'])) + + def test_unsigned_int_type(self): + """Test that 'unsigned_int'-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('unsigned_int.cpp', set(['unsigned', 'int'])) + + @skipUnlessDarwin + def test_unsigned_int_type_from_block(self): + """Test that 'unsigned int'-type variables are displayed correctly from a block.""" + self.build_and_run_expr( + 'unsigned_int.cpp', set(['unsigned', 'int']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestLongTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestLongTypes.py new file mode 100644 index 00000000000..28f81937409 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestLongTypes.py @@ -0,0 +1,51 @@ +""" +Test that variables of integer basic types are displayed correctly. +""" + +import AbstractBase + +from lldbsuite.test.decorators import * + + +class LongTypesTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + def test_long_type(self): + """Test that long-type variables are displayed correctly.""" + self.build_and_run('long.cpp', set(['long'])) + + @skipUnlessDarwin + def test_long_type_from_block(self): + """Test that long-type variables are displayed correctly from a block.""" + self.build_and_run('long.cpp', set(['long']), bc=True) + + def test_unsigned_long_type(self): + """Test that 'unsigned long'-type variables are displayed correctly.""" + self.build_and_run('unsigned_long.cpp', set(['unsigned', 'long'])) + + @skipUnlessDarwin + def test_unsigned_long_type_from_block(self): + """Test that 'unsigned_long'-type variables are displayed correctly from a block.""" + self.build_and_run( + 'unsigned_long.cpp', set(['unsigned', 'long']), bc=True) + + def test_long_long_type(self): + """Test that 'long long'-type variables are displayed correctly.""" + self.build_and_run('long_long.cpp', set(['long long'])) + + @skipUnlessDarwin + def test_long_long_type_from_block(self): + """Test that 'long_long'-type variables are displayed correctly from a block.""" + self.build_and_run('long_long.cpp', set(['long long']), bc=True) + + def test_unsigned_long_long_type(self): + """Test that 'unsigned long long'-type variables are displayed correctly.""" + self.build_and_run('unsigned_long_long.cpp', + set(['unsigned', 'long long'])) + + @skipUnlessDarwin + def test_unsigned_long_long_type_from_block(self): + """Test that 'unsigned_long_long'-type variables are displayed correctly from a block.""" + self.build_and_run( + 'unsigned_long_long.cpp', set(['unsigned', 'long long']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestLongTypesExpr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestLongTypesExpr.py new file mode 100644 index 00000000000..b753a9d5a89 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestLongTypesExpr.py @@ -0,0 +1,51 @@ +""" +Test that variable expressions of integer basic types are evaluated correctly. +""" + +import AbstractBase + +from lldbsuite.test.decorators import * + + +class LongTypesExprTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + def test_long_type(self): + """Test that long-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('long.cpp', set(['long'])) + + @skipUnlessDarwin + def test_long_type_from_block(self): + """Test that long-type variables are displayed correctly from a block.""" + self.build_and_run_expr('long.cpp', set(['long']), bc=True) + + def test_unsigned_long_type(self): + """Test that 'unsigned long'-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('unsigned_long.cpp', set(['unsigned', 'long'])) + + @skipUnlessDarwin + def test_unsigned_long_type_from_block(self): + """Test that 'unsigned_long'-type variables are displayed correctly from a block.""" + self.build_and_run_expr( + 'unsigned_long.cpp', set(['unsigned', 'long']), bc=True) + + def test_long_long_type(self): + """Test that 'long long'-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('long_long.cpp', set(['long long'])) + + @skipUnlessDarwin + def test_long_long_type_from_block(self): + """Test that 'long_long'-type variables are displayed correctly from a block.""" + self.build_and_run_expr('long_long.cpp', set(['long long']), bc=True) + + def test_unsigned_long_long_type(self): + """Test that 'unsigned long long'-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('unsigned_long_long.cpp', + set(['unsigned', 'long long'])) + + @skipUnlessDarwin + def test_unsigned_long_long_type_from_block(self): + """Test that 'unsigned_long_long'-type variables are displayed correctly from a block.""" + self.build_and_run_expr( + 'unsigned_long_long.cpp', set(['unsigned', 'long long']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py new file mode 100644 index 00000000000..69194cfb96a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py @@ -0,0 +1,54 @@ +""" +Test that recursive types are handled correctly. +""" + + + +import lldb +import lldbsuite.test.lldbutil as lldbutil +from lldbsuite.test.lldbtest import * + + +class RecursiveTypesTestCase(TestBase): + + mydir = TestBase.compute_mydir(__file__) + + def setUp(self): + # Call super's setUp(). + TestBase.setUp(self) + + # Find the line number to break for main.c. + self.line = line_number('recursive_type_main.cpp', + '// Test at this line.') + + self.d1 = { + 'CXX_SOURCES': 'recursive_type_main.cpp recursive_type_1.cpp'} + self.d2 = { + 'CXX_SOURCES': 'recursive_type_main.cpp recursive_type_2.cpp'} + + def test_recursive_type_1(self): + """Test that recursive structs are displayed correctly.""" + self.build(dictionary=self.d1) + self.setTearDownCleanup(dictionary=self.d1) + self.print_struct() + + def test_recursive_type_2(self): + """Test that recursive structs are displayed correctly.""" + self.build(dictionary=self.d2) + self.setTearDownCleanup(dictionary=self.d2) + self.print_struct() + + def print_struct(self): + self.runCmd("file " + self.getBuildArtifact("a.out"), CURRENT_EXECUTABLE_SET) + + lldbutil.run_break_set_by_file_and_line( + self, + "recursive_type_main.cpp", + self.line, + num_expected_locations=-1, + loc_exact=True) + + self.runCmd("run", RUN_SUCCEEDED) + + self.expect("print tpi", RUN_SUCCEEDED) + self.expect("print *tpi", RUN_SUCCEEDED) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestShortType.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestShortType.py new file mode 100644 index 00000000000..d940d1ba017 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestShortType.py @@ -0,0 +1,31 @@ +""" +Test that variables of type short are displayed correctly. +""" + +import AbstractBase + +from lldbsuite.test.decorators import * + + +class ShortTypeTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + def test_short_type(self): + """Test that short-type variables are displayed correctly.""" + self.build_and_run('short.cpp', set(['short'])) + + @skipUnlessDarwin + def test_short_type_from_block(self): + """Test that short-type variables are displayed correctly from a block.""" + self.build_and_run('short.cpp', set(['short']), bc=True) + + def test_unsigned_short_type(self): + """Test that 'unsigned_short'-type variables are displayed correctly.""" + self.build_and_run('unsigned_short.cpp', set(['unsigned', 'short'])) + + @skipUnlessDarwin + def test_unsigned_short_type_from_block(self): + """Test that 'unsigned short'-type variables are displayed correctly from a block.""" + self.build_and_run( + 'unsigned_short.cpp', set(['unsigned', 'short']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestShortTypeExpr.py b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestShortTypeExpr.py new file mode 100644 index 00000000000..17bcfd378e1 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/TestShortTypeExpr.py @@ -0,0 +1,32 @@ +""" +Test that variable expressions of type short are evaluated correctly. +""" + +import AbstractBase + +from lldbsuite.test.decorators import * + + +class ShortExprTestCase(AbstractBase.GenericTester): + + mydir = AbstractBase.GenericTester.compute_mydir(__file__) + + def test_short_type(self): + """Test that short-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('short.cpp', set(['short'])) + + @skipUnlessDarwin + def test_short_type_from_block(self): + """Test that short-type variables are displayed correctly from a block.""" + self.build_and_run_expr('short.cpp', set(['short']), bc=True) + + def test_unsigned_short_type(self): + """Test that 'unsigned_short'-type variable expressions are evaluated correctly.""" + self.build_and_run_expr('unsigned_short.cpp', + set(['unsigned', 'short'])) + + @skipUnlessDarwin + def test_unsigned_short_type_from_block(self): + """Test that 'unsigned short'-type variables are displayed correctly from a block.""" + self.build_and_run_expr( + 'unsigned_short.cpp', set(['unsigned', 'short']), bc=True) diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/basic_type.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/basic_type.cpp new file mode 100644 index 00000000000..2d7e7b2e21b --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/basic_type.cpp @@ -0,0 +1,225 @@ +// This file must have the following defined before it is included: +// T defined to the type to test (int, float, etc) +// T_CSTR a C string representation of the type T ("int", "float") +// T_VALUE_1 defined to a valid initializer value for TEST_TYPE (7 for int, 2.0 for float) +// T_VALUE_2, T_VALUE_3, T_VALUE_4 defined to a valid initializer value for TEST_TYPE that is different from TEST_VALUE_1 +// T_PRINTF_FORMAT defined if T can be printed with printf +// +// An example for integers is below +#if 0 + +#define T int +#define T_CSTR "int" +#define T_VALUE_1 11001110 +#define T_VALUE_2 22002220 +#define T_VALUE_3 33003330 +#define T_VALUE_4 44044440 +#define T_PRINTF_FORMAT "%i" + +#include "basic_type.cpp" + +#endif + +#ifdef TEST_BLOCK_CAPTURED_VARS +#include <dispatch/dispatch.h> +#endif +#include <cstdint> +#include <cstdio> +#include <cstdlib> + +class a_class +{ +public: + a_class (const T& a, const T& b) : + m_a (a), + m_b (b) + { + } + + ~a_class () + { + } + + const T& + get_a() const + { + return m_a; + } + + void + set_a (const T& a) + { + m_a = a; + } + + const T& + get_b() const + { + return m_b; + } + + void + set_b (const T& b) + { + m_b = b; + } + +protected: + T m_a; + T m_b; +}; + +typedef struct a_struct_tag { + T a; + T b; +} a_struct_t; + + +typedef union a_union_zero_tag { + T a; + double a_double; +} a_union_zero_t; + +typedef struct a_union_nonzero_tag { + double a_double; + a_union_zero_t u; +} a_union_nonzero_t; + + +int +main (int argc, char const *argv[]) +{ + FILE *out = stdout; + + // By default, output to stdout + // If a filename is provided as the command line argument, + // output to that file. + if (argc == 2 && argv[1] && argv[1][0] != '\0') + { + out = fopen (argv[1], "w"); + } + + T a = T_VALUE_1; + T* a_ptr = &a; + T& a_ref = a; + T a_array_bounded[2] = { T_VALUE_1, T_VALUE_2 }; + T a_array_unbounded[] = { T_VALUE_1, T_VALUE_2 }; + + a_class a_class_instance (T_VALUE_1, T_VALUE_2); + a_class *a_class_ptr = &a_class_instance; + a_class &a_class_ref = a_class_instance; + + a_struct_t a_struct = { T_VALUE_1, T_VALUE_2 }; + a_struct_t *a_struct_ptr = &a_struct; + a_struct_t &a_struct_ref = a_struct; + + // Create a union with type T at offset zero + a_union_zero_t a_union_zero; + a_union_zero.a = T_VALUE_1; + a_union_zero_t *a_union_zero_ptr = &a_union_zero; + a_union_zero_t &a_union_zero_ref = a_union_zero; + + // Create a union with type T at a non-zero offset + a_union_nonzero_t a_union_nonzero; + a_union_nonzero.u.a = T_VALUE_1; + a_union_nonzero_t *a_union_nonzero_ptr = &a_union_nonzero; + a_union_nonzero_t &a_union_nonzero_ref = a_union_nonzero; + + a_struct_t a_struct_array_bounded[2] = {{ T_VALUE_1, T_VALUE_2 }, { T_VALUE_3, T_VALUE_4 }}; + a_struct_t a_struct_array_unbounded[] = {{ T_VALUE_1, T_VALUE_2 }, { T_VALUE_3, T_VALUE_4 }}; + a_union_zero_t a_union_zero_array_bounded[2]; + a_union_zero_array_bounded[0].a = T_VALUE_1; + a_union_zero_array_bounded[1].a = T_VALUE_2; + a_union_zero_t a_union_zero_array_unbounded[] = {{ T_VALUE_1 }, { T_VALUE_2 }}; + +#ifdef T_PRINTF_FORMAT + fprintf (out, "%s: a = '" T_PRINTF_FORMAT "'\n", T_CSTR, a); + fprintf (out, "%s*: %p => *a_ptr = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_ptr, *a_ptr); + fprintf (out, "%s&: @%p => a_ref = '" T_PRINTF_FORMAT "'\n", T_CSTR, &a_ref, a_ref); + + fprintf (out, "%s[2]: a_array_bounded[0] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_bounded[0]); + fprintf (out, "%s[2]: a_array_bounded[1] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_bounded[1]); + + fprintf (out, "%s[]: a_array_unbounded[0] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_unbounded[0]); + fprintf (out, "%s[]: a_array_unbounded[1] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_unbounded[1]); + + fprintf (out, "(a_class) a_class_instance.m_a = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_a()); + fprintf (out, "(a_class) a_class_instance.m_b = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_b()); + fprintf (out, "(a_class*) a_class_ptr = %p, a_class_ptr->m_a = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_a()); + fprintf (out, "(a_class*) a_class_ptr = %p, a_class_ptr->m_b = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_b()); + fprintf (out, "(a_class&) a_class_ref = %p, a_class_ref.m_a = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_a()); + fprintf (out, "(a_class&) a_class_ref = %p, a_class_ref.m_b = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_b()); + + fprintf (out, "(a_struct_t) a_struct.a = '" T_PRINTF_FORMAT "'\n", a_struct.a); + fprintf (out, "(a_struct_t) a_struct.b = '" T_PRINTF_FORMAT "'\n", a_struct.b); + fprintf (out, "(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->a = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->a); + fprintf (out, "(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->b = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->b); + fprintf (out, "(a_struct_t&) a_struct_ref = %p, a_struct_ref.a = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.a); + fprintf (out, "(a_struct_t&) a_struct_ref = %p, a_struct_ref.b = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.b); + + fprintf (out, "(a_union_zero_t) a_union_zero.a = '" T_PRINTF_FORMAT "'\n", a_union_zero.a); + fprintf (out, "(a_union_zero_t*) a_union_zero_ptr = %p, a_union_zero_ptr->a = '" T_PRINTF_FORMAT "'\n", a_union_zero_ptr, a_union_zero_ptr->a); + fprintf (out, "(a_union_zero_t&) a_union_zero_ref = %p, a_union_zero_ref.a = '" T_PRINTF_FORMAT "'\n", &a_union_zero_ref, a_union_zero_ref.a); + + fprintf (out, "(a_union_nonzero_t) a_union_nonzero.u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero.u.a); + fprintf (out, "(a_union_nonzero_t*) a_union_nonzero_ptr = %p, a_union_nonzero_ptr->u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero_ptr, a_union_nonzero_ptr->u.a); + fprintf (out, "(a_union_nonzero_t&) a_union_nonzero_ref = %p, a_union_nonzero_ref.u.a = '" T_PRINTF_FORMAT "'\n", &a_union_nonzero_ref, a_union_nonzero_ref.u.a); + + fprintf (out, "(a_struct_t[2]) a_struct_array_bounded[0].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[0].a); + fprintf (out, "(a_struct_t[2]) a_struct_array_bounded[0].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[0].b); + fprintf (out, "(a_struct_t[2]) a_struct_array_bounded[1].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[1].a); + fprintf (out, "(a_struct_t[2]) a_struct_array_bounded[1].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[1].b); + + fprintf (out, "(a_struct_t[]) a_struct_array_unbounded[0].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[0].a); + fprintf (out, "(a_struct_t[]) a_struct_array_unbounded[0].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[0].b); + fprintf (out, "(a_struct_t[]) a_struct_array_unbounded[1].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[1].a); + fprintf (out, "(a_struct_t[]) a_struct_array_unbounded[1].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[1].b); + + fprintf (out, "(a_union_zero_t[2]) a_union_zero_array_bounded[0].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_bounded[0].a); + fprintf (out, "(a_union_zero_t[2]) a_union_zero_array_bounded[1].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_bounded[1].a); + + fprintf (out, "(a_union_zero_t[]) a_union_zero_array_unbounded[0].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_unbounded[0].a); + fprintf (out, "(a_union_zero_t[]) a_union_zero_array_unbounded[1].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_unbounded[1].a); + +#endif + puts("About to exit, break here to check values..."); // Here is the line we will break on to check variables. + +#ifdef TEST_BLOCK_CAPTURED_VARS + void (^myBlock)() = ^() { + fprintf (out, "%s: a = '" T_PRINTF_FORMAT "'\n", T_CSTR, a); + fprintf (out, "%s*: %p => *a_ptr = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_ptr, *a_ptr); + fprintf (out, "%s&: @%p => a_ref = '" T_PRINTF_FORMAT "'\n", T_CSTR, &a_ref, a_ref); + + fprintf (out, "(a_class) a_class_instance.m_a = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_a()); + fprintf (out, "(a_class) a_class_instance.m_b = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_b()); + fprintf (out, "(a_class*) a_class_ptr = %p, a_class_ptr->m_a = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_a()); + fprintf (out, "(a_class*) a_class_ptr = %p, a_class_ptr->m_b = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_b()); + fprintf (out, "(a_class&) a_class_ref = %p, a_class_ref.m_a = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_a()); + fprintf (out, "(a_class&) a_class_ref = %p, a_class_ref.m_b = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_b()); + + fprintf (out, "(a_struct_t) a_struct.a = '" T_PRINTF_FORMAT "'\n", a_struct.a); + fprintf (out, "(a_struct_t) a_struct.b = '" T_PRINTF_FORMAT "'\n", a_struct.b); + fprintf (out, "(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->a = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->a); + fprintf (out, "(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->b = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->b); + fprintf (out, "(a_struct_t&) a_struct_ref = %p, a_struct_ref.a = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.a); + fprintf (out, "(a_struct_t&) a_struct_ref = %p, a_struct_ref.b = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.b); + + fprintf (out, "(a_union_zero_t) a_union_zero.a = '" T_PRINTF_FORMAT "'\n", a_union_zero.a); + fprintf (out, "(a_union_zero_t*) a_union_zero_ptr = %p, a_union_zero_ptr->a = '" T_PRINTF_FORMAT "'\n", a_union_zero_ptr, a_union_zero_ptr->a); + fprintf (out, "(a_union_zero_t&) a_union_zero_ref = %p, a_union_zero_ref.a = '" T_PRINTF_FORMAT "'\n", &a_union_zero_ref, a_union_zero_ref.a); + + fprintf (out, "(a_union_nonzero_t) a_union_nonzero.u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero.u.a); + fprintf (out, "(a_union_nonzero_t*) a_union_nonzero_ptr = %p, a_union_nonzero_ptr->u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero_ptr, a_union_nonzero_ptr->u.a); + fprintf (out, "(a_union_nonzero_t&) a_union_nonzero_ref = %p, a_union_nonzero_ref.u.a = '" T_PRINTF_FORMAT "'\n", &a_union_nonzero_ref, a_union_nonzero_ref.u.a); + + fprintf (out, "That's All Folks!\n"); // Break here to test block captured variables. + }; + + myBlock(); +#endif + + if (out != stdout) + fclose (out); + + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/char.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/char.cpp new file mode 100644 index 00000000000..584582ed9b9 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/char.cpp @@ -0,0 +1,9 @@ +#define T char +#define T_CSTR "char" +#define T_VALUE_1 'a' +#define T_VALUE_2 'b' +#define T_VALUE_3 '!' +#define T_VALUE_4 '~' +#define T_PRINTF_FORMAT "%c" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/double.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/double.cpp new file mode 100644 index 00000000000..6788dadfe02 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/double.cpp @@ -0,0 +1,9 @@ +#define T double +#define T_CSTR "double" +#define T_VALUE_1 1100.125 +#define T_VALUE_2 2200.250 +#define T_VALUE_3 33.00 +#define T_VALUE_4 44.00 +#define T_PRINTF_FORMAT "%lg" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/float.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/float.cpp new file mode 100644 index 00000000000..4bc124661aa --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/float.cpp @@ -0,0 +1,9 @@ +#define T float +#define T_CSTR "float" +#define T_VALUE_1 1100.125 +#define T_VALUE_2 2200.250 +#define T_VALUE_3 33.00 +#define T_VALUE_4 44.00 +#define T_PRINTF_FORMAT "%g" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/int.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/int.cpp new file mode 100644 index 00000000000..922398b1c6e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/int.cpp @@ -0,0 +1,9 @@ +#define T int +#define T_CSTR "int" +#define T_VALUE_1 11001110 +#define T_VALUE_2 22002220 +#define T_VALUE_3 33003330 +#define T_VALUE_4 44004440 +#define T_PRINTF_FORMAT "%i" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/long.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/long.cpp new file mode 100644 index 00000000000..9056b42ee77 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/long.cpp @@ -0,0 +1,18 @@ +#define T long +#define T_CSTR "long" + +#ifdef __LP64__ +#define T_VALUE_1 110011101111 +#define T_VALUE_2 220022202222 +#define T_VALUE_3 330033303333 +#define T_VALUE_4 440044404444 +#else +#define T_VALUE_1 110011101 +#define T_VALUE_2 220022202 +#define T_VALUE_3 330033303 +#define T_VALUE_4 440044404 +#endif + +#define T_PRINTF_FORMAT "%ld" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/long_long.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/long_long.cpp new file mode 100644 index 00000000000..5b442e7257e --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/long_long.cpp @@ -0,0 +1,18 @@ +#define T long long +#define T_CSTR "long long" + +#ifdef __LP64__ +#define T_VALUE_1 110011101111 +#define T_VALUE_2 220022202222 +#define T_VALUE_3 330033303333 +#define T_VALUE_4 440044404444 +#else +#define T_VALUE_1 110011101 +#define T_VALUE_2 220022202 +#define T_VALUE_3 330033303 +#define T_VALUE_4 440044404 +#endif + +#define T_PRINTF_FORMAT "%lld" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/recursive_type_1.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/recursive_type_1.cpp new file mode 100644 index 00000000000..81d923ffd94 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/recursive_type_1.cpp @@ -0,0 +1,12 @@ +typedef struct t *tp; +typedef tp (*get_tp)(); + +struct s { + get_tp get_tp_p; +}; + +struct t { + struct s *s; +}; + +struct t t; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/recursive_type_2.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/recursive_type_2.cpp new file mode 100644 index 00000000000..304739049a0 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/recursive_type_2.cpp @@ -0,0 +1,10 @@ +typedef struct t *tp; +typedef tp (*get_tp)(); + +struct t { + struct { + get_tp get_tp_p; + }; +}; + +struct t t; diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/recursive_type_main.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/recursive_type_main.cpp new file mode 100644 index 00000000000..e06cd309be3 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/recursive_type_main.cpp @@ -0,0 +1,8 @@ +typedef struct t *tp; +extern struct t t; + +int main() { + tp tpi = &t; + // Test at this line. + return 0; +} diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/short.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/short.cpp new file mode 100644 index 00000000000..470c68aa8ba --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/short.cpp @@ -0,0 +1,9 @@ +#define T short +#define T_CSTR "short" +#define T_VALUE_1 11001 +#define T_VALUE_2 22002 +#define T_VALUE_3 -32768 +#define T_VALUE_4 32767 +#define T_PRINTF_FORMAT "%hd" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_char.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_char.cpp new file mode 100644 index 00000000000..0ac555a5a18 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_char.cpp @@ -0,0 +1,9 @@ +#define T unsigned char +#define T_CSTR "unsigned char" +#define T_VALUE_1 '0' +#define T_VALUE_2 '9' +#define T_VALUE_3 '@' +#define T_VALUE_4 '$' +#define T_PRINTF_FORMAT "%c" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_int.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_int.cpp new file mode 100644 index 00000000000..1b307b04afc --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_int.cpp @@ -0,0 +1,9 @@ +#define T unsigned int +#define T_CSTR "unsigned int" +#define T_VALUE_1 11001110 +#define T_VALUE_2 22002220 +#define T_VALUE_3 33003330 +#define T_VALUE_4 44004440 +#define T_PRINTF_FORMAT "%u" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_long.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_long.cpp new file mode 100644 index 00000000000..0c442e399d5 --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_long.cpp @@ -0,0 +1,18 @@ +#define T unsigned long +#define T_CSTR "unsigned long" + +#ifdef __LP64__ +#define T_VALUE_1 110011101111 +#define T_VALUE_2 220022202222 +#define T_VALUE_3 330033303333 +#define T_VALUE_4 440044404444 +#else +#define T_VALUE_1 110011101 +#define T_VALUE_2 220022202 +#define T_VALUE_3 330033303 +#define T_VALUE_4 440044404 +#endif + +#define T_PRINTF_FORMAT "%lu" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_long_long.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_long_long.cpp new file mode 100644 index 00000000000..648aad01b3a --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_long_long.cpp @@ -0,0 +1,18 @@ +#define T unsigned long long +#define T_CSTR "unsigned long long" + +#ifdef __LP64__ +#define T_VALUE_1 110011101111 +#define T_VALUE_2 220022202222 +#define T_VALUE_3 330033303333 +#define T_VALUE_4 440044404444 +#else +#define T_VALUE_1 110011101 +#define T_VALUE_2 220022202 +#define T_VALUE_3 330033303 +#define T_VALUE_4 440044404 +#endif + +#define T_PRINTF_FORMAT "%llu" + +#include "basic_type.cpp" diff --git a/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_short.cpp b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_short.cpp new file mode 100644 index 00000000000..09af2aad62c --- /dev/null +++ b/gnu/llvm/lldb/packages/Python/lldbsuite/test/types/unsigned_short.cpp @@ -0,0 +1,9 @@ +#define T unsigned short +#define T_CSTR "unsigned short" +#define T_VALUE_1 11001 +#define T_VALUE_2 22002 +#define T_VALUE_3 0 +#define T_VALUE_4 65535 +#define T_PRINTF_FORMAT "%hu" + +#include "basic_type.cpp" |