Ejemplo n.º 1
0
    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
Ejemplo n.º 2
0
    def test_invalid_scripted_register_context(self):
        """Test that we can launch an lldb scripted process with an invalid
        Scripted Thread, with invalid register context."""
        self.build()

        os.environ['SKIP_SCRIPTED_PROCESS_LAUNCH'] = '1'
        def cleanup():
          del os.environ["SKIP_SCRIPTED_PROCESS_LAUNCH"]
        self.addTearDownHook(cleanup)

        self.runCmd("settings set target.load-script-from-symbol-file true")
        self.move_blueprint_to_dsym('invalid_scripted_process.py')
        target = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
        self.assertTrue(target, VALID_TARGET)
        log_file = self.getBuildArtifact('thread.log')
        self.runCmd("log enable lldb thread -f " + log_file)
        self.assertTrue(os.path.isfile(log_file))

        launch_info = lldb.SBLaunchInfo(None)
        launch_info.SetProcessPluginName("ScriptedProcess")
        launch_info.SetScriptedProcessClassName("a_out.InvalidScriptedProcess")
        error = lldb.SBError()

        process = target.Launch(launch_info, error)

        self.assertSuccess(error)
        self.assertTrue(process, PROCESS_IS_VALID)
        self.assertEqual(process.GetProcessID(), 666)
        self.assertEqual(process.GetNumThreads(), 0)

        with open(log_file, 'r') as f:
            log = f.read()

        self.assertIn("Failed to get scripted thread registers data.", log)
    def get_to_bkpt(self, bkpt_pattern):
        exe = os.path.join(os.getcwd(), "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
        # bkpt_pattern
        breakpoint = target.BreakpointCreateBySourceRegex(
            bkpt_pattern, lldb.SBFileSpec("main.swift"))
        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)

        self.frame = threads[0].GetFrameAtIndex(0)
Ejemplo n.º 4
0
def run_command(debugger, command, result, internal_dict):
    device_app = internal_dict['fruitstrap_device_app']
    args = command.split('--', 1)
    lldb.target.modules[0].SetPlatformFileSpec(lldb.SBFileSpec(device_app))
    args_arr = []
    if len(args) > 1:
        args_arr = shlex.split(args[1])
    # EPIC: Specify not to use posix to maintain quotes, newlines, etc in passed arguments
    args_arr = args_arr + shlex.split('{args}', posix=False)

    launchInfo = lldb.SBLaunchInfo(args_arr)
    global listener
    launchInfo.SetListener(listener)

    #This env variable makes NSLog, CFLog and os_log messages get mirrored to stderr
    #https://stackoverflow.com/a/39581193
    launchInfo.SetEnvironmentEntries(['OS_ACTIVITY_DT_MODE=enable'], True)

    envs_arr = []
    if len(args) > 1:
        envs_arr = shlex.split(args[1])
    envs_arr = envs_arr + shlex.split('{envs}')
    launchInfo.SetEnvironmentEntries(envs_arr, True)

    lldb.target.Launch(launchInfo, startup_error)
    lockedstr = ': Locked'
    if lockedstr in str(startup_error):
        print('\\nDevice Locked\\n')
        os._exit(254)
    else:
        print(str(startup_error))
Ejemplo n.º 5
0
    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())
        launch_info.SetLaunchFlags(lldb.eLaunchFlagInheritTCCFromParent)

        (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)
    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)))
