Tarantool development patches archive
 help / color / mirror / Atom feed
From: Mikhail Elhimov via Tarantool-patches <tarantool-patches@dev.tarantool.org>
To: Sergey Kaplun <skaplun@tarantool.org>,
	Sergey Bronnikov <sergeyb@tarantool.org>,
	Evgeniy Temirgaleev <e.temirgaleev@tarantool.org>
Cc: tarantool-patches@dev.tarantool.org
Subject: [Tarantool-patches] [PATCH luajit v2 3/7] dbg: handle missing cmd arg in a dbg-agnostic way
Date: Fri,  4 Dec 2026 23:03:04 +0300	[thread overview]
Message-ID: <10189fbca6be567d54795a24179fe8105ede822a.1796410322.git.m.elhimov@vk.team> (raw)
In-Reply-To: <cover.1796410322.git.m.elhimov@vk.team>

* unified handling of command-level error for consistency (introduced
  special exception for LLDB that works similar to `gdb.GdbError`, i.e.
  doesn't cause traceback to be printed)
* `dbg.eval` no longer accept `None` argument (previously that way both
  GDB and LLDB implicitly handled missing command argument which
  eventually resulted in a poor-informative error)
---
 src/luajit_dbg.py                             | 65 ++++++++----
 .../debug-extension-tests.py                  | 98 +++++++++++++++++--
 2 files changed, 133 insertions(+), 30 deletions(-)

diff --git a/src/luajit_dbg.py b/src/luajit_dbg.py
index cfc3961c..7d8f2766 100644
--- a/src/luajit_dbg.py
+++ b/src/luajit_dbg.py
@@ -273,9 +273,6 @@ class _GDBDebugger(Debugger):
             return None
 
     def eval(self, expr):
-        if not expr:
-            return None
-
         return gdb.parse_and_eval(expr)
 
     def detect_arch(self):
@@ -672,9 +669,6 @@ class _LLDBDebugger(Debugger):
             return None
 
     def eval(self, expr):
-        if not expr:
-            return None
-
         process = self.target.GetProcess()
         thread = process.GetSelectedThread()
         frame = thread.GetSelectedFrame()
@@ -709,8 +703,13 @@ class _LLDBDebugger(Debugger):
     def write(self, msg):
         sys.stdout.write(msg)
 
+    class DbgError(Exception):
+        '''Raised to indicate an error during command execution.
+        Doesn't cause a traceback to be printed (like gdb.GdbError for GDB).'''
+        pass
+
     def error(self, errmsg):
-        return Exception(errmsg)
+        return self.DbgError(errmsg)
 
     def check_libluajit(self):
         # TODO: Implement postpone loading for LLDB too.
@@ -753,12 +752,27 @@ class _LLDBDebugger(Debugger):
         def __call__(ljbase, debugger, args, exe_ctx, result):
             try:
                 ljbase.execute(args)
-            except Exception as e:
+            except _LLDBDebugger.DbgError as e:
                 msg = 'Failed to execute command `{}`: {}'.format(
                     ljbase.name,
                     e
                 )
                 result.SetError(msg)
+                # `result` is an output argument of LLDB command
+                # handler. If an error message is set, LLDB
+                # displays it in the session. But such a message
+                # is missing in the output when the same problem
+                # occurs in batch mode, so in order to be able to
+                # catch this kind of error in batch mode it is
+                # needed to put it into stderr explicitly.
+                # Also to avoid duplication of the same error
+                # message in interactive mode, it should be done
+                # in batch mode only. There is no official way to
+                # check if LLDB is in the batch mode so one of the
+                # recommended workarounds is used below that
+                # checks if tty is not used for standard input.
+                if not sys.stdin.isatty():
+                    result.PutError(lldb.SBFile.Create(sys.stderr, True))
 
         @abc.abstractmethod
         def execute(ljbase, args):
@@ -2929,6 +2943,15 @@ def dump_jslots(J):
     return '\n'.join(dump)
 
 
+# Extension commands helpers. ####################################
+
+
+def cast_command_arg(typestr, arg):
+    if not arg:
+        raise dbg.error('Argument is required')
+    return dbg.cast(typestr, dbg.eval(arg))
+
+
 # Extension commands. ############################################
 
 
@@ -2976,7 +2999,7 @@ https://github.com/tarantool/tarantool/wiki/LuaJIT-Bytecodes.
     '''
 
     def execute(self, arg):
-        dbg.print(dump_bc(dbg.cast('BCIns *', dbg.eval(arg))[0]))
+        dbg.print(dump_bc(cast_command_arg('BCIns *', arg)[0]))
 
 
 class LJDumpCType(dbg.LJBase):
@@ -2988,7 +3011,7 @@ and dumps the ID and the name for this C data type.
     '''
 
     def execute(self, arg):
-        dbg.print(dump_ctype(dbg.cast('CType *', dbg.eval(arg))))
+        dbg.print(dump_ctype(cast_command_arg('CType *', arg)))
 
 
 class LJDumpFunc(dbg.LJBase):
@@ -3013,7 +3036,7 @@ function:
     '''
 
     def execute(self, arg):
-        dbg.print(dump_func(dbg.cast('GCfuncC *', dbg.eval(arg))))
+        dbg.print(dump_func(cast_command_arg('GCfuncC *', arg)))
 
 
 class LJGC(dbg.LJBase):
@@ -3068,7 +3091,7 @@ error message occurs.
     '''
 
     def execute(self, arg):
-        dbg.print(dump_gcobj(dbg.cast('GCobj *', dbg.eval(arg))))
+        dbg.print(dump_gcobj(cast_command_arg('GCobj *', arg)))
 
 
 class LJDumpIR(dbg.LJBase):
@@ -3085,7 +3108,7 @@ https://github.com/tarantool/tarantool/wiki/LuaJIT-SSA-IR.
     '''
 
     def execute(self, arg):
-        dbg.print(dump_irins(dbg.cast('IRIns *', dbg.eval(arg))))
+        dbg.print(dump_irins(cast_command_arg('IRIns *', arg)))
 
 
 class LJDumpJSlots(dbg.LJBase):
@@ -3102,7 +3125,8 @@ when there is no coroutine to be inspected in the debugged frame.
     '''
 
     def execute(self, arg):
-        dbg.print(dump_jslots(J(G(L(dbg.eval(arg))))))
+        lstate = L(dbg.eval(arg) if arg else None)
+        dbg.print(dump_jslots(J(G(lstate))))
 
 
 class LJDumpProto(dbg.LJBase):
@@ -3127,7 +3151,7 @@ function:
     '''
 
     def execute(self, arg):
-        dbg.print(dump_proto(dbg.cast('GCproto *', dbg.eval(arg))))
+        dbg.print(dump_proto(cast_command_arg('GCproto *', arg)))
 
 
 class LJDumpStack(dbg.LJBase):
@@ -3164,7 +3188,8 @@ If L is omitted, the main coroutine is used.
     '''
 
     def execute(self, arg):
-        dbg.print(dump_stack(L(dbg.eval(arg))))
+        lstate = L(dbg.eval(arg) if arg else None)
+        dbg.print(dump_stack(lstate))
 
 
 class LJState(dbg.LJBase):
@@ -3199,7 +3224,7 @@ is replaced with the corresponding error when decoding fails.
     '''
 
     def execute(self, arg):
-        string = dbg.cast('GCstr *', dbg.eval(arg))
+        string = cast_command_arg('GCstr *', arg)
         dbg.print("String: {body} [{len} bytes] with hash {hash}".format(
             body=strdata(string),
             hash=strx64(string['hash']),
@@ -3220,7 +3245,7 @@ The command receives a GCtab address and dumps the table contents:
     '''
 
     def execute(self, arg):
-        t = dbg.cast('GCtab *', dbg.eval(arg))
+        t = cast_command_arg('GCtab *', arg)
         array = mref('TValue *', t['array'])
         nodes = mref('struct Node *', t['node'])
         mt = gcval(t['metatable'])
@@ -3283,7 +3308,7 @@ error message occurs.
     '''
 
     def execute(self, arg):
-        dbg.print(dump_tvalue(dbg.cast('TValue *', dbg.eval(arg))))
+        dbg.print(dump_tvalue(cast_command_arg('TValue *', arg)))
 
 
 class LJDumpTrace(dbg.LJBase):
@@ -3302,7 +3327,7 @@ Trace may be preceded with /FLAGS:
 
     def execute(self, arg):
         arg, flags = dbg.extract_flags(arg, 'rs')
-        dbg.print(dump_trace(dbg.cast('GCtrace *', dbg.eval(arg)), flags))
+        dbg.print(dump_trace(cast_command_arg('GCtrace *', arg), flags))
 
 
 def load(event=None):
diff --git a/test/tarantool-debugger-tests/debug-extension-tests.py b/test/tarantool-debugger-tests/debug-extension-tests.py
index ab44121c..75459378 100644
--- a/test/tarantool-debugger-tests/debug-extension-tests.py
+++ b/test/tarantool-debugger-tests/debug-extension-tests.py
@@ -1,6 +1,7 @@
 # This file provides tests for LuaJIT debug extensions for lldb
 # and gdb.
 
+import functools
 import os
 import re
 import subprocess
@@ -10,6 +11,11 @@ import unittest
 
 from threading import Timer
 
+# Assume not cross-platform debugging.
+machine = os.uname().machine
+if machine not in ['x86_64', 'arm64', 'aarch64']:
+    raise Exception('{}: Unknown architecture in testing'.format(machine))
+
 LEGACY = re.match(r'^2\.', sys.version)
 
 LUAJIT_BINARY = os.environ['LUAJIT_TEST_BINARY']
@@ -19,6 +25,13 @@ LLDB = 'lldb' in DEBUGGER
 EXTENSION = EXTENSION_PATH + '/luajit_dbg.py'
 TIMEOUT = 10
 
+# List of regex that specifies lines to be wiped out from the
+# debugger output before checking against test's pattern.
+# In case some specific line need to be removed, just append this
+# list with the corresponding regex (use the strictest regex
+# possible to avoid accidental removing of useful data).
+RX_LINES_TO_REMOVE = []
+
 if LLDB:
     INFERIOR_ARGS = '--'
     LOAD_EXTENSION = 'command script import ' + EXTENSION
@@ -35,6 +48,23 @@ if LLDB:
         '--source-quietly',
         '--source'
     ]
+
+    # While executing an extension commands, LLDB might produce
+    # errors that cannot be caught in the extension. The internal
+    # parser does some processing in background and might emit
+    # an error message into stderr asynchronously.
+    # Also, the internal parser has a kind of fallback mechanism
+    # that might resolve the problem to proceed working correctly,
+    # but there is no way to "cancel" the mentioned error message,
+    # which might affect tests in this case.
+    if machine in ['arm64', 'aarch64']:
+        # This error occurs on ARM while parsing `union FPRCBArg`
+        # (it looks like either offset of `f` field or size of
+        # `union FPRCBArg` is identified incorrectly).
+        RX_LINES_TO_REMOVE.append(
+            r".*DW_TAG_member 'f' refers to type \w+ which extends beyond.*",
+        )
+
 else:
     # GDB.
     INFERIOR_ARGS = '--args'
@@ -68,12 +98,12 @@ def execute_process(cmd, timeout=TIMEOUT):
         process = subprocess.Popen(
             cmd,
             stdout=subprocess.PIPE,
-            stderr=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
             # This prevents sending of SIGSTTOU to the test when
             # running by `make'. Stdin is unused anyway.
             stdin=subprocess.DEVNULL
         )
-        timer = Timer(TIMEOUT, process.kill)
+        timer = Timer(timeout, process.kill)
         timer.start()
         stdout, _ = process.communicate()
         timer.cancel()
@@ -87,16 +117,31 @@ def execute_process(cmd, timeout=TIMEOUT):
         process = subprocess.run(
             cmd,
             stdout=subprocess.PIPE,
-            stderr=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
             # This prevents sending of SIGSTTOU to the test when
             # running by `make'. Stdin is unused anyway.
             stdin=subprocess.DEVNULL,
             universal_newlines=True,
-            timeout=TIMEOUT
+            timeout=timeout,
         )
         return process.stdout
 
 
+# Decorator that wipes out lines from the function result.
+def filterout_result(rx_lines):
+    def decorator(func):
+        @functools.wraps(func)
+        def wrapper(*args, **kwargs):
+            result = func(*args, **kwargs)
+            return re.sub(r'^({})\n'.format('|'.join(rx_lines)),
+                          '', result, flags=re.M)
+        return wrapper
+    return decorator
+
+
+if RX_LINES_TO_REMOVE:
+    execute_process = filterout_result(RX_LINES_TO_REMOVE)(execute_process)
+
 IS_DUALNUM = execute_process([
     LUAJIT_BINARY, '-e', "print(require('ffi').abi('dualnum'))"
 ]).strip() == 'true'
@@ -114,17 +159,12 @@ RX_P = 'p64' if IS_GC64 else 'p32'
 RX_INT = r'integer' if IS_DUALNUM else r'number'
 RX_ISDUALNUM = r'True' if IS_DUALNUM else r'False'
 
-
-# Assume not cross-platform debugging.
-machine = os.uname().machine
 if machine == 'x86_64':
     RX_GPR = r'r\w\w'
     RX_FPR = r'xmm\d+'
 elif machine == 'arm64' or machine == 'aarch64':
     RX_GPR = r'x\d+'
     RX_FPR = r'd\d+'
-else:
-    raise Exception('Unknown architecture in testing')
 
 
 class TestCaseBase(unittest.TestCase):
@@ -1051,7 +1091,45 @@ class TestLJCTypeBase(TestCaseBase):
     pattern = r'\[\d+\] <int>'
 
 
-for test_cls in TestCaseBase.__subclasses__():
+class TestMissingArgBase(TestCaseBase):
+    location = 'lj_cf_print'
+    lua_script = 'print(1)'
+    pattern = r'Argument is required\n'
+
+    @classmethod
+    def setUpClass(cls):
+        cls.extension_cmds = '{}\n'.format(cls.cmd_name)
+        super(TestMissingArgBase, cls).setUpClass()
+
+
+# Generate the bunch of tests to check the "missing arg" error
+# with various commands.
+for cmd_name in [
+    'lj-bc',
+    'lj-ctype',
+    'lj-func',
+    'lj-gco',
+    'lj-proto',
+    'lj-str',
+    'lj-tab',
+    'lj-tv',
+]:
+    test_class_name = 'TestMissingArg_' + cmd_name.replace('-', '_')
+    globals()[test_class_name] = \
+        type(test_class_name, (TestMissingArgBase,), dict(cmd_name=cmd_name))
+
+
+def get_leaf_subclasses(cls):
+    subclasses = cls.__subclasses__()
+    if not subclasses:
+        yield cls
+    else:
+        for sub in subclasses:
+            for leaf in get_leaf_subclasses(sub):
+                yield leaf
+
+
+for test_cls in get_leaf_subclasses(TestCaseBase):
     test_cls.test = lambda self: self.check()
 
 if __name__ == '__main__':
-- 
2.55.0


  parent reply	other threads:[~2026-12-04 20:04 UTC|newest]

Thread overview: 8+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-04 20:03 [Tarantool-patches] [PATCH luajit v2 0/7] dbg: avoid hardcoded enums Mikhail Elhimov via Tarantool-patches
2026-12-04 20:03 ` [Tarantool-patches] [PATCH luajit v2 1/7] dbg: simplify composing of all commands output Mikhail Elhimov via Tarantool-patches
2026-12-04 20:03 ` [Tarantool-patches] [PATCH luajit v2 2/7] dbg: cleanup and unify `dbg.eval` Mikhail Elhimov via Tarantool-patches
2026-12-04 20:03 ` Mikhail Elhimov via Tarantool-patches [this message]
2026-12-04 20:03 ` [Tarantool-patches] [PATCH luajit v2 4/7] dbg: add tests of deferred extension loading Mikhail Elhimov via Tarantool-patches
2026-12-04 20:03 ` [Tarantool-patches] [PATCH luajit v2 5/7] dbg: avoid hardcoded enums Mikhail Elhimov via Tarantool-patches
2026-12-04 20:03 ` [Tarantool-patches] [PATCH luajit v2 6/7] dbg: display fast function name along with ffid Mikhail Elhimov via Tarantool-patches
2026-12-04 20:03 ` [Tarantool-patches] [PATCH luajit v2 7/7] dbg: remove wrong GC state Mikhail Elhimov via Tarantool-patches

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=10189fbca6be567d54795a24179fe8105ede822a.1796410322.git.m.elhimov@vk.team \
    --to=tarantool-patches@dev.tarantool.org \
    --cc=e.temirgaleev@tarantool.org \
    --cc=m.elhimov@vk.team \
    --cc=sergeyb@tarantool.org \
    --cc=skaplun@tarantool.org \
    --subject='Re: [Tarantool-patches] [PATCH luajit v2 3/7] dbg: handle missing cmd arg in a dbg-agnostic way' \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox