mib updated this revision to Diff 408081.
mib retitled this revision from "[lldb/crashlog] Replace interactive mode by 
CrashLogScriptedProcess" to "[lldb/crashlog] Add CrashLogScriptedProcess to 
replace interactive mode".
mib edited the summary of this revision.
mib added a comment.
Herald added a subscriber: mgorny.

Merge D119389 <https://reviews.llvm.org/D119389> into this and address 
@JDevlieghere comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119501/new/

https://reviews.llvm.org/D119501

Files:
  lldb/bindings/python/CMakeLists.txt
  lldb/examples/python/crashlog.py
  lldb/examples/python/scripted_process/crashlog_scripted_process.py
  lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp

Index: lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
===================================================================
--- lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
+++ lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
@@ -303,6 +303,9 @@
 
   StructuredData::DictionarySP thread_info_sp = GetInterface().GetThreadsInfo();
 
+  // FIXME: Need to sort the dictionary otherwise the thread ids won't match the
+  // thread indices.
+
   if (!thread_info_sp)
     return ScriptedInterface::ErrorWithMessage<bool>(
         LLVM_PRETTY_FUNCTION,
Index: lldb/examples/python/scripted_process/crashlog_scripted_process.py
===================================================================
--- /dev/null
+++ lldb/examples/python/scripted_process/crashlog_scripted_process.py
@@ -0,0 +1,148 @@
+import os,json,struct,signal
+
+from typing import Any, Dict
+
+import lldb
+from lldb.plugins.scripted_process import ScriptedProcess
+from lldb.plugins.scripted_process import ScriptedThread
+
+from lldb.macosx.crashlog import CrashLog,CrashLogParser
+
+class CrashLogScriptedProcess(ScriptedProcess):
+    def parse_crashlog(self):
+        try:
+            crash_log = CrashLogParser().parse(self.dbg, self.crashlog_path, False)
+        except Exception as e:
+            return
+
+        self.pid = crash_log.process_id
+        self.crashed_thread_idx = crash_log.crashed_thread_idx
+        self.loaded_images = []
+
+        for thread in crash_log.threads:
+            if thread.did_crash():
+                for ident in thread.idents:
+                    images = crash_log.find_images_with_identifier(ident)
+                    if images:
+                        for image in images:
+                            #TODO: Add to self.loaded_images and load images in lldb
+                            err = image.add_module(self.target)
+                            if err:
+                                print(err)
+                            else:
+                                self.loaded_images.append(image)
+            self.threads[thread.index] = CrashLogScriptedThread(self, None, thread)
+
+    def __init__(self, target: lldb.SBTarget, args : lldb.SBStructuredData):
+        super().__init__(target, args)
+
+        if not self.target or not self.target.IsValid():
+            return
+
+        self.crashlog_path = None
+
+        crashlog_path = args.GetValueForKey("crashlog_path")
+        if crashlog_path and crashlog_path.IsValid():
+            if crashlog_path.GetType() == lldb.eStructuredDataTypeString:
+                self.crashlog_path = crashlog_path.GetStringValue(100)
+
+        if not self.crashlog_path:
+            return
+
+        self.pid = super().get_process_id()
+        self.crashed_thread_idx = 0
+        self.parse_crashlog()
+
+    def get_memory_region_containing_address(self, addr: int) -> lldb.SBMemoryRegionInfo:
+        return None
+
+    def get_thread_with_id(self, tid: int):
+        return {}
+
+    def get_registers_for_thread(self, tid: int):
+        return {}
+
+    def read_memory_at_address(self, addr: int, size: int) -> lldb.SBData:
+        # NOTE: CrashLogs don't contain any memory.
+        return lldb.SBData()
+
+    def get_loaded_images(self):
+        # TODO: Iterate over corefile_target modules and build a data structure
+        # from it.
+        return self.loaded_images
+
+    def get_process_id(self) -> int:
+        return self.pid
+
+    def should_stop(self) -> bool:
+        return True
+
+    def is_alive(self) -> bool:
+        return True
+
+    def get_scripted_thread_plugin(self):
+        return CrashLogScriptedThread.__module__ + "." + CrashLogScriptedThread.__name__
+
+class CrashLogScriptedThread(ScriptedThread):
+    def create_register_ctx(self):
+        if not self.has_crashed:
+            return dict.fromkeys([*map(lambda reg: reg['name'], self.register_info['registers'])] , 0)
+
+        if not self.backing_thread or not len(self.backing_thread.registers):
+            return dict.fromkeys([*map(lambda reg: reg['name'], self.register_info['registers'])] , 0)
+
+        for reg in self.register_info['registers']:
+            reg_name = reg['name']
+            if reg_name in self.backing_thread.registers:
+                self.register_ctx[reg_name] = self.backing_thread.registers[reg_name]
+            else:
+                self.register_ctx[reg_name] = 0
+
+        return self.register_ctx
+
+    def create_stackframes(self):
+        if not self.has_crashed:
+            return None
+
+        if not self.backing_thread or not len(self.backing_thread.frames):
+            return None
+
+        for frame in self.backing_thread.frames:
+            sym_addr = lldb.SBAddress()
+            sym_addr.SetLoadAddress(frame.pc, self.target)
+            if not sym_addr.IsValid():
+                continue
+            self.frames.append({"idx": frame.index, "pc": frame.pc})
+
+        return self.frames
+
+    def __init__(self, process, args, crashlog_thread):
+        super().__init__(process, args)
+
+        self.backing_thread = crashlog_thread
+        self.idx = self.backing_thread.index
+        self.has_crashed = (self.scripted_process.crashed_thread_idx == self.idx)
+        self.create_stackframes()
+
+    def get_thread_id(self) -> int:
+        return self.idx
+
+    def get_name(self) -> str:
+        return CrashLogScriptedThread.__name__ + ".thread-" + str(self.idx)
+
+    def get_state(self):
+        if not self.has_crashed:
+            return lldb.eStateStopped
+        return lldb.eStateCrashed
+
+    def get_stop_reason(self) -> Dict[str, Any]:
+        if not self.has_crashed:
+            return { "type": lldb.eStopReasonNone, "data": {  }}
+        # TODO: Investigate what stop reason should be reported when crashed
+        return { "type": lldb.eStopReasonException, "data": { "desc": "EXC_BAD_ACCESS" }}
+
+    def get_register_context(self) -> str:
+        if not self.register_ctx:
+            self.register_ctx = self.create_register_ctx()
+
+        return struct.pack("{}Q".format(len(self.register_ctx)), *self.register_ctx.values())
Index: lldb/examples/python/crashlog.py
===================================================================
--- lldb/examples/python/crashlog.py
+++ lldb/examples/python/crashlog.py
@@ -65,7 +65,6 @@
 
 from lldb.utils import symbolication
 
-
 def read_plist(s):
     if sys.version_info.major == 3:
         return plistlib.loads(s)
@@ -770,138 +769,6 @@
     sys.exit(0)
 
 
-class Interactive(cmd.Cmd):
-    '''Interactive prompt for analyzing one or more Darwin crash logs, type "help" to see a list of supported commands.'''
-    image_option_parser = None
-
-    def __init__(self, crash_logs):
-        cmd.Cmd.__init__(self)
-        self.use_rawinput = False
-        self.intro = 'Interactive crashlogs prompt, type "help" to see a list of supported commands.'
-        self.crash_logs = crash_logs
-        self.prompt = '% '
-
-    def default(self, line):
-        '''Catch all for unknown command, which will exit the interpreter.'''
-        print("uknown command: %s" % line)
-        return True
-
-    def do_q(self, line):
-        '''Quit command'''
-        return True
-
-    def do_quit(self, line):
-        '''Quit command'''
-        return True
-
-    def do_symbolicate(self, line):
-        description = '''Symbolicate one or more darwin crash log files by index to provide source file and line information,
-        inlined stack frames back to the concrete functions, and disassemble the location of the crash
-        for the first frame of the crashed thread.'''
-        option_parser = CreateSymbolicateCrashLogOptions(
-            'symbolicate', description, False)
-        command_args = shlex.split(line)
-        try:
-            (options, args) = option_parser.parse_args(command_args)
-        except:
-            return
-
-        if args:
-            # We have arguments, they must valid be crash log file indexes
-            for idx_str in args:
-                idx = int(idx_str)
-                if idx < len(self.crash_logs):
-                    SymbolicateCrashLog(self.crash_logs[idx], options)
-                else:
-                    print('error: crash log index %u is out of range' % (idx))
-        else:
-            # No arguments, symbolicate all crash logs using the options
-            # provided
-            for idx in range(len(self.crash_logs)):
-                SymbolicateCrashLog(self.crash_logs[idx], options)
-
-    def do_list(self, line=None):
-        '''Dump a list of all crash logs that are currently loaded.
-
-        USAGE: list'''
-        print('%u crash logs are loaded:' % len(self.crash_logs))
-        for (crash_log_idx, crash_log) in enumerate(self.crash_logs):
-            print('[%u] = %s' % (crash_log_idx, crash_log.path))
-
-    def do_image(self, line):
-        '''Dump information about one or more binary images in the crash log given an image basename, or all images if no arguments are provided.'''
-        usage = "usage: %prog [options] <PATH> [PATH ...]"
-        description = '''Dump information about one or more images in all crash logs. The <PATH> can be a full path, image basename, or partial path. Searches are done in this order.'''
-        command_args = shlex.split(line)
-        if not self.image_option_parser:
-            self.image_option_parser = optparse.OptionParser(
-                description=description, prog='image', usage=usage)
-            self.image_option_parser.add_option(
-                '-a',
-                '--all',
-                action='store_true',
-                help='show all images',
-                default=False)
-        try:
-            (options, args) = self.image_option_parser.parse_args(command_args)
-        except:
-            return
-
-        if args:
-            for image_path in args:
-                fullpath_search = image_path[0] == '/'
-                for (crash_log_idx, crash_log) in enumerate(self.crash_logs):
-                    matches_found = 0
-                    for (image_idx, image) in enumerate(crash_log.images):
-                        if fullpath_search:
-                            if image.get_resolved_path() == image_path:
-                                matches_found += 1
-                                print('[%u] ' % (crash_log_idx), image)
-                        else:
-                            image_basename = image.get_resolved_path_basename()
-                            if image_basename == image_path:
-                                matches_found += 1
-                                print('[%u] ' % (crash_log_idx), image)
-                    if matches_found == 0:
-                        for (image_idx, image) in enumerate(crash_log.images):
-                            resolved_image_path = image.get_resolved_path()
-                            if resolved_image_path and string.find(
-                                    image.get_resolved_path(), image_path) >= 0:
-                                print('[%u] ' % (crash_log_idx), image)
-        else:
-            for crash_log in self.crash_logs:
-                for (image_idx, image) in enumerate(crash_log.images):
-                    print('[%u] %s' % (image_idx, image))
-        return False
-
-
-def interactive_crashlogs(debugger, options, args):
-    crash_log_files = list()
-    for arg in args:
-        for resolved_path in glob.glob(arg):
-            crash_log_files.append(resolved_path)
-
-    crash_logs = list()
-    for crash_log_file in crash_log_files:
-        try:
-            crash_log = CrashLogParser().parse(debugger, crash_log_file, options.verbose)
-        except Exception as e:
-            print(e)
-            continue
-        if options.debug:
-            crash_log.dump()
-        if not crash_log.images:
-            print('error: no images in crash log "%s"' % (crash_log))
-            continue
-        else:
-            crash_logs.append(crash_log)
-
-    interpreter = Interactive(crash_logs)
-    # List all crash logs that were imported
-    interpreter.do_list()
-    interpreter.cmdloop()
-
-
 def save_crashlog(debugger, command, exe_ctx, result, dict):
     usage = "usage: %prog [options] <output-path>"
     description = '''Export the state of current target into a crashlog file'''
@@ -1096,6 +963,43 @@
         for error in crash_log.errors:
             print(error)
 
+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
+
+    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)
 
 def CreateSymbolicateCrashLogOptions(
         command_name,
@@ -1199,8 +1103,14 @@
             '-i',
             '--interactive',
             action='store_true',
-            help='parse all crash logs and enter interactive mode',
+            help='parse a crash log and load it in a ScriptedProcess',
             default=False)