Ejemplo n.º 7
0
  def doLaunch(self, stop_at_entry, args):
    """ Handle process launch.  """
    error = lldb.SBError()

    fs = self.target.GetExecutable()
    exe = os.path.join(fs.GetDirectory(), fs.GetFilename())
    if self.process is not None and self.process.IsValid():
      pid = self.process.GetProcessID()
      state = state_type_to_str(self.process.GetState())
      self.process.Destroy()

    launchInfo = lldb.SBLaunchInfo(args.split(' '))
    self.process = self.target.Launch(launchInfo, error)
    if not error.Success():
      sys.stderr.write("Error during launch: " + str(error))
      return

    # launch succeeded, store pid and add some event listeners
    self.pid = self.process.GetProcessID()
    self.processListener = lldb.SBListener("process_event_listener")
    self.process.GetBroadcaster().AddListener(self.processListener, lldb.SBProcess.eBroadcastBitStateChanged)

    print "Launched %s %s (pid=%d)" % (exe, args, self.pid)

    if not stop_at_entry:
      self.doContinue()
    else:
      self.processPendingEvents(self.eventDelayLaunch)
Ejemplo n.º 8
0
def run_to_breakpoint_do_run(test,
                             target,
                             bkpt,
                             launch_info=None,
                             only_one_thread=True):

    # Launch the process, and do not stop at the entry point.
    if not launch_info:
        launch_info = lldb.SBLaunchInfo(None)
        launch_info.SetWorkingDirectory(test.get_process_working_directory())

    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()))

    # 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)
Ejemplo n.º 9
0
    def run(self, debugger, command):
        lldb.target.modules[0].SetPlatformFileSpec(
            lldb.SBFileSpec(self.device_app))
        args = command.split('--', 1)
        error = lldb.SBError()
        args_arr = []
        if len(args) > 1:
            args_arr = shlex.split(args[1], posix=False)
        args_arr = args_arr + shlex.split(self.args, posix=False)

        launchInfo = lldb.SBLaunchInfo(args_arr)
        launchInfo.SetListener(self.listener)
        if self.helper_script:
            launchInfo.SetLaunchFlags(lldb.eLaunchFlagStopAtEntry
                                      | lldb.eLaunchFlagDisableASLR)

        # This env variable makes NSLog, CFLog and os_log messages get mirrored to stderr
        # https://stackoverflow.com/a/39581193
        launchInfo.SetEnvironmentEntries(['OS_ACTIVITY_DT_MODE=enable'], True)

        lldb.target.Launch(launchInfo, error)
        lockedstr = ': Locked'
        if lockedstr in str(error):
            print('\\nDevice Locked\\n')
            sys.exit(254)
        else:
            print("Start Status:", str(error))
        # it seems status not sync-ed without this sleep
        time.sleep(0.3)
Ejemplo n.º 10
0
def run_command(debugger, command, result, internal_dict):
    device_app = internal_dict['fruitstrap_device_app']
    args = command.split('--',1)
    error = lldb.SBError()
    lldb.target.modules[0].SetPlatformFileSpec(lldb.SBFileSpec(device_app))
    args_arr = []
    if len(args) > 1:
        args_arr = shlex.split(args[1])
    args_arr = args_arr + shlex.split('{args}')

    launchInfo = lldb.SBLaunchInfo(args_arr)
    global listener
    launchInfo.SetListener(listener)
    
    #This env variable makes NSLog, CFLog and os_log messages get mirrored to stderr
    #https://stackoverflow.com/a/39581193 
    launchInfo.SetEnvironmentEntries(['OS_ACTIVITY_DT_MODE=enable'], True)
    
    lldb.target.Launch(launchInfo, error)
    lockedstr = ': Locked'
    if lockedstr in str(error):
       print('\\nDevice Locked\\n')
       os._exit(254)
    else:
       print(str(error))
Ejemplo n.º 11
0
    def test_launch_scripted_process_sbapi(self):
        """Test that we can launch an lldb scripted process using the SBAPI,
        check its process ID and read string from memory."""
        self.build()
        target = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
        self.assertTrue(target, VALID_TARGET)

        scripted_process_example_relpath = [
            '..', '..', '..', '..', 'examples', 'python', 'scripted_process',
            'my_scripted_process.py'
        ]
        os.environ['SKIP_SCRIPTED_PROCESS_LAUNCH'] = '1'
        self.runCmd("command script import " + os.path.join(
            self.getSourceDir(), *scripted_process_example_relpath))

        launch_info = lldb.SBLaunchInfo(None)
        launch_info.SetProcessPluginName("ScriptedProcess")
        launch_info.SetScriptedProcessClassName(
            "my_scripted_process.MyScriptedProcess")

        error = lldb.SBError()
        process = target.Launch(launch_info, error)
        self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID)
        self.assertEqual(process.GetProcessID(), 42)

        hello_world = "Hello, world!"
        memory_read = process.ReadCStringFromMemory(
            0x50000000000,
            len(hello_world) + 1,  # NULL byte
            error)

        self.assertTrue(error.Success(),
                        "Failed to read memory from scripted process.")
        self.assertEqual(hello_world, memory_read)
    def test_invalid_scripted_register_context(self):
        """Test that we can launch an lldb scripted process with an invalid
        Scripted Thread, with invalid register context."""
        self.build()
        target = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
        self.assertTrue(target, VALID_TARGET)
        log_file = self.getBuildArtifact('thread.log')
        self.runCmd("log enable lldb thread -f " + log_file)
        self.assertTrue(os.path.isfile(log_file))

        os.environ['SKIP_SCRIPTED_PROCESS_LAUNCH'] = '1'
        def cleanup():
          del os.environ["SKIP_SCRIPTED_PROCESS_LAUNCH"]
        self.addTearDownHook(cleanup)

        scripted_process_example_relpath = 'invalid_scripted_process.py'
        self.runCmd("command script import " + os.path.join(self.getSourceDir(),
                                                            scripted_process_example_relpath))

        launch_info = lldb.SBLaunchInfo(None)
        launch_info.SetProcessPluginName("ScriptedProcess")
        launch_info.SetScriptedProcessClassName("invalid_scripted_process.InvalidScriptedProcess")
        error = lldb.SBError()

        process = target.Launch(launch_info, error)

        self.assertTrue(error.Success(), error.GetCString())
        self.assertTrue(process, PROCESS_IS_VALID)
        self.assertEqual(process.GetProcessID(), 666)
        self.assertEqual(process.GetNumThreads(), 0)

        with open(log_file, 'r') as f:
            log = f.read()

        self.assertIn("Failed to get scripted thread registers data.", log)
Ejemplo n.º 13
0
    def test_scripted_process_and_scripted_thread(self):
        """Test that we can launch an lldb scripted process using the SBAPI,
        check its process ID, read string from memory, check scripted thread
        id, name stop reason and register context.
        """
        self.build()
        target = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
        self.assertTrue(target, VALID_TARGET)

        os.environ['SKIP_SCRIPTED_PROCESS_LAUNCH'] = '1'

        def cleanup():
            del os.environ["SKIP_SCRIPTED_PROCESS_LAUNCH"]

        self.addTearDownHook(cleanup)

        scripted_process_example_relpath = 'dummy_scripted_process.py'
        self.runCmd("command script import " + os.path.join(
            self.getSourceDir(), scripted_process_example_relpath))

        launch_info = lldb.SBLaunchInfo(None)
        launch_info.SetProcessPluginName("ScriptedProcess")
        launch_info.SetScriptedProcessClassName(
            "dummy_scripted_process.DummyScriptedProcess")

        error = lldb.SBError()
        process = target.Launch(launch_info, error)
        self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID)
        self.assertEqual(process.GetProcessID(), 42)

        self.assertEqual(process.GetNumThreads(), 1)

        thread = process.GetSelectedThread()
        self.assertTrue(thread, "Invalid thread.")
        self.assertEqual(thread.GetThreadID(), 0x19)
        self.assertEqual(thread.GetName(), "DummyScriptedThread.thread-1")
        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonSignal)

        self.assertGreater(thread.GetNumFrames(), 0)

        frame = thread.GetFrameAtIndex(0)
        GPRs = None
        register_set = frame.registers  # Returns an SBValueList.
        for regs in register_set:
            if 'general purpose' in regs.name.lower():
                GPRs = regs
                break

        self.assertTrue(GPRs, "Invalid General Purpose Registers Set")
        self.assertGreater(GPRs.GetNumChildren(), 0)
        for idx, reg in enumerate(GPRs, start=1):
            if idx > 21:
                break
            self.assertEqual(idx, int(reg.value, 16))

        self.assertTrue(frame.IsArtificial(), "Frame is not artificial")
        pc = frame.GetPCAddress().GetLoadAddress(target)
        self.assertEqual(pc, 0x0100001b00)
