diff options
Diffstat (limited to 'gnu/llvm/lldb/packages/Python/lldbsuite/test/python_api/process')
9 files changed, 769 insertions, 0 deletions
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 +} |