+        option_parser.add_option(
+            '-b',
+            '--batch',
+            action='store_true',
+            help='dump symbolicated stackframes without creating a debug session',
+            default=True)
     return option_parser
 
 
@@ -1233,10 +1143,16 @@
     error = lldb.SBError()
 
     if args:
-        if options.interactive:
-            interactive_crashlogs(debugger, options, args)
-        else:
-            for crash_log_file in args:
+        for crash_log_file in args:
+            ci = debugger.GetCommandInterpreter()
+            if options.interactive:
+                load_crashlog_in_scripted_process(debugger, crash_log_file)
+            elif options.batch:
+                crash_log = CrashLogParser().parse(debugger, crash_log_file, options.verbose)
+                SymbolicateCrashLog(crash_log, options)
+            elif ci and ci.IsInteractive():
+                load_crashlog_in_scripted_process(debugger, crash_log_file)
+            else:
                 crash_log = CrashLogParser().parse(debugger, crash_log_file, options.verbose)
                 SymbolicateCrashLog(crash_log, options)
 
Index: lldb/bindings/python/CMakeLists.txt
===================================================================
--- lldb/bindings/python/CMakeLists.txt
+++ lldb/bindings/python/CMakeLists.txt
@@ -114,6 +114,7 @@
       ${swig_target}
       ${lldb_python_target_dir} "macosx"
       FILES "${LLDB_SOURCE_DIR}/examples/python/crashlog.py"
+            "${LLDB_SOURCE_DIR}/examples/python/scripted_process/crashlog_scripted_process.py"
             "${LLDB_SOURCE_DIR}/examples/darwin/heap_find/heap.py")
 
     create_python_package(
_______________________________________________
lldb-commits mailing list
lldb-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits
  • [Lldb-commits] [PATCH]... Med Ismail Bennani via Phabricator via lldb-commits

Reply via email to