Ejemplo n.º 14
0
    def test_launch_scripted_process_stack_frames(self):
        """Test that we can launch an lldb scripted process from the command
        line, check its process ID and read string from memory."""
        self.build()
        target = self.dbg.CreateTarget(self.getBuildArtifact("a.out"))
        self.assertTrue(target, VALID_TARGET)

        for module in target.modules:
            if 'a.out' in module.GetFileSpec().GetFilename():
                main_module = module
                break

        self.assertTrue(main_module, "Invalid main module.")
        error = target.SetModuleLoadAddress(main_module, 0)
        self.assertTrue(error.Success(), "Reloading main module at offset 0 failed.")

        os.environ['SKIP_SCRIPTED_PROCESS_LAUNCH'] = '1'
        def cleanup():
          del os.environ["SKIP_SCRIPTED_PROCESS_LAUNCH"]
        self.addTearDownHook(cleanup)

        scripted_process_example_relpath = 'stack_core_scripted_process.py'
        self.runCmd("command script import " + os.path.join(self.getSourceDir(),
                                                            scripted_process_example_relpath))

        corefile_process = None
        with tempfile.NamedTemporaryFile() as file:
            self.create_stack_skinny_corefile(file.name)
            corefile_target = self.dbg.CreateTarget(None)
            corefile_process = corefile_target.LoadCore(self.getBuildArtifact(file.name))
        self.assertTrue(corefile_process, PROCESS_IS_VALID)

        structured_data = lldb.SBStructuredData()
        structured_data.SetFromJSON(json.dumps({
            "backing_target_idx" : self.dbg.GetIndexOfTarget(corefile_process.GetTarget())
        }))
        launch_info = lldb.SBLaunchInfo(None)
        launch_info.SetProcessPluginName("ScriptedProcess")
        launch_info.SetScriptedProcessClassName("stack_core_scripted_process.StackCoreScriptedProcess")
        launch_info.SetScriptedProcessDictionary(structured_data)

        error = lldb.SBError()
        process = target.Launch(launch_info, error)
        self.assertTrue(error.Success(), error.GetCString())
        self.assertTrue(process, PROCESS_IS_VALID)
        self.assertEqual(process.GetProcessID(), 42)

        self.assertEqual(process.GetNumThreads(), 1)
        thread = process.GetSelectedThread()
        self.assertTrue(thread, "Invalid thread.")
        self.assertEqual(thread.GetName(), "StackCoreScriptedThread.thread-1")

        self.assertEqual(thread.GetNumFrames(), 3)
        frame = thread.GetSelectedFrame()
        self.assertTrue(frame, "Invalid frame.")
        self.assertEqual(frame.GetFunctionName(), "bar")
        self.assertEqual(int(frame.FindValue("i", lldb.eValueTypeVariableArgument).GetValue()), 42)
        self.assertEqual(int(frame.FindValue("j", lldb.eValueTypeVariableLocal).GetValue()), 42 * 42)
Ejemplo n.º 15
0
def run_to_source_breakpoint(test,
                             bkpt_pattern,
                             source_spec,
                             launch_info=None,
                             exe_name="a.out",
                             in_cwd=True):
    """Start up a target, using exe_name as the executable, and run it to
       a breakpoint set by source regex bkpt_pattern.

       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 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.
    """

    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 the breakpoints
    breakpoint = target.BreakpointCreateBySourceRegex(bkpt_pattern,
                                                      source_spec)
    test.assertTrue(
        breakpoint.GetNumLocations() > 0,
        'No locations found for source breakpoint: "%s"' % (bkpt_pattern))

    # Launch the process, and do not stop at the entry point.
    if not launch_info:
        launch_info = lldb.SBLaunchInfo(None)
        launch_info.SetWorkingDirectory(test.get_process_working_directory())

    error = lldb.SBError()
    process = target.Launch(launch_info, error)

    test.assertTrue(
        process, "Could not create a valid process for %s: %s" %
        (exe_name, error.GetCString()))

    # Frame #0 should be at our breakpoint.
    threads = get_threads_stopped_at_breakpoint(process, breakpoint)

    test.assertTrue(
        len(threads) == 1,
        "Expected 1 thread to stop at breakpoint, %d did." % (len(threads)))
    thread = threads[0]
    return (target, process, thread, breakpoint)
Ejemplo n.º 16
0
    def test_bad_emulator_path(self):
        self.set_emulator_setting("emulator-path",
                                  self.getBuildArtifact("nonexistent.file"))

        target = self._create_target()
        info = lldb.SBLaunchInfo([])
        error = lldb.SBError()
        target.Launch(info, error)
        self.assertTrue(error.Fail())
        self.assertIn("doesn't exist", error.GetCString())
Ejemplo n.º 17
0
 def test_launch_in_terminal (self):
     exe = "/bin/ls"
     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)
     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)
Ejemplo n.º 18
0
    def test(self):
        self.build()

        # Extracts path of the interpreter.
        spec = lldb.SBModuleSpec()
        spec.SetFileSpec(lldb.SBFileSpec(self.getBuildArtifact("a.out")))
        interp_section = lldb.SBModule(spec).FindSection(".interp")
        if not interp_section:
            return
        section_data = interp_section.GetSectionData()
        error = lldb.SBError()
        exe = section_data.GetString(error, 0)
        if error.Fail():
            return

        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        # Set breakpoints both on shared library function as well as on
        # main. Both of them will be pending breakpoints.
        breakpoint_main = target.BreakpointCreateBySourceRegex(
            "// Break here", lldb.SBFileSpec("main.cpp"))
        breakpoint_shared_library = target.BreakpointCreateBySourceRegex(
            "get_signal_crash", lldb.SBFileSpec("signal_file.cpp"))
        launch_info = lldb.SBLaunchInfo([
            "--library-path",
            self.get_process_working_directory(),
            self.getBuildArtifact("a.out")
        ])
        launch_info.SetWorkingDirectory(self.get_process_working_directory())
        error = lldb.SBError()
        process = target.Launch(launch_info, error)
        self.assertTrue(error.Success())

        # Stopped on main here.
        self.assertEqual(process.GetState(), lldb.eStateStopped)
        thread = process.GetSelectedThread()
        self.assertIn("main",
                      thread.GetFrameAtIndex(0).GetDisplayFunctionName())
        process.Continue()

        # Stopped on get_signal_crash function here.
        self.assertEqual(process.GetState(), lldb.eStateStopped)
        self.assertIn("get_signal_crash",
                      thread.GetFrameAtIndex(0).GetDisplayFunctionName())
        process.Continue()

        # Stopped because of generated signal.
        self.assertEqual(process.GetState(), lldb.eStateStopped)
        self.assertIn("raise",
                      thread.GetFrameAtIndex(0).GetDisplayFunctionName())
        self.assertIn("get_signal_crash",
                      thread.GetFrameAtIndex(1).GetDisplayFunctionName())
    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 address_breakpoints(self):
        """Test that breakpoints set on a bad address say they are bad."""
        exe = os.path.join(os.getcwd(), "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)

        launch_info = lldb.SBLaunchInfo(None)

        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)

        # 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.Clear()

        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.")
