From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from [87.239.111.99] (localhost [127.0.0.1]) by dev.tarantool.org (Postfix) with ESMTP id B5A8B6E1EC; Tue, 24 Nov 2026 16:44:44 +0300 (MSK) DKIM-Filter: OpenDKIM Filter v2.11.0 dev.tarantool.org B5A8B6E1EC DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=tarantool.org; s=dev; t=1795527884; bh=PqA7iMCJXVn+FqbFBOAzyoRqDQAoiHiz89a9a2C1jxM=; h=Date:To:Cc:References:In-Reply-To:Subject:List-Id: List-Unsubscribe:List-Archive:List-Post:List-Help:List-Subscribe: From:Reply-To:From; b=s4wj5B6KPrcjbG2diE0KZuG56i8BFYbONKtL7eX8cF3saSV5lLXJglfRIKArz/Oi9 k+0WoHmVoVxyOXlLQHCORoIAayZrZBBR7Vd+KS/UquexUPGwj/LHxWWRjZa4C0tXSr AJ7GbKQFyNqYVMp8CjoOb8OTM+dniFmQGLmDmarU= Received: from send35.i.mail.ru (send35.i.mail.ru [89.221.237.130]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by dev.tarantool.org (Postfix) with ESMTPS id AD7786E1EC for ; Tue, 24 Nov 2026 16:44:43 +0300 (MSK) DKIM-Filter: OpenDKIM Filter v2.11.0 dev.tarantool.org AD7786E1EC Received: by exim-smtp-56bb8ff957-6t9bc with esmtpa (envelope-from ) id 1xVqp8-000000009cQ-07fz; Tue, 24 Nov 2026 16:44:42 +0300 Content-Type: multipart/alternative; boundary="------------rT54GruQV4VoO1hiIqKd5LBr" Message-ID: <44bc204d-986a-4595-9c95-9f49986b631d@tarantool.org> Date: Tue, 24 Nov 2026 16:44:40 +0300 MIME-Version: 1.0 User-Agent: Mozilla Thunderbird To: Mikhail Elhimov , Sergey Kaplun , Evgeniy Temirgaleev Cc: tarantool-patches@dev.tarantool.org References: <0a9a648552eb3a3bbaa9639e0d567ae008cb0e14.1794522533.git.m.elhimov@vk.team> Content-Language: en-US In-Reply-To: <0a9a648552eb3a3bbaa9639e0d567ae008cb0e14.1794522533.git.m.elhimov@vk.team> X-Mailru-Src: smtp X-4EC0790: 10 X-618D5548: A4445D502C9DB1785D1BE6A8D71B10A53ADBB4A02CE9AE676F523E1C917586C3C90332965441D576 X-7564579A: B8F34718100C35BD X-77F55803: 4F1203BC0FB41BD9DFC18640EC9820978B05C10A48D4749464769B14DE02A8CB182A05F538085040D64E40638544CA433DE06ABAFEAF6705C41D2ABF1F5333B0DF6662984D4EFC147AD2C9CDF6B3E5BD X-7FA49CB5: FF5795518A3D127A4AD6D5ED66289B5278DA827A17800CE75263010198C72082EA1F7E6F0F101C67BD4B6F7A4D31EC0BCC500DACC3FED6E28638F802B75D45FF8AA50765F7900637AC83A81C8FD4AD23D82A6BABE6F325AC2E85FA5F3EDFCBAA7353EFBB5533756603DA5D6BE41EFC0D3BE189015EE30C025FC508EA666B27154A3DDDD3D75017F7389733CBF5DBD5E9D5E8D9A59859A8B669875440691429F6CC7F00164DA146DA6F5DAA56C3B73B237318B6A418E8EAB86D1867E19FE14079C09775C1D3CA48CF3D321E7403792E342EB15956EA79C166A417C69337E82CC275ECD9A6C639B01B78DA827A17800CE7888FFA144A8AE6D0731C566533BA786AA5CC5B56E945C8DA X-C1DE0DAB: 0D63561A33F958A5881EBAC7EA61F13E5002B1117B3ED696AE9D14D532FC1F16F5FEB6EB1EB183FD823CB91A9FED034534781492E4B8EEAD9286887DC8F77E65 X-C8649E89: 1C3962B70DF3F0ADB58128AB1E6D661A716CD42B3DD1D34CAB70F9BE574AE9C625B6776AC983F447FC0B9F89525902EE6F57B2FD27647F25E66C117BDB76D659B93A68552051C652FB12729B6A2CAD5B9646890B21777AB536E9141F1189AFED3B0A417EB4F86E3CB8341EE9D5BE9A0A2509582D6F44D584D1180335D3B116CF94E0E48D1D60AEE0C7CEAA0681F5848F4C41F94D744909CE2512F26BEC029E55448553D2254B8D95CD72808BE417F3B9E0E7457915DAA85F X-D57D3AED: 3ZO7eAau8CL7WIMRKs4sN3D3tLDjz0dLbV79QFUyzQ2Ujvy7cMT6pYYqY16iZVKkSc3dCLJ7zSJH7+u4VD18S7Vl4ZUrpaVfd2+vE6kuoey4m4VkSEu53w8ahmwBjZKM/YPHZyZHvz5uv+WouB9+ObcCpyrx6l7KImUglyhkEat/+ysWwi0gdhEs0JGjl6ggRWTy1haxBpVdbIX1nthFXOcIETfglQORZ0zpDET4Zrk3igikrdHlWFs4gmfLTVQHDLEd9SnCO68= X-Mailru-Sender: 689FA8AB762F73937C9FA53A4753B313025110D5EE069AE1E57A5D66192662631FC9B6E872CCFA2AEF86D5F70DA33880E41E8EF7A07863ECB274557F927329BE2DDF8182D28ACDB545BD1C3CC395C826B4A721A3011E896F X-Mras: Ok Subject: Re: [Tarantool-patches] [PATCH luajit 1/4] dbg: clean up and unification X-BeenThere: tarantool-patches@dev.tarantool.org X-Mailman-Version: 2.1.34 Precedence: list List-Id: Tarantool development patches List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , From: Sergey Bronnikov via Tarantool-patches Reply-To: Sergey Bronnikov Errors-To: tarantool-patches-bounces@dev.tarantool.org Sender: "Tarantool-patches" This is a multi-part message in MIME format. --------------rT54GruQV4VoO1hiIqKd5LBr Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Hello, On 11/13/26 02:42, Mikhail Elhimov wrote: > * unified `dbg.eval` approach to simplify error handling (exception in > case of any failure) > * removed trailing newline in all the dumpers to unify composing of the > complex output > * newly introduced `dbg.print` is used whenever trailing newline is > needed to make code more compact and clean > * moved handling of a missing command arg to command level (all the > dump-like functions now expect concrete value) > * unified handling of command-level error (introduced special exception > for LLDB that works similar to `gdb.GdbError`, i.e. doesn't cause > traceback to be printed) > * in `gdb.eval()` dropped check of the value returned by > `gdb.parse_and_eval()` as it would also fail for an expression like > `'0'` (looks like a kind of experimental code that was left by mistake) > * `lldb.eval()` is adjusted to return object of the same type as > `lldb.cast()` method returns (this improves consistency) > * renamed `dbg.eval` argument to reflect its meaning (it is > an expression rather than a command) It would be much easier to review if this weren't all dumped into one huge commit. Could you split to a number of commits, one per item? > --- > src/luajit_dbg.py | 178 +++++++++-------- > .../debug-extension-tests.py | 182 +++++++++++++----- > 2 files changed, 234 insertions(+), 126 deletions(-) > > diff --git a/src/luajit_dbg.py b/src/luajit_dbg.py > index 80057a4e..77abf8c6 100644 > --- a/src/luajit_dbg.py > +++ b/src/luajit_dbg.py > @@ -110,6 +110,10 @@ class Debugger(object): > self.write('{} command initialized\n'.format(name)) > self.write('LuaJIT debug extension is successfully loaded\n') > > + def print(self, msg): > + '''Print the message with the new line.''' > + self.write(msg + '\n') > + > @abc.abstractmethod > def cast(self, typestr, val): > '''Cast the value to the required C type.''' > @@ -146,8 +150,8 @@ class Debugger(object): > pass > > @abc.abstractmethod > - def eval(self, command): > - '''Parse and evaluate the given debugger command.''' > + def eval(self, expr): > + '''Parse and evaluate the given debugger expression.''' > pass > > @abc.abstractmethod > @@ -268,14 +272,8 @@ class _GDBDebugger(Debugger): > else: > return None > > - def eval(self, command): > - if not command: > - return None > - > - ret = gdb.parse_and_eval(command) > - if not ret: > - raise gdb.GdbError('table argument empty') > - return ret > + def eval(self, expr): > + return gdb.parse_and_eval(expr) > > def detect_arch(self): > if hasattr(self, 'arch'): > @@ -670,15 +668,26 @@ class _LLDBDebugger(Debugger): > else: > return None > > - def eval(self, command): > - if not command: > - return None > - > + def eval(self, expr): > process = self.target.GetProcess() > thread = process.GetSelectedThread() > frame = thread.GetSelectedFrame() > - ret = frame.EvaluateExpression(command) > - return ret > + val = frame.EvaluateExpression(expr) > + # LLDB doesn't throw an exception if it fails to > + # evaluate an expression. In order to simplify handling > + # of `Debugger.eval()` it is convenient to make it work > + # similar to GDB, i.e. throw an exception in case of > + # failure. > + # Be aware that SBValue.IsValid() is necessary, but not > + # sufficient as it only indicates that the value object > + # does contain the relevant data (including the potential > + # error), so it is necessary to check the `error` property > + # as well. > + if not val.IsValid(): > + raise self.error('{}: invalid expression'.format(expr)) > + if val.error.fail: > + raise self.error(val.error) > + return lldb.value(val) > > def detect_arch(self): > if hasattr(self, 'arch'): > @@ -694,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. > @@ -738,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 error message is set, LLDB displays > + # it in session. But such a message is missing in > + # 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): > @@ -2399,7 +2428,7 @@ def dump_proto(proto): > startbc = proto_bc(proto) > func_loc = proto_loc(proto) > # Location has the following format: '{chunk}:{firstline}'. > - dump = '{func_loc}-{lastline}\n'.format( > + dump = '{func_loc}-{lastline}'.format( > func_loc=func_loc, > lastline=proto['firstline'] + proto['numline'], > ) > @@ -2408,9 +2437,9 @@ def dump_proto(proto): > return '=> ' + str(npc_from + delta).zfill(4) > > for bcnum in range(0, int(proto['sizebc'])): > - dump += (str(bcnum).zfill(4) + ' ' + dump_bc( > + dump += ('\n' + str(bcnum).zfill(4) + ' ' + dump_bc( > startbc[bcnum], jmp_format=jmp_format, jmp_ctx=bcnum, proto=proto, > - ) + '\n') > + )) > return dump > > > @@ -2421,9 +2450,9 @@ def dump_func(func): > pt = funcproto(func) > return dump_proto(pt) > elif ffid == 1: > - return 'C function @ {}\n'.format(strx64(func['f'])) > + return 'C function @ {}'.format(strx64(func['f'])) > else: > - return 'fast function #{}\n'.format(int(ffid)) > + return 'fast function #{}'.format(int(ffid)) > > > # FFI dumpers. > @@ -2740,7 +2769,7 @@ def dump_irins(irins, trace=None): > if op1 != -1: > args = dump_call_args(trace, int(op1)) > > - return '{flags} {type} {name:6} [{mode:2}] {f}({args}) {ct}\n'.format( > + return '{flags} {type} {name:6} [{mode:2}] {f}({args}) {ct}'.format( > flags=flags, > name=irname, > mode=ir_mode(irop), > @@ -2792,7 +2821,7 @@ def dump_irins(irins, trace=None): > else: > typename = IRTYPES[irt_type(irt)] > > - return '{flags} {type} {name:6} [{mode:2}] {left:<9s} {right}\n'.format( > + return '{flags} {type} {name:6} [{mode:2}] {left:<9s} {right}'.format( flags=flags, name=irname, mode=ir_mode(irop), @@ > -2857,18 +2886,19 @@ def dump_regsp(irins, ins_number): def > dump_trace(trace, flags): - dump = 'Trace {num} start\n\tproto: > {start_pt}\n\tBC: {start_bc}\n'.format( + dump = 'Trace {num} > start\n\tproto: {start_pt}\n\tBC: {start_bc}'.format( > num=trace['traceno'], start_pt=gcref(trace['startpt']), > start_bc=mref('BCIns *', trace['startpc']), ) nins = trace['nins'] - > REF_BIAS - dump += '---- TRACE IR\n' + dump += '\n---- TRACE IR' nsnap > = 0 snap = trace['snap'][nsnap] snapref = snap['ref'] for irnum in > range(1, nins): + dump += '\n' irref = REF_BIAS + irnum if 's' in > flags and irref >= snapref and nsnap < trace['nsnap']: > dump += '.... ' > @@ -2894,27 +2924,32 @@ def dump_tref(tref): > ) > > > -def dump_jslots(coroutine): > - lstate = L(None) > - g = G(lstate or coroutine) > - j = J(g) > - > - dump = '' > - maxslot = j['baseslot'] + j['maxslot'] > +def dump_jslots(J): > + dump = [] > + maxslot = J['baseslot'] + J['maxslot'] > first_base_slot = 1 + LJ_FR2 > for n in reversed(range(first_base_slot, maxslot)): > - tref = j['slot'][n] > + tref = J['slot'][n] > ref = tref_ref(tref) > address = dbg.address(tref) > - dump += '{addr} {nslot:04d} {base:1s} {tref}{const}\n'.format( > + dump.append('{addr} {nslot:04d} {base:1s} {tref}{const}'.format( > addr=address, > - base='B' if address == j['base'] else ' ', > + base='B' if address == J['base'] else ' ', > nslot=n, > tref=dump_tref(tref), > - const=' ' + dump_irk(j['cur'], ref - REF_BIAS) > - if ref != 0 and ref < REF_BIAS else '' > - ) > - return dump > + const=' ' + dump_irk(J['cur'], ref - REF_BIAS) > + if ref != 0 and ref < REF_BIAS else '' > + )) > + 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. ############################################ > @@ -2931,8 +2966,8 @@ compile-time flag to inspect if LuaJIT is built in dual-number mode. > ''' > > def execute(self, arg): > - dbg.write( > - 'LJ_64: {LJ_64}, LJ_GC64: {LJ_GC64}, LJ_DUALNUM: {LJ_DUALNUM}\n' > + dbg.print( > + 'LJ_64: {LJ_64}, LJ_GC64: {LJ_GC64}, LJ_DUALNUM: {LJ_DUALNUM}' > .format( > LJ_64=LJ_64, > LJ_GC64=LJ_GC64, > @@ -2964,9 +2999,7 @@https://github.com/tarantool/tarantool/wiki/LuaJIT-Bytecodes. > ''' > > def execute(self, arg): > - dbg.write('{}\n'.format( > - dump_bc(dbg.cast('BCIns *', dbg.eval(arg))[0]) > - )) > + dbg.print(dump_bc(cast_command_arg('BCIns *', arg)[0])) > > > class LJDumpCType(dbg.LJBase): > @@ -2978,9 +3011,7 @@ and dumps the ID and the name for this C data type. > ''' > > def execute(self, arg): > - dbg.write('{}\n'.format( > - dump_ctype(dbg.cast('CType *', dbg.eval(arg))) > - )) > + dbg.print(dump_ctype(cast_command_arg('CType *', arg))) > > > class LJDumpFunc(dbg.LJBase): > @@ -3005,7 +3036,7 @@ function: > ''' > > def execute(self, arg): > - dbg.write('{}'.format(dump_func(dbg.cast('GCfuncC *', dbg.eval(arg))))) > + dbg.print(dump_func(cast_command_arg('GCfuncC *', arg))) > > > class LJGC(dbg.LJBase): > @@ -3029,7 +3060,7 @@ The command requires no args and dumps current GC stats: > > def execute(self, arg): > g = G(L(None)) > - dbg.write('GC stats: {state}\n{stats}\n'.format( > + dbg.print('GC stats: {state}\n{stats}'.format( > state=gc_state(g), > stats=dump_gc(g) > )) > @@ -3060,8 +3091,7 @@ error message occurs. > ''' > > def execute(self, arg): > - gcobj = dbg.cast('GCobj *', dbg.eval(arg)) > - dbg.write('{}\n'.format(dump_gcobj(gcobj))) > + dbg.print(dump_gcobj(cast_command_arg('GCobj *', arg))) > > > class LJDumpIR(dbg.LJBase): > @@ -3078,7 +3108,7 @@https://github.com/tarantool/tarantool/wiki/LuaJIT-SSA-IR. > ''' > > def execute(self, arg): > - dbg.write('{}'.format(dump_irins(dbg.cast('IRIns *', dbg.eval(arg))))) > + dbg.print(dump_irins(cast_command_arg('IRIns *', arg))) > > > class LJDumpJSlots(dbg.LJBase): > @@ -3095,9 +3125,8 @@ when there is no coroutine to be inspected in the debugged frame. > ''' > > def execute(self, arg): > - dbg.write('{}'.format( > - dump_jslots(dbg.cast('lua_State *', dbg.eval(arg))) > - )) > + lstate = L(dbg.eval(arg) if arg else None) > + dbg.print(dump_jslots(J(G(lstate)))) > > > class LJDumpProto(dbg.LJBase): > @@ -3122,9 +3151,7 @@ function: > ''' > > def execute(self, arg): > - dbg.write('{}'.format( > - dump_proto(dbg.cast('GCproto *', dbg.eval(arg))) > - )) > + dbg.print(dump_proto(cast_command_arg('GCproto *', arg))) > > > class LJDumpStack(dbg.LJBase): > @@ -3161,7 +3188,8 @@ If L is omitted, the main coroutine is used. > ''' > > def execute(self, arg): > - dbg.write('{}\n'.format(dump_stack(L(dbg.eval(arg))))) > + lstate = L(dbg.eval(arg) if arg else None) > + dbg.print(dump_stack(lstate)) > > > class LJState(dbg.LJBase): > @@ -3175,13 +3203,13 @@ The command requires no args and dumps current VM and GC states: > > def execute(self, arg): > g = G(L(None)) > - dbg.write('{}\n'.format('\n'.join( > + dbg.print('\n'.join( > map(lambda t: '{} state: {}'.format(*t), { > 'VM': vm_state(g), > 'GC': gc_state(g), > 'JIT': jit_state(g), > }.items()) > - ))) > + )) > > > class LJDumpString(dbg.LJBase): > @@ -3196,8 +3224,8 @@ is replaced with the corresponding error when decoding fails. > ''' > > def execute(self, arg): > - string = dbg.cast('GCstr *', dbg.eval(arg)) > - dbg.write("String: {body} [{len} bytes] with hash {hash}\n".format( > + string = cast_command_arg('GCstr *', arg) > + dbg.print("String: {body} [{len} bytes] with hash {hash}".format( > body=strdata(string), > hash=strx64(string['hash']), > len=string['len'], > @@ -3217,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']) > @@ -3227,22 +3255,22 @@ The command receives a GCtab address and dumps the table contents: > } > > if mt != 0: > - dbg.write('Metatable detected: {}\n'.format(strx64(mt))) > + dbg.print('Metatable detected: {}'.format(strx64(mt))) > > - dbg.write('Array part: {} slots\n'.format(capacity['apart'])) > + dbg.print('Array part: {} slots'.format(capacity['apart'])) > for i in range(capacity['apart']): > slot = array + i > - dbg.write('{ptr}: [{index}]: {value}\n'.format( > + dbg.print('{ptr}: [{index}]: {value}'.format( > ptr=slot, > index=i, > value=dump_tvalue(slot) > )) > > - dbg.write('Hash part: {} nodes\n'.format(capacity['hpart'])) > + dbg.print('Hash part: {} nodes'.format(capacity['hpart'])) > # See hmask comment in lj_obj.h > for i in range(capacity['hpart']): > node = nodes + i > - dbg.write('{ptr}: {{ {key} }} => {{ {val} }}; next = {n}\n'.format( > + dbg.print('{ptr}: {{ {key} }} => {{ {val} }}; next = {n}'.format( > ptr=node, > key=dump_tvalue(node['key']), > val=dump_tvalue(node['val']), > @@ -3280,8 +3308,7 @@ error message occurs. > ''' > > def execute(self, arg): > - tv = dbg.cast('TValue *', dbg.eval(arg)) > - dbg.write('{}\n'.format(dump_tvalue(tv))) > + dbg.print(dump_tvalue(cast_command_arg('TValue *', arg))) > > > class LJDumpTrace(dbg.LJBase): > @@ -3300,10 +3327,7 @@ Trace may be preceded with /FLAGS: > > def execute(self, arg): > arg, flags = dbg.extract_flags(arg, 'rs') > - dbg.write('{}'.format(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..fe8c5028 100644 > --- a/test/tarantool-debugger-tests/debug-extension-tests.py > +++ b/test/tarantool-debugger-tests/debug-extension-tests.py > @@ -19,30 +19,6 @@ LLDB = 'lldb' in DEBUGGER > EXTENSION = EXTENSION_PATH + '/luajit_dbg.py' > TIMEOUT = 10 > > -if LLDB: > - INFERIOR_ARGS = '--' > - LOAD_EXTENSION = 'command script import ' + EXTENSION > - PROCESS_RUN = ( > - # Prevent errors in case when running tests in Docker. > - 'settings set target.disable-aslr false\n' > - 'process launch' > - ) > - # Don't run any initialization scripts. > - RUN_CMD_FILE = [ > - '--batch', > - '--no-lldbinit', > - '--no-use-colors', > - '--source-quietly', > - '--source' > - ] > -else: > - # GDB. > - INFERIOR_ARGS = '--args' > - LOAD_EXTENSION = 'source ' + EXTENSION > - PROCESS_RUN = 'run' > - # Don't run any initialization scripts. > - RUN_CMD_FILE = ['--batch', '--nx', '--quiet', '--command'] > - > TEST_VERBOSE = os.getenv('DEBUGGER_TEST_VERBOSE', default=False) > > RX_ADDR = r'0x[a-f0-9]+' > @@ -60,7 +36,7 @@ def persist(data): > return tmp > > > -def execute_process(cmd, timeout=TIMEOUT): > +def execute_process_raw(cmd, timeout=TIMEOUT): > if LEGACY: > # XXX: The Python 2.7 version of `subprocess.Popen` > # doesn't have a timeout option, so the required > @@ -68,12 +44,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 +63,71 @@ 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 > > > +if LLDB: > + INFERIOR_ARGS = '--' > + LOAD_EXTENSION = 'command script import ' + EXTENSION > + PROCESS_RUN = ( > + # Prevent errors in case when running tests in Docker. > + 'settings set target.disable-aslr false\n' > + 'process launch' > + ) > + # Don't run any initialization scripts. > + RUN_CMD_FILE = [ > + '--batch', > + '--no-lldbinit', > + '--no-use-colors', > + '--source-quietly', > + '--source' > + ] > + SET_EXEC = 'target create ' + LUAJIT_BINARY > + SET_RUN_ARGS = 'settings set target.run-args' > + > + def execute_process(cmd, timeout=TIMEOUT): > + # While executing extension commands LLDB might produce > + # errors that cannot be caught in 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, but is not able to > + # "cancel" the error message which might fail tests in > + # this case. > + # > + # List of regex that specifies lines to be wiped out from > + # the LLDB output. In case additional cleaning is needed, > + # just append this list with the correponding regex (use > + # as strict regex as possible in order to avoid accidental > + # removing of relevant data). > + RX_LINES_TO_REMOVE = [ > + # This error occurs while parsing `union FPRCBArg` (it > + # looks like either offset of `f`` field or size of > + # `union FPRCBArg` is identified incorrectly). > + r".*DW_TAG_member 'f' refers to type \w+ which extends beyond.*", > + ] > + raw_out = execute_process_raw(cmd, timeout) > + return re.sub(r'^({})\n'.format('|'.join(RX_LINES_TO_REMOVE)), > + '', raw_out, flags=re.M) > + > +else: > + # GDB. > + INFERIOR_ARGS = '--args' > + LOAD_EXTENSION = 'source ' + EXTENSION > + PROCESS_RUN = 'run' > + # Don't run any initialization scripts. > + RUN_CMD_FILE = ['--batch', '--nx', '--quiet', '--command'] > + SET_EXEC = 'file ' + LUAJIT_BINARY > + SET_RUN_ARGS = 'set args' > + execute_process = execute_process_raw > + > IS_DUALNUM = execute_process([ > LUAJIT_BINARY, '-e', "print(require('ffi').abi('dualnum'))" > ]).strip() == 'true' > @@ -129,42 +160,38 @@ else: > > class TestCaseBase(unittest.TestCase): > @classmethod > - def construct_cmds(cls): > - return '\n'.join([ > + def construct_cmds(cls, deferred, *run_args): > + cmds = [ > + SET_EXEC, > + SET_RUN_ARGS + ' ' + ' '.join(run_args), > 'b {loc}'.format(loc=cls.location), > PROCESS_RUN, > 'n', > - LOAD_EXTENSION, > cls.extension_cmds.strip(), > - 'q', > - ]) > + ] > + cmds.insert(0 if deferred else 1, LOAD_EXTENSION) > + return '\n'.join(cmds) > > - @classmethod > - def setUpClass(cls): > - cmd_file = persist(cls.construct_cmds()) > - script_file = persist(cls.lua_script) > + def check(self, deferred=False): > + script_file = persist(self.lua_script) > + cmd_file = persist(self.construct_cmds(deferred, script_file.name)) > process_cmd = [ > DEBUGGER, > *RUN_CMD_FILE, > cmd_file.name, > - INFERIOR_ARGS, > - LUAJIT_BINARY, > - script_file.name, > ] > if TEST_VERBOSE: > - print('# Test name: {}'.format(cls.__name__)) > + print('# Test name: {}'.format(self.__class__.__name__)) > print('# Test command: {}'.format(' '.join(process_cmd))) > - cls.output = execute_process(process_cmd) > + output = execute_process(process_cmd) > if TEST_VERBOSE: > - print('# Command output:\n{}'.format(cls.output)) > + print('# Command output:\n{}'.format(output)) > cmd_file.close() > script_file.close() > - > - def check(self): > if LEGACY: > - self.assertRegexpMatches(self.output, self.pattern.strip()) > + self.assertRegexpMatches(output, self.pattern.strip()) > else: > - self.assertRegex(self.output, self.pattern.strip()) > + self.assertRegex(output, self.pattern.strip()) > > > # Test that the emitted debug information supports macro > @@ -1051,8 +1078,65 @@ class TestLJCTypeBase(TestCaseBase): > pattern = r'\[\d+\] ' > > > -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() > + > + > +class TestMissingArgLJFunc(TestMissingArgBase): > + cmd_name = 'lj-func' > + > + > +class TestMissingArgLJTValue(TestMissingArgBase): > + cmd_name = 'lj-tv' > + > + > +class TestMissingArgLJBC(TestMissingArgBase): > + cmd_name = 'lj-bc' > + > + > +class TestMissingArgLJStr(TestMissingArgBase): > + cmd_name = 'lj-str' > + > + > +class TestMissingArgLJTable(TestMissingArgBase): > + cmd_name = 'lj-tab' > + > + > +class TestMissingArgLJProto(TestMissingArgBase): > + cmd_name = 'lj-proto' > + > + > +class TestMissingArgLJGCO(TestMissingArgBase): > + cmd_name = 'lj-gco' > + > + > +class TestMissingArgLJCType(TestMissingArgBase): > + cmd_name = 'lj-ctype' > + > + > +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() > + test_cls.test_with_deferred_loading = \ > + unittest.skipIf(LLDB, "not supported for LLDB")( > + lambda self: self.check(True) > + ) > > if __name__ == '__main__': > unittest.main(verbosity=2) --------------rT54GruQV4VoO1hiIqKd5LBr Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: 7bit

Hello,

On 11/13/26 02:42, Mikhail Elhimov wrote:
* unified `dbg.eval` approach to simplify error handling (exception in
  case of any failure)
* removed trailing newline in all the dumpers to unify composing of the
  complex output
* newly introduced `dbg.print` is used whenever trailing newline is
  needed to make code more compact and clean
* moved handling of a missing command arg to command level (all the
  dump-like functions now expect concrete value)
* unified handling of command-level error (introduced special exception
  for LLDB that works similar to `gdb.GdbError`, i.e. doesn't cause
  traceback to be printed)
* in `gdb.eval()` dropped check of the value returned by
  `gdb.parse_and_eval()` as it would also fail for an expression like
 `'0'` (looks like a kind of experimental code that was left by mistake)
* `lldb.eval()` is adjusted to return object of the same type as
  `lldb.cast()` method returns (this improves consistency)
* renamed `dbg.eval` argument to reflect its meaning (it is
  an expression rather than a command)

It would be much easier to review if this weren't all dumped into one huge commit.

Could you split to a number of commits, one per item?


---
 src/luajit_dbg.py                             | 178 +++++++++--------
 .../debug-extension-tests.py                  | 182 +++++++++++++-----
 2 files changed, 234 insertions(+), 126 deletions(-)

diff --git a/src/luajit_dbg.py b/src/luajit_dbg.py
index 80057a4e..77abf8c6 100644
--- a/src/luajit_dbg.py
+++ b/src/luajit_dbg.py
@@ -110,6 +110,10 @@ class Debugger(object):
                 self.write('{} command initialized\n'.format(name))
             self.write('LuaJIT debug extension is successfully loaded\n')
 
+    def print(self, msg):
+        '''Print the message with the new line.'''
+        self.write(msg + '\n')
+
     @abc.abstractmethod
     def cast(self, typestr, val):
         '''Cast the value to the required C type.'''
@@ -146,8 +150,8 @@ class Debugger(object):
         pass
 
     @abc.abstractmethod
-    def eval(self, command):
-        '''Parse and evaluate the given debugger command.'''
+    def eval(self, expr):
+        '''Parse and evaluate the given debugger expression.'''
         pass
 
     @abc.abstractmethod
@@ -268,14 +272,8 @@ class _GDBDebugger(Debugger):
         else:
             return None
 
-    def eval(self, command):
-        if not command:
-            return None
-
-        ret = gdb.parse_and_eval(command)
-        if not ret:
-            raise gdb.GdbError('table argument empty')
-        return ret
+    def eval(self, expr):
+        return gdb.parse_and_eval(expr)
 
     def detect_arch(self):
         if hasattr(self, 'arch'):
@@ -670,15 +668,26 @@ class _LLDBDebugger(Debugger):
         else:
             return None
 
-    def eval(self, command):
-        if not command:
-            return None
-
+    def eval(self, expr):
         process = self.target.GetProcess()
         thread = process.GetSelectedThread()
         frame = thread.GetSelectedFrame()
-        ret = frame.EvaluateExpression(command)
-        return ret
+        val = frame.EvaluateExpression(expr)
+        # LLDB doesn't throw an exception if it fails to
+        # evaluate an expression. In order to simplify handling
+        # of `Debugger.eval()` it is convenient to make it work
+        # similar to GDB, i.e. throw an exception in case of
+        # failure.
+        # Be aware that SBValue.IsValid() is necessary, but not
+        # sufficient as it only indicates that the value object
+        # does contain the relevant data (including the potential
+        # error), so it is necessary to check the `error` property
+        # as well.
+        if not val.IsValid():
+            raise self.error('{}: invalid expression'.format(expr))
+        if val.error.fail:
+            raise self.error(val.error)
+        return lldb.value(val)
 
     def detect_arch(self):
         if hasattr(self, 'arch'):
@@ -694,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.
@@ -738,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 error message is set, LLDB displays
+                # it in session. But such a message is missing in
+                # 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):
@@ -2399,7 +2428,7 @@ def dump_proto(proto):
     startbc = proto_bc(proto)
     func_loc = proto_loc(proto)
     # Location has the following format: '{chunk}:{firstline}'.
-    dump = '{func_loc}-{lastline}\n'.format(
+    dump = '{func_loc}-{lastline}'.format(
         func_loc=func_loc,
         lastline=proto['firstline'] + proto['numline'],
     )
@@ -2408,9 +2437,9 @@ def dump_proto(proto):
         return '=> ' + str(npc_from + delta).zfill(4)
 
     for bcnum in range(0, int(proto['sizebc'])):
-        dump += (str(bcnum).zfill(4) + ' ' + dump_bc(
+        dump += ('\n' + str(bcnum).zfill(4) + ' ' + dump_bc(
             startbc[bcnum], jmp_format=jmp_format, jmp_ctx=bcnum, proto=proto,
-        ) + '\n')
+        ))
     return dump
 
 
@@ -2421,9 +2450,9 @@ def dump_func(func):
         pt = funcproto(func)
         return dump_proto(pt)
     elif ffid == 1:
-        return 'C function @ {}\n'.format(strx64(func['f']))
+        return 'C function @ {}'.format(strx64(func['f']))
     else:
-        return 'fast function #{}\n'.format(int(ffid))
+        return 'fast function #{}'.format(int(ffid))
 
 
 # FFI dumpers.
@@ -2740,7 +2769,7 @@ def dump_irins(irins, trace=None):
         if op1 != -1:
             args = dump_call_args(trace, int(op1))
 
-        return '{flags} {type} {name:6} [{mode:2}] {f}({args}) {ct}\n'.format(
+        return '{flags} {type} {name:6} [{mode:2}] {f}({args}) {ct}'.format(
             flags=flags,
             name=irname,
             mode=ir_mode(irop),
@@ -2792,7 +2821,7 @@ def dump_irins(irins, trace=None):
     else:
         typename = IRTYPES[irt_type(irt)]
 
-    return '{flags} {type} {name:6} [{mode:2}] {left:<9s} {right}\n'.format(
+    return '{flags} {type} {name:6} [{mode:2}] {left:<9s} {right}'.format(
         flags=flags,
         name=irname,
         mode=ir_mode(irop),
@@ -2857,18 +2886,19 @@ def dump_regsp(irins, ins_number):
 
 
 def dump_trace(trace, flags):
-    dump = 'Trace {num} start\n\tproto: {start_pt}\n\tBC: {start_bc}\n'.format(
+    dump = 'Trace {num} start\n\tproto: {start_pt}\n\tBC: {start_bc}'.format(
         num=trace['traceno'],
         start_pt=gcref(trace['startpt']),
         start_bc=mref('BCIns *', trace['startpc']),
     )
 
     nins = trace['nins'] - REF_BIAS
-    dump += '---- TRACE IR\n'
+    dump += '\n---- TRACE IR'
     nsnap = 0
     snap = trace['snap'][nsnap]
     snapref = snap['ref']
     for irnum in range(1, nins):
+        dump += '\n'
         irref = REF_BIAS + irnum
         if 's' in flags and irref >= snapref and nsnap < trace['nsnap']:
             dump += '....          '
@@ -2894,27 +2924,32 @@ def dump_tref(tref):
     )
 
 
-def dump_jslots(coroutine):
-    lstate = L(None)
-    g = G(lstate or coroutine)
-    j = J(g)
-
-    dump = ''
-    maxslot = j['baseslot'] + j['maxslot']
+def dump_jslots(J):
+    dump = []
+    maxslot = J['baseslot'] + J['maxslot']
     first_base_slot = 1 + LJ_FR2
     for n in reversed(range(first_base_slot, maxslot)):
-        tref = j['slot'][n]
+        tref = J['slot'][n]
         ref = tref_ref(tref)
         address = dbg.address(tref)
-        dump += '{addr} {nslot:04d} {base:1s} {tref}{const}\n'.format(
+        dump.append('{addr} {nslot:04d} {base:1s} {tref}{const}'.format(
             addr=address,
-            base='B' if address == j['base'] else ' ',
+            base='B' if address == J['base'] else ' ',
             nslot=n,
             tref=dump_tref(tref),
-            const=' ' + dump_irk(j['cur'], ref - REF_BIAS)
-                if ref != 0 and ref < REF_BIAS else ''
-        )
-    return dump
+            const=' ' + dump_irk(J['cur'], ref - REF_BIAS)
+                  if ref != 0 and ref < REF_BIAS else ''
+        ))
+    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. ############################################
@@ -2931,8 +2966,8 @@ compile-time flag to inspect if LuaJIT is built in dual-number mode.
     '''
 
     def execute(self, arg):
-        dbg.write(
-            'LJ_64: {LJ_64}, LJ_GC64: {LJ_GC64}, LJ_DUALNUM: {LJ_DUALNUM}\n'
+        dbg.print(
+            'LJ_64: {LJ_64}, LJ_GC64: {LJ_GC64}, LJ_DUALNUM: {LJ_DUALNUM}'
             .format(
                 LJ_64=LJ_64,
                 LJ_GC64=LJ_GC64,
@@ -2964,9 +2999,7 @@ https://github.com/tarantool/tarantool/wiki/LuaJIT-Bytecodes.
     '''
 
     def execute(self, arg):
-        dbg.write('{}\n'.format(
-            dump_bc(dbg.cast('BCIns *', dbg.eval(arg))[0])
-        ))
+        dbg.print(dump_bc(cast_command_arg('BCIns *', arg)[0]))
 
 
 class LJDumpCType(dbg.LJBase):
@@ -2978,9 +3011,7 @@ and dumps the ID and the name for this C data type.
     '''
 
     def execute(self, arg):
-        dbg.write('{}\n'.format(
-            dump_ctype(dbg.cast('CType *', dbg.eval(arg)))
-        ))
+        dbg.print(dump_ctype(cast_command_arg('CType *', arg)))
 
 
 class LJDumpFunc(dbg.LJBase):
@@ -3005,7 +3036,7 @@ function:
     '''
 
     def execute(self, arg):
-        dbg.write('{}'.format(dump_func(dbg.cast('GCfuncC *', dbg.eval(arg)))))
+        dbg.print(dump_func(cast_command_arg('GCfuncC *', arg)))
 
 
 class LJGC(dbg.LJBase):
@@ -3029,7 +3060,7 @@ The command requires no args and dumps current GC stats:
 
     def execute(self, arg):
         g = G(L(None))
-        dbg.write('GC stats: {state}\n{stats}\n'.format(
+        dbg.print('GC stats: {state}\n{stats}'.format(
             state=gc_state(g),
             stats=dump_gc(g)
         ))
@@ -3060,8 +3091,7 @@ error message occurs.
     '''
 
     def execute(self, arg):
-        gcobj = dbg.cast('GCobj *', dbg.eval(arg))
-        dbg.write('{}\n'.format(dump_gcobj(gcobj)))
+        dbg.print(dump_gcobj(cast_command_arg('GCobj *', arg)))
 
 
 class LJDumpIR(dbg.LJBase):
@@ -3078,7 +3108,7 @@ https://github.com/tarantool/tarantool/wiki/LuaJIT-SSA-IR.
     '''
 
     def execute(self, arg):
-        dbg.write('{}'.format(dump_irins(dbg.cast('IRIns *', dbg.eval(arg)))))
+        dbg.print(dump_irins(cast_command_arg('IRIns *', arg)))
 
 
 class LJDumpJSlots(dbg.LJBase):
@@ -3095,9 +3125,8 @@ when there is no coroutine to be inspected in the debugged frame.
     '''
 
     def execute(self, arg):
-        dbg.write('{}'.format(
-            dump_jslots(dbg.cast('lua_State *', dbg.eval(arg)))
-        ))
+        lstate = L(dbg.eval(arg) if arg else None)
+        dbg.print(dump_jslots(J(G(lstate))))
 
 
 class LJDumpProto(dbg.LJBase):
@@ -3122,9 +3151,7 @@ function:
     '''
 
     def execute(self, arg):
-        dbg.write('{}'.format(
-            dump_proto(dbg.cast('GCproto *', dbg.eval(arg)))
-        ))
+        dbg.print(dump_proto(cast_command_arg('GCproto *', arg)))
 
 
 class LJDumpStack(dbg.LJBase):
@@ -3161,7 +3188,8 @@ If L is omitted, the main coroutine is used.
     '''
 
     def execute(self, arg):
-        dbg.write('{}\n'.format(dump_stack(L(dbg.eval(arg)))))
+        lstate = L(dbg.eval(arg) if arg else None)
+        dbg.print(dump_stack(lstate))
 
 
 class LJState(dbg.LJBase):
@@ -3175,13 +3203,13 @@ The command requires no args and dumps current VM and GC states:
 
     def execute(self, arg):
         g = G(L(None))
-        dbg.write('{}\n'.format('\n'.join(
+        dbg.print('\n'.join(
             map(lambda t: '{} state: {}'.format(*t), {
                 'VM':  vm_state(g),
                 'GC':  gc_state(g),
                 'JIT': jit_state(g),
             }.items())
-        )))
+        ))
 
 
 class LJDumpString(dbg.LJBase):
@@ -3196,8 +3224,8 @@ is replaced with the corresponding error when decoding fails.
     '''
 
     def execute(self, arg):
-        string = dbg.cast('GCstr *', dbg.eval(arg))
-        dbg.write("String: {body} [{len} bytes] with hash {hash}\n".format(
+        string = cast_command_arg('GCstr *', arg)
+        dbg.print("String: {body} [{len} bytes] with hash {hash}".format(
             body=strdata(string),
             hash=strx64(string['hash']),
             len=string['len'],
@@ -3217,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'])
@@ -3227,22 +3255,22 @@ The command receives a GCtab address and dumps the table contents:
         }
 
         if mt != 0:
-            dbg.write('Metatable detected: {}\n'.format(strx64(mt)))
+            dbg.print('Metatable detected: {}'.format(strx64(mt)))
 
-        dbg.write('Array part: {} slots\n'.format(capacity['apart']))
+        dbg.print('Array part: {} slots'.format(capacity['apart']))
         for i in range(capacity['apart']):
             slot = array + i
-            dbg.write('{ptr}: [{index}]: {value}\n'.format(
+            dbg.print('{ptr}: [{index}]: {value}'.format(
                 ptr=slot,
                 index=i,
                 value=dump_tvalue(slot)
             ))
 
-        dbg.write('Hash part: {} nodes\n'.format(capacity['hpart']))
+        dbg.print('Hash part: {} nodes'.format(capacity['hpart']))
         # See hmask comment in lj_obj.h
         for i in range(capacity['hpart']):
             node = nodes + i
-            dbg.write('{ptr}: {{ {key} }} => {{ {val} }}; next = {n}\n'.format(
+            dbg.print('{ptr}: {{ {key} }} => {{ {val} }}; next = {n}'.format(
                 ptr=node,
                 key=dump_tvalue(node['key']),
                 val=dump_tvalue(node['val']),
@@ -3280,8 +3308,7 @@ error message occurs.
     '''
 
     def execute(self, arg):
-        tv = dbg.cast('TValue *', dbg.eval(arg))
-        dbg.write('{}\n'.format(dump_tvalue(tv)))
+        dbg.print(dump_tvalue(cast_command_arg('TValue *', arg)))
 
 
 class LJDumpTrace(dbg.LJBase):
@@ -3300,10 +3327,7 @@ Trace may be preceded with /FLAGS:
 
     def execute(self, arg):
         arg, flags = dbg.extract_flags(arg, 'rs')
-        dbg.write('{}'.format(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..fe8c5028 100644
--- a/test/tarantool-debugger-tests/debug-extension-tests.py
+++ b/test/tarantool-debugger-tests/debug-extension-tests.py
@@ -19,30 +19,6 @@ LLDB = 'lldb' in DEBUGGER
 EXTENSION = EXTENSION_PATH + '/luajit_dbg.py'
 TIMEOUT = 10
 
-if LLDB:
-    INFERIOR_ARGS = '--'
-    LOAD_EXTENSION = 'command script import ' + EXTENSION
-    PROCESS_RUN = (
-        # Prevent errors in case when running tests in Docker.
-        'settings set target.disable-aslr false\n'
-        'process launch'
-    )
-    # Don't run any initialization scripts.
-    RUN_CMD_FILE = [
-        '--batch',
-        '--no-lldbinit',
-        '--no-use-colors',
-        '--source-quietly',
-        '--source'
-    ]
-else:
-    # GDB.
-    INFERIOR_ARGS = '--args'
-    LOAD_EXTENSION = 'source ' + EXTENSION
-    PROCESS_RUN = 'run'
-    # Don't run any initialization scripts.
-    RUN_CMD_FILE = ['--batch', '--nx', '--quiet', '--command']
-
 TEST_VERBOSE = os.getenv('DEBUGGER_TEST_VERBOSE', default=False)
 
 RX_ADDR = r'0x[a-f0-9]+'
@@ -60,7 +36,7 @@ def persist(data):
     return tmp
 
 
-def execute_process(cmd, timeout=TIMEOUT):
+def execute_process_raw(cmd, timeout=TIMEOUT):
     if LEGACY:
         # XXX: The Python 2.7 version of `subprocess.Popen`
         # doesn't have a timeout option, so the required
@@ -68,12 +44,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 +63,71 @@ 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
 
 
+if LLDB:
+    INFERIOR_ARGS = '--'
+    LOAD_EXTENSION = 'command script import ' + EXTENSION
+    PROCESS_RUN = (
+        # Prevent errors in case when running tests in Docker.
+        'settings set target.disable-aslr false\n'
+        'process launch'
+    )
+    # Don't run any initialization scripts.
+    RUN_CMD_FILE = [
+        '--batch',
+        '--no-lldbinit',
+        '--no-use-colors',
+        '--source-quietly',
+        '--source'
+    ]
+    SET_EXEC = 'target create ' + LUAJIT_BINARY
+    SET_RUN_ARGS = 'settings set target.run-args'
+
+    def execute_process(cmd, timeout=TIMEOUT):
+        # While executing extension commands LLDB might produce
+        # errors that cannot be caught in 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, but is not able to
+        # "cancel" the error message which might fail tests in
+        # this case.
+        #
+        # List of regex that specifies lines to be wiped out from
+        # the LLDB output. In case additional cleaning is needed,
+        # just append this list with the correponding regex (use
+        # as strict regex as possible in order to avoid accidental
+        # removing of relevant data).
+        RX_LINES_TO_REMOVE = [
+            # This error occurs while parsing `union FPRCBArg` (it
+            # looks like either offset of `f`` field or size of
+            # `union FPRCBArg` is identified incorrectly).
+            r".*DW_TAG_member 'f' refers to type \w+ which extends beyond.*",
+        ]
+        raw_out = execute_process_raw(cmd, timeout)
+        return re.sub(r'^({})\n'.format('|'.join(RX_LINES_TO_REMOVE)),
+                      '', raw_out, flags=re.M)
+
+else:
+    # GDB.
+    INFERIOR_ARGS = '--args'
+    LOAD_EXTENSION = 'source ' + EXTENSION
+    PROCESS_RUN = 'run'
+    # Don't run any initialization scripts.
+    RUN_CMD_FILE = ['--batch', '--nx', '--quiet', '--command']
+    SET_EXEC = 'file ' + LUAJIT_BINARY
+    SET_RUN_ARGS = 'set args'
+    execute_process = execute_process_raw
+
 IS_DUALNUM = execute_process([
     LUAJIT_BINARY, '-e', "print(require('ffi').abi('dualnum'))"
 ]).strip() == 'true'
@@ -129,42 +160,38 @@ else:
 
 class TestCaseBase(unittest.TestCase):
     @classmethod
-    def construct_cmds(cls):
-        return '\n'.join([
+    def construct_cmds(cls, deferred, *run_args):
+        cmds = [
+            SET_EXEC,
+            SET_RUN_ARGS + ' ' + ' '.join(run_args),
             'b {loc}'.format(loc=cls.location),
             PROCESS_RUN,
             'n',
-            LOAD_EXTENSION,
             cls.extension_cmds.strip(),
-            'q',
-        ])
+        ]
+        cmds.insert(0 if deferred else 1, LOAD_EXTENSION)
+        return '\n'.join(cmds)
 
-    @classmethod
-    def setUpClass(cls):
-        cmd_file = persist(cls.construct_cmds())
-        script_file = persist(cls.lua_script)
+    def check(self, deferred=False):
+        script_file = persist(self.lua_script)
+        cmd_file = persist(self.construct_cmds(deferred, script_file.name))
         process_cmd = [
             DEBUGGER,
             *RUN_CMD_FILE,
             cmd_file.name,
-            INFERIOR_ARGS,
-            LUAJIT_BINARY,
-            script_file.name,
         ]
         if TEST_VERBOSE:
-            print('# Test name: {}'.format(cls.__name__))
+            print('# Test name: {}'.format(self.__class__.__name__))
             print('# Test command: {}'.format(' '.join(process_cmd)))
-        cls.output = execute_process(process_cmd)
+        output = execute_process(process_cmd)
         if TEST_VERBOSE:
-            print('# Command output:\n{}'.format(cls.output))
+            print('# Command output:\n{}'.format(output))
         cmd_file.close()
         script_file.close()
-
-    def check(self):
         if LEGACY:
-            self.assertRegexpMatches(self.output, self.pattern.strip())
+            self.assertRegexpMatches(output, self.pattern.strip())
         else:
-            self.assertRegex(self.output, self.pattern.strip())
+            self.assertRegex(output, self.pattern.strip())
 
 
 # Test that the emitted debug information supports macro
@@ -1051,8 +1078,65 @@ 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()
+
+
+class TestMissingArgLJFunc(TestMissingArgBase):
+    cmd_name = 'lj-func'
+
+
+class TestMissingArgLJTValue(TestMissingArgBase):
+    cmd_name = 'lj-tv'
+
+
+class TestMissingArgLJBC(TestMissingArgBase):
+    cmd_name = 'lj-bc'
+
+
+class TestMissingArgLJStr(TestMissingArgBase):
+    cmd_name = 'lj-str'
+
+
+class TestMissingArgLJTable(TestMissingArgBase):
+    cmd_name = 'lj-tab'
+
+
+class TestMissingArgLJProto(TestMissingArgBase):
+    cmd_name = 'lj-proto'
+
+
+class TestMissingArgLJGCO(TestMissingArgBase):
+    cmd_name = 'lj-gco'
+
+
+class TestMissingArgLJCType(TestMissingArgBase):
+    cmd_name = 'lj-ctype'
+
+
+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()
+    test_cls.test_with_deferred_loading = \
+        unittest.skipIf(LLDB, "not supported for LLDB")(
+            lambda self: self.check(True)
+        )
 
 if __name__ == '__main__':
     unittest.main(verbosity=2)
--------------rT54GruQV4VoO1hiIqKd5LBr--