Ejemplo n.º 21
0
def run_command(debugger, command, result, internal_dict):
    device_app = internal_dict['fruitstrap_device_app']
    args = command.split('--', 1)
    error = lldb.SBError()
    lldb.target.modules[0].SetPlatformFileSpec(lldb.SBFileSpec(device_app))
    lldb.target.Launch(
        lldb.SBLaunchInfo(shlex.split(args[1] and args[1] or '{args}')), error)
    lockedstr = ': Locked'
    if lockedstr in str(error):
        print('\\nDevice Locked\\n')
        os._exit(254)
    else:
        print(str(error))
Ejemplo n.º 22
0
    def launch_info(self):
        info = lldb.SBLaunchInfo([])

        if self.getPlatform() == "freebsd" or self.getPlatform() == "linux":
            # LD_LIBRARY_PATH must be set so the shared libraries are found on
            # startup
            library_path = os.environ.get("LD_LIBRARY_PATH", "")
            if library_path:
                library_path += ":"
            library_path += self.getBuildDir()

            info.SetEnvironmentEntries(["LD_LIBRARY_PATH=" + library_path], True)

        return info
Ejemplo n.º 23
0
    def test_debugger_internal_variables(self):
        """Ensure that SBDebugger reachs the same instance of properties
           regardless CommandInterpreter's context initialization"""
        self.build()
        exe = self.getBuildArtifact("a.out")

        # Create a target by the debugger.
        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        property_name = "target.process.memory-cache-line-size"

        def get_cache_line_size():
            value_list = lldb.SBStringList()
            value_list = self.dbg.GetInternalVariableValue(property_name,
                                                           self.dbg.GetInstanceName())

            self.assertEqual(value_list.GetSize(), 1)
            try:
                return int(value_list.GetStringAtIndex(0))
            except ValueError as error:
                self.fail("Value is not a number: " + error)

        # Get global property value while there are no processes.
        global_cache_line_size = get_cache_line_size()

        # Run a process via SB interface. CommandInterpreter's execution context
        # remains empty.
        error = lldb.SBError()
        launch_info = lldb.SBLaunchInfo(None)
        launch_info.SetLaunchFlags(lldb.eLaunchFlagStopAtEntry)
        process = target.Launch(launch_info, error)
        self.assertTrue(process, PROCESS_IS_VALID)

        # This should change the value of a process's local property.
        new_cache_line_size = global_cache_line_size + 512
        error = self.dbg.SetInternalVariable(property_name,
                                             str(new_cache_line_size),
                                             self.dbg.GetInstanceName())
        self.assertTrue(error.Success(),
                        property_name + " value was changed successfully")

        # Check that it was set actually.
        self.assertEqual(get_cache_line_size(), new_cache_line_size)

        # Run any command to initialize CommandInterpreter's execution context.
        self.runCmd("target list")

        # Test the local property again, is it set to new_cache_line_size?
        self.assertEqual(get_cache_line_size(), new_cache_line_size)
Ejemplo n.º 24
0
    def test_with_python_api(self):
        """Test that we get thread names when interrupting a process."""
        self.build()
        exe = os.path.join(os.getcwd(), "a.out")

        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        launch_info = lldb.SBLaunchInfo(None)
        error = lldb.SBError()
        lldb.debugger.SetAsync(True)
        process = target.Launch(launch_info, error)
        self.assertTrue(process, PROCESS_IS_VALID)

        listener = lldb.debugger.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()
Ejemplo n.º 25
0
def run_command(debugger, command, result, internal_dict):
    args = command.split('--', 1)
    args_arr = []
    if len(args) > 1:
        args_arr = shlex.split(args[1])
    else:
        args_arr = shlex.split('')
    error = lldb.SBError()
    lldb.target.Launch(lldb.SBLaunchInfo(args_arr), error)
    lockedstr = ': Locked'
    if lockedstr in str(error):
        print('\nDevice Locked\n')
        os._exit(254)
    else:
        print(str(error))
Ejemplo n.º 26
0
    def test_launch_in_terminal(self):
        self.build()
        exe = os.path.join(os.getcwd(), "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)
Ejemplo n.º 27
0
    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)
Ejemplo n.º 28
0
    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)
Ejemplo n.º 29
0
    def _test(self):
        self.build()

        # Extracts path of the interpreter.
        exe = self.getBuildArtifact("a.out")

        spec = lldb.SBModuleSpec()
        spec.SetFileSpec(lldb.SBFileSpec(exe))
        interp_section = lldb.SBModule(spec).FindSection(".interp")
        if not interp_section:
            return
        section_data = interp_section.GetSectionData()
        error = lldb.SBError()
        dyld_path = section_data.GetString(error, 0)
        if error.Fail():
            return

        target = self.dbg.CreateTarget(exe)
        self.assertTrue(target, VALID_TARGET)

        # Set a breakpoint in the main function that will get hit after the
        # program exec's via the dynamic loader. The breakpoint will only get
        # hit if we can successfully read the shared library lists in the
        # DynamicLoaderPOSIXDYLD.cpp when we exec into the dynamic loader.
        breakpoint_main = target.BreakpointCreateBySourceRegex(
            "// Break here", lldb.SBFileSpec("main.cpp"))
        # Setup our launch info to supply the dynamic loader path to the
        # program so it gets two args:
        # - path to a.out
        # - path to dynamic loader
        launch_info = lldb.SBLaunchInfo([dyld_path])
        error = lldb.SBError()
        process = target.Launch(launch_info, error)
        self.assertSuccess(error)

        threads = lldbutil.get_stopped_threads(process, lldb.eStopReasonExec)
        self.assertEqual(len(threads), 1, "We got a thread stopped for exec.")

        process.Continue()

        # Stopped on main here.
        self.assertState(process.GetState(), lldb.eStateStopped)
        thread = process.GetSelectedThread()
        self.assertIn("main",
                      thread.GetFrameAtIndex(0).GetDisplayFunctionName())
Ejemplo n.º 30
0
def load_crashlog_in_scripted_process(debugger, crash_log_file):
    result = lldb.SBCommandReturnObject()

    crashlog_path = os.path.expanduser(crash_log_file)
    if not os.path.exists(crashlog_path):
        result.PutCString("error: crashlog file %s does not exist" %
                          crashlog_path)

    try:
        crashlog = CrashLogParser().parse(debugger, crashlog_path, False)
    except Exception as e:
        result.PutCString("error: python exception: %s" % e)
        return

    if debugger.GetNumTargets() > 0:
        target = debugger.GetTargetAtIndex(0)
    else:
        target = crashlog.create_target()
    if not target:
        result.PutCString("error: couldn't create target")
        return

    ci = debugger.GetCommandInterpreter()
    if not ci:
        result.PutCString("error: couldn't get command interpreter")
        return

    res = lldb.SBCommandReturnObject()
    ci.HandleCommand(
        'script from lldb.macosx import crashlog_scripted_process', res)
    if not res.Succeeded():
        result.PutCString(
            "error: couldn't import crashlog scripted process module")
        return

    structured_data = lldb.SBStructuredData()
    structured_data.SetFromJSON(json.dumps({"crashlog_path": crashlog_path}))
    launch_info = lldb.SBLaunchInfo(None)
    launch_info.SetProcessPluginName("ScriptedProcess")
    launch_info.SetScriptedProcessClassName(
        "crashlog_scripted_process.CrashLogScriptedProcess")
    launch_info.SetScriptedProcessDictionary(structured_data)
    error = lldb.SBError()
    process = target.Launch(launch_info, error)