gdbstub: Allow late attachment
PATCH v4 3/9 gdbstub: Try unlinking the unix socket before binding
In reply to Ilya LeoshkevichIn case an emulated process execve()s another emulated process, bind() will fail, because the socket already exists. So try deleting it. Use the existing unix_listen() function which does this.
Note that it is not possible to handle this in do_execv(): deleting gdbserver_user_state.socket_path before safe_execve() is not correct, because the latter may fail, and afterwards we may lose control.
--- gdbstub/user.c | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-)
gdbstub/user.c +5 -19
@@ -10,6 +10,7 @@*/ #include "qemu/osdep.h" +#include "qapi/error.h" #include "qemu/bitops.h" #include "qemu/cutils.h" #include "qemu/sockets.h"
@@ -317,9 +318,9 @@ static bool gdb_accept_socket(int gdb_fd)static int gdbserver_open_socket (const char *path) {g_autoptr (GString) buf =g_string_new ("" ); -struct sockaddr_un sockaddr = {};char *pid_placeholder; -int fd, ret; +Error *err =NULL ; +int fd; pid_placeholder =strstr (path,"%d" );if (pid_placeholder !=NULL ) {
@@ -329,24 +330,9 @@ static int gdbserver_open_socket(const char *path) path = buf->str; } - fd =socket (AF_UNIX ,SOCK_STREAM ,0 ); + fd =unix_listen (path, &err);if (fd <0 ) { -perror ("create socket" ); -return -1 ; - } - - sockaddr.sun_family =AF_UNIX ; -pstrcpy (sockaddr.sun_path,sizeof (sockaddr.sun_path) -1 , path); - ret =bind (fd, (struct sockaddr *)&sockaddr,sizeof (sockaddr)); -if (ret <0 ) { -perror ("bind socket" ); -close (fd); -return -1 ; - } - ret =listen (fd,1 ); -if (ret <0 ) { -perror ("listen socket" ); -close (fd); +warn_report_err (err);return -1 ; }
Signature · 1 line
2.47.1
PATCH v4 5/9 user: Introduce host_interrupt_signal
In reply to Ilya LeoshkevichAttaching to the gdbstub of a running process requires stopping its threads. For threads that run on a CPU, cpu_exit() is enough, but the only way to grab attention of a thread that is stuck in a long-running syscall is to interrupt it with a signal.
Reserve a host realtime signal for this, just like it's already done for TARGET_SIGABRT on Linux. This may reduce the number of available guest realtime signals by one, but this is acceptable, since there are quite a lot of them, and it's unlikely that there are apps that need them all.
Set signal_pending for the safe_sycall machinery to prevent invoking the syscall. This is a lie, since we don't queue a guest signal, but process_pending_signals() can handle the absence of pending signals. The syscall returns with QEMU_ERESTARTSYS errno, which arranges for the automatic restart. This is important, because it helps avoiding disturbing poorly written guests.
--- bsd-user/signal.c | 12 ++++++++++++ include/user/signal.h | 2 ++ linux-user/signal.c | 25 ++++++++++++++++++++----- 3 files changed, 34 insertions(+), 5 deletions(-)
bsd-user/signal.c +12 -0
@@ -51,6 +51,8 @@ static inline int sas_ss_flags(TaskState *ts, unsigned long sp)on_sig_stack (ts, sp) ?SS_ONSTACK :0 ; } +int host_interrupt_signal =SIGRTMAX ; +/* * The BSD ABIs use the same signal numbers across all the CPU architectures, so * (unlike Linux) these functions are just the identity mapping. This might not
@@ -491,6 +493,12 @@ static void host_signal_handler(int host_sig, siginfo_t *info, void *puc)uintptr_t pc =0 ;bool sync_sig = false; +if (host_sig == host_interrupt_signal) { + ts->signal_pending =1 ; +cpu_exit (thread_cpu); +return ; + } +/* * Non-spoofed SIGSEGV and SIGBUS are synchronous, and need special * handling wrt signal blocking and unwinding.
@@ -854,6 +862,9 @@ void signal_init(void)for (i =1 ; i <=TARGET_NSIG ; i++) { host_sig =target_to_host_signal (i); +if (host_sig == host_interrupt_signal) { +continue ; + }sigaction (host_sig,NULL , &oact);if (oact.sa_sigaction == (void *)SIG_IGN ) { sigact_table[i -1 ]._sa_handler =TARGET_SIG_IGN ;
@@ -872,6 +883,7 @@ void signal_init(void)sigaction (host_sig, &act,NULL ); } } +sigaction (host_interrupt_signal, &act,NULL ); } static void handle_pending_signal(CPUArchState *env, int sig,
include/user/signal.h +2 -0
@@ -20,4 +20,6 @@*/ int target_to_host_signal (int sig); +extern int host_interrupt_signal; +#endif
linux-user/signal.c +20 -5
@@ -517,6 +517,8 @@ static int core_dump_signal(int sig) } } +int host_interrupt_signal; +static void signal_table_init (const char *rtsig_map) {int hsig, tsig, count;
@@ -580,10 +582,10 @@ static void signal_table_init(const char *rtsig_map)* Attempts for configure "missing" signals via sigaction will be * silently ignored. * -* Reserve one signal for internal usage (see below). +* Reserve two signals for internal usage (see below). */ - hsig =SIGRTMIN +1 ; + hsig =SIGRTMIN +2 ;for (tsig =TARGET_SIGRTMIN ; hsig <=SIGRTMAX && tsig <=TARGET_NSIG ; hsig++, tsig++) {
@@ -604,12 +606,17 @@ static void signal_table_init(const char *rtsig_map) host_to_target_signal_table[SIGABRT ] =0 ;for (hsig =SIGRTMIN ; hsig <=SIGRTMAX ; hsig++) {if (!host_to_target_signal_table[hsig]) { - host_to_target_signal_table[hsig] =TARGET_SIGABRT ; -break ; +if (host_interrupt_signal) { + host_to_target_signal_table[hsig] =TARGET_SIGABRT ; +break ; + }else { + host_interrupt_signal = hsig; + } } }if (hsig >SIGRTMAX ) { -fprintf (stderr,"No rt signals left for SIGABRT mapping\n" ); +fprintf (stderr, +"No rt signals left for interrupt and SIGABRT mapping\n" );exit (EXIT_FAILURE ); }
@@ -689,6 +696,8 @@ void signal_init(const char *rtsig_map) } sigact_table[tsig -1 ]._sa_handler = thand; } + +sigaction (host_interrupt_signal, &act,NULL ); }/* Force a synchronously taken signal. The kernel force_sig() function
@@ -1036,6 +1045,12 @@ static void host_signal_handler(int host_sig, siginfo_t *info, void *puc)bool sync_sig = false;void *sigmask; +if (host_sig == host_interrupt_signal) { + ts->signal_pending =1 ; +cpu_exit (thread_cpu); +return ; + } +/* * Non-spoofed SIGSEGV and SIGBUS are synchronous, and need special * handling wrt signal blocking and unwinding. Non-spoofed SIGILL,
Signature · 1 line
2.47.1
PATCH v4 7/9 gdbstub: Allow late attachment
In reply to Ilya LeoshkevichAllow debugging individual processes in multi-process applications by starting them with export QEMU_GDB=/tmp/qemu-%d.sock,suspend=n. Currently one would have to attach to every process to ensure the app makes progress.
In case suspend=n is not specified, the flow remains unchanged. If it is specified, then accepting the client connection is delegated to a thread. In the future this machinery may be reused for handling reconnections and interruptions.
On accepting a connection, the thread schedules gdb_handlesig() on the first CPU and wakes it up with host_interrupt_signal. Note that the result of this gdb_handlesig() invocation is handled, as opposed to many other existing call sites. These other call sites probably need to be fixed separately.
--- bsd-user/main.c | 1 - gdbstub/user.c | 118 ++++++++++++++++++++++++++++++++++++++++++---- linux-user/main.c | 1 - 3 files changed, 108 insertions(+), 12 deletions(-)
bsd-user/main.c +0 -1
@@ -629,7 +629,6 @@ int main(int argc, char **argv)if (gdbstub) {gdbserver_start (gdbstub); -gdb_handlesig (cpu,0 ,NULL ,NULL ,0 ); }cpu_loop (env);/* never exits */
gdbstub/user.c +108 -10
141 lines not on this page · raw message
linux-user/main.c +0 -1
@@ -1028,7 +1028,6 @@ int main(int argc, char **argv, char **envp) gdbstub);exit (EXIT_FAILURE ); } -gdb_handlesig (cpu,0 ,NULL ,NULL ,0 ); }#ifdef CONFIG_SEMIHOSTING
Signature · 1 line
2.47.1
v4 cover gdbstub: Allow late attachment
v3: https://lore.kernel.org/qemu-devel/[email protected]/
v3 -> v4: Rebase.
Add missing "\n"s to error messages.
Use unix_listen() (Alex).
Use qapi_bool_parse() and patch it to accept NULL (Alex). Remove a leftover include (Alex).
Rename port_or_path to path, set it to NULL after freeing (Alex).
v2: https://lore.kernel.org/qemu-devel/[email protected]/
v2 -> v3: Rebase.
Patches that need review:
- [PATCH 2/8] gdbstub: Try unlinking the unix socket before binding
- [PATCH 4/8] user: Introduce host_interrupt_signal # linux part
- [PATCH 6/8] gdbstub: Allow late attachment
- [PATCH 7/8] docs/user: Document the %d placeholder and suspend=n QEMU_GDB features
- [PATCH 8/8] tests/tcg: Add late gdbstub attach test
v1: https://lore.kernel.org/qemu-devel/[email protected]/
v1 -> v2: Rebase, fix conflicts with the QEMU_RTSIG_MAP patch.
Use qemu_get_thread_id() for %d (Helge, Richard, Warner). Add R-bs, except for the Richard's one on 4/8, since conflict resolution caused a noticeable change.
Hi,
This series adds the ability to attach GDB to a running qemu-user instance. This is useful for debugging multi-process apps.
Patches 1 and 2 implement a small related feature: the ability to create individual UNIX sockets for each child process.
Patches 3-5 add the required infrastructure. In particular, we need to reserve a host signal for waking up threads, as discussed in [1]. By the way, the problem with atomicity of checking for pending signals and invoking syscalls that I'm describing in that thread seems to have already been solved by the safe_syscall infrastructure, so the changes are fairly simple.
If this series is accepted, I will rebase the all-stop series on top of it.
Patch 6 is the implementation, patch 7 is a documentation update, patch 8 is a test. I tested this series on Linux and only compile-tested on the BSDs.
Best regards,
Ilya
Ilya Leoshkevich (9):
qapi: Make qapi_bool_parse() gracefully handle NULL value
gdbstub: Allow the %d placeholder in the socket path
gdbstub: Try unlinking the unix socket before binding
user: Introduce user/signal.h
user: Introduce host_interrupt_signal
osdep: Introduce qemu_kill_thread()
gdbstub: Allow late attachment
docs/user: Document the %d placeholder and suspend=n QEMU_GDB features tests/tcg: Add late gdbstub attach test
bsd-user/main.c | 1 - bsd-user/signal-common.h | 1 - bsd-user/signal.c | 13 ++ docs/user/main.rst | 16 ++- gdbstub/user.c | 150 +++++++++++++++++---- include/qemu/osdep.h | 9 ++ include/user/signal.h | 25 ++++ linux-user/main.c | 1 - linux-user/signal-common.h | 1 - linux-user/signal.c | 26 +++- linux-user/syscall.c | 1 + qapi/qapi-util.c | 16 +-- tests/guest-debug/run-test.py | 15 ++- tests/tcg/multiarch/Makefile.target | 9 +- tests/tcg/multiarch/gdbstub/late-attach.py | 28 ++++ tests/tcg/multiarch/late-attach.c | 41 ++++++ util/oslib-posix.c | 15 +++ 17 files changed, 317 insertions(+), 51 deletions(-) create mode 100644 include/user/signal.h create mode 100644 tests/tcg/multiarch/gdbstub/late-attach.py create mode 100644 tests/tcg/multiarch/late-attach.c
Signature · 1 line
2.47.1
PATCH v4 1/9 qapi: Make qapi_bool_parse() gracefully handle NULL value
Use g_strcmp0(), so that NULL is considered an invalid parameter value.
--- qapi/qapi-util.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)
qapi/qapi-util.c +8 -8
@@ -86,17 +86,17 @@ int qapi_enum_parse(const QEnumLookup *lookup, const char *buf,bool qapi_bool_parse (const char *name,const char *value,bool *obj,Error **errp) { -if (g_str_equal (value,"on" ) || -g_str_equal (value,"yes" ) || -g_str_equal (value,"true" ) || -g_str_equal (value,"y" )) { +if (!g_strcmp0 (value,"on" ) || + !g_strcmp0 (value,"yes" ) || + !g_strcmp0 (value,"true" ) || + !g_strcmp0 (value,"y" )) { *obj = true;return true; } -if (g_str_equal (value,"off" ) || -g_str_equal (value,"no" ) || -g_str_equal (value,"false" ) || -g_str_equal (value,"n" )) { +if (!g_strcmp0 (value,"off" ) || + !g_strcmp0 (value,"no" ) || + !g_strcmp0 (value,"false" ) || + !g_strcmp0 (value,"n" )) { *obj = false;return true; }
Signature · 1 line
2.47.1
PATCH v4 4/9 user: Introduce user/signal.h
In reply to Ilya Leoshkevichgdbstub needs target_to_host_signal(), so move its declaration to a public header.
--- bsd-user/signal-common.h | 1 - bsd-user/signal.c | 1 + include/user/signal.h | 23 +++++++++++++++++++++++ linux-user/signal-common.h | 1 - linux-user/signal.c | 1 + linux-user/syscall.c | 1 + 6 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 include/user/signal.h
bsd-user/signal-common.h +0 -1
@@ -42,7 +42,6 @@ void process_pending_signals(CPUArchState *env);void queue_signal (CPUArchState *env,int sig,int si_type,target_siginfo_t *info);void signal_init (void ); -int target_to_host_signal (int sig);void target_to_host_sigset (sigset_t *d,const target_sigset_t *s);/*
bsd-user/signal.c +1 -0
@@ -24,6 +24,7 @@#include "user/cpu_loop.h" #include "exec/page-protection.h" #include "user/page-protection.h" +#include "user/signal.h" #include "user/tswap-target.h" #include "gdbstub/user.h" #include "signal-common.h"
include/user/signal.h new file +23 -0
@@ -0,0 +1,23 @@ +/* +* Signal-related declarations. +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ +#ifndef USER_SIGNAL_H +#define USER_SIGNAL_H + +#ifndef CONFIG_USER_ONLY +#error Cannot include this header from system emulation +#endif + +/** +* target_to_host_signal: +* @sig: target signal. +* +* On success, return the host signal between 0 (inclusive) and NSIG +* (exclusive) corresponding to the target signal @sig. Return any other value +* on failure. +*/ +int target_to_host_signal (int sig); + +#endif
linux-user/signal-common.h +0 -1
@@ -61,7 +61,6 @@ void queue_signal(CPUArchState *env, int sig, int si_type, target_siginfo_t *info);void host_to_target_siginfo (target_siginfo_t *tinfo,const siginfo_t *info);void target_to_host_siginfo (siginfo_t *info,const target_siginfo_t *tinfo); -int target_to_host_signal (int sig);int host_to_target_signal (int sig);long do_sigreturn (CPUArchState *env);long do_rt_sigreturn (CPUArchState *env);
linux-user/signal.c +1 -0
@@ -36,6 +36,7 @@#include "user/cpu_loop.h" #include "user/page-protection.h" #include "user/safe-syscall.h" +#include "user/signal.h" #include "tcg/tcg.h" /* target_siginfo_t must fit in gdbstub's siginfo save area. */
linux-user/syscall.c +1 -0
@@ -138,6 +138,7 @@#include "user-mmap.h" #include "user/page-protection.h" #include "user/safe-syscall.h" +#include "user/signal.h" #include "qemu/guest-random.h" #include "qemu/selfmap.h" #include "user/syscall-trace.h"
Signature · 1 line
2.47.1
PATCH v4 9/9 tests/tcg: Add late gdbstub attach test
In reply to Ilya LeoshkevichAdd a small test to prevent regressions.
Make sure that host_interrupt_signal is not visible to the guest.
--- tests/guest-debug/run-test.py | 15 ++++++-- tests/tcg/multiarch/Makefile.target | 9 ++++- tests/tcg/multiarch/gdbstub/late-attach.py | 28 +++++++++++++++ tests/tcg/multiarch/late-attach.c | 41 ++++++++++++++++++++++ 4 files changed, 90 insertions(+), 3 deletions(-) create mode 100644 tests/tcg/multiarch/gdbstub/late-attach.py create mode 100644 tests/tcg/multiarch/late-attach.c
tests/guest-debug/run-test.py +13 -2
@@ -36,6 +36,8 @@ def get_args(): parser.add_argument("--gdb-args", help="Additional gdb arguments") parser.add_argument("--output", help="A file to redirect output to") parser.add_argument("--stderr", help="A file to redirect stderr to") + parser.add_argument("--no-suspend", action="store_true", + help="Ask the binary to not wait for GDB connection") return parser.parse_args()
@@ -73,10 +75,19 @@ def log(output, msg): # Launch QEMU with binary if "system" in args.qemu: + if args.no_suspend: + suspend = '' + else: + suspend = ' -S' cmd = f'{args.qemu} {args.qargs} {args.binary}' \ - f' -S -gdb unix:path={socket_name},server=on' + f'{suspend} -gdb unix:path={socket_name},server=on' else: - cmd = f'{args.qemu} {args.qargs} -g {socket_name} {args.binary}' + if args.no_suspend: + suspend = ',suspend=n' + else: + suspend = '' + cmd = f'{args.qemu} {args.qargs} -g {socket_name}{suspend}' \ + f' {args.binary}' log(output, "QEMU CMD: %s" % (cmd)) inferior = subprocess.Popen(shlex.split(cmd))
tests/tcg/multiarch/Makefile.target +8 -1
@@ -130,6 +130,13 @@ run-gdbstub-follow-fork-mode-parent: follow-fork-mode --bin $< --test $(MULTIARCH_SRC)/gdbstub/follow-fork-mode-parent.py, \ following parents on fork) +run-gdbstub-late-attach: late-attach + $(call run-test, $@, env LATE_ATTACH_PY=1 $(GDB_SCRIPT) \ + --gdb $(GDB) \ + --qemu $(QEMU) --qargs "$(QEMU_OPTS)" --no-suspend \ + --bin $< --test $(MULTIARCH_SRC)/gdbstub/late-attach.py, \ + attaching to a running process) + else run-gdbstub-%: $(call skip-test, "gdbstub test $*", "need working gdb with $(patsubst -%,,$(TARGET_NAME)) support")
@@ -139,7 +146,7 @@ EXTRA_RUNS += run-gdbstub-sha1 run-gdbstub-qxfer-auxv-read \ run-gdbstub-registers run-gdbstub-prot-none \ run-gdbstub-catch-syscalls run-gdbstub-follow-fork-mode-child \ run-gdbstub-follow-fork-mode-parent \ - run-gdbstub-qxfer-siginfo-read + run-gdbstub-qxfer-siginfo-read run-gdbstub-late-attach # ARM Compatible Semi Hosting Tests #
tests/tcg/multiarch/gdbstub/late-attach.py new file +28 -0
@@ -0,0 +1,28 @@ +"""Test attaching GDB to a running process. + +SPDX-License-Identifier: GPL-2.0-or-later +""" +from test_gdbstub import main, report + + +def run_test(): + """Run through the tests one by one""" + try: + phase = gdb.parse_and_eval("phase").string() + except gdb.error: + # Assume the guest did not reach main(). + phase = "start" + + if phase == "start": + gdb.execute("break sigwait") + gdb.execute("continue") + phase = gdb.parse_and_eval("phase").string() + report(phase == "sigwait", "{} == \"sigwait\"".format(phase)) + + gdb.execute("signal SIGUSR1") + + exitcode = int(gdb.parse_and_eval("$_exitcode")) + report(exitcode == 0, "{} == 0".format(exitcode)) + + +main(run_test)
tests/tcg/multiarch/late-attach.c new file +41 -0
41 lines not on this page · raw message
Signature · 1 line
2.47.1
PATCH v4 6/9 osdep: Introduce qemu_kill_thread()
In reply to Ilya LeoshkevichAdd a function for sending signals to individual threads. It does not make sense on Windows, so do not provide an implementation, so that if someone uses it by accident, they will get a linker error.
--- include/qemu/osdep.h | 9 +++++++++ util/oslib-posix.c | 15 +++++++++++++++ 2 files changed, 24 insertions(+)
include/qemu/osdep.h +9 -0
@@ -630,6 +630,15 @@ bool qemu_write_pidfile(const char *pidfile, Error **errp);int qemu_get_thread_id (void ); +/** +* qemu_kill_thread: +* @tid: thread id. +* @sig: host signal. +* +* Send @sig to one of QEMU's own threads with identifier @tid. +*/ +int qemu_kill_thread (int tid,int sig); + #ifndef CONFIG_IOVEC struct iovec { void *iov_base;
util/oslib-posix.c +15 -0
@@ -111,6 +111,21 @@ int qemu_get_thread_id(void)#endif } +int qemu_kill_thread (int tid,int sig) +{ +#if defined(__linux__) +return syscall (__NR_tgkill,getpid (), tid, sig); +#elif defined(__FreeBSD__) +return thr_kill2 (getpid (), tid, sig); +#elif defined(__NetBSD__) +return _lwp_kill (tid, sig); +#elif defined(__OpenBSD__) +return thrkill (tid, sig,NULL ); +#else +return kill (tid, sig); +#endif +} +int qemu_daemon (int nochdir,int noclose) {return daemon (nochdir, noclose);
Signature · 1 line
2.47.1
PATCH v4 2/9 gdbstub: Allow the %d placeholder in the socket path
In reply to Ilya LeoshkevichJust like for QEMU_LOG_FILENAME, replace %d with PID in the GDB socket path. This allows running multi-process applications with, e.g., export QEMU_GDB=/tmp/qemu-%d.sock. Currently this is not possible, since the first process will cause the subsequent ones to fail due to not being able to bind() the GDB socket.
--- gdbstub/user.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
gdbstub/user.c +10 -0
@@ -316,9 +316,19 @@ static bool gdb_accept_socket(int gdb_fd)static int gdbserver_open_socket (const char *path) { +g_autoptr (GString) buf =g_string_new ("" );struct sockaddr_un sockaddr = {}; +char *pid_placeholder;int fd, ret; + pid_placeholder =strstr (path,"%d" ); +if (pid_placeholder !=NULL ) { +g_string_append_len (buf, path, pid_placeholder - path); +g_string_append_printf (buf,"%d" ,qemu_get_thread_id ()); +g_string_append (buf, pid_placeholder +2 ); + path = buf->str; + } + fd =socket (AF_UNIX ,SOCK_STREAM ,0 );if (fd <0 ) {perror ("create socket" );
Signature · 1 line
2.47.1
PATCH v4 8/9 docs/user: Document the %d placeholder and suspend=n QEMU_GDB features
In reply to Ilya Leoshkevich--- docs/user/main.rst | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-)
docs/user/main.rst +13 -3
@@ -50,7 +50,7 @@ Command line options :: - qemu-i386 [-h] [-d] [-L path] [-s size] [-cpu model] [-g port] [-B offset] [-R size] program [arguments...] + qemu-i386 [-h] [-d] [-L path] [-s size] [-cpu model] [-g endpoint] [-B offset] [-R size] program [arguments...] ``-h`` Print the help
@@ -87,8 +87,18 @@ Debug options: Activate logging of the specified items (use '-d help' for a list of log items) -``-g port`` - Wait gdb connection to port +``-g endpoint`` + Wait gdb connection to a port (e.g., ``1234``) or a unix socket (e.g., + ``/tmp/qemu.sock``). + + If a unix socket path contains single ``%d`` placeholder (e.g., + ``/tmp/qemu-%d.sock``), it is replaced by the emulator PID, which is useful + when passing this option via the ``QEMU_GDB`` environment variable to a + multi-process application. + + If the endpoint address is followed by ``,suspend=n`` (e.g., + ``1234,suspend=n``), then the emulated program starts without waiting for a + connection, which can be established at any later point in time. ``-one-insn-per-tb`` Run the emulation with one guest instruction per translation block.
Signature · 1 line
2.47.1
Re: [PATCH v4 1/9] qapi: Make qapi_bool_parse() gracefully handle NULL value
In reply to Ilya LeoshkevichQuoted 1 line · Ilya Leoshkevich
Use
g_strcmp0(), so that NULL is considered an invalid parameter value.
Why are we calling qapi_bool_parse with a NULL value in the first place ? IMHO this is a sign of a bug higher up the call chain that ought to be fixed, as in general all our input parsing code would expect non-NULL input values.
Quoted 41 lines
Suggested-by Alex Bennée <[email protected]>Signed-off-by Ilya Leoshkevich <[email protected]>--- qapi/qapi-util.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)qapi/qapi-util.c +8
-8@@ -86,17 +86,17 @@ int qapi_enum_parse(const QEnumLookup *lookup, const char *buf,bool qapi_bool_parse (const char *name,const char *value,bool *obj,Error **errp) { -if (g_str_equal (value,"on" ) || -g_str_equal (value,"yes" ) || -g_str_equal (value,"true" ) || -g_str_equal (value,"y" )) { +if (!g_strcmp0 (value,"on" ) || + !g_strcmp0 (value,"yes" ) || + !g_strcmp0 (value,"true" ) || + !g_strcmp0 (value,"y" )) { *obj = true;return true; } -if (g_str_equal (value,"off" ) || -g_str_equal (value,"no" ) || -g_str_equal (value,"false" ) || -g_str_equal (value,"n" )) { +if (!g_strcmp0 (value,"off" ) || + !g_strcmp0 (value,"no" ) || + !g_strcmp0 (value,"false" ) || + !g_strcmp0 (value,"n" )) { *obj = false;return true; }Signature · 1 line
2.47.1
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|
Re: [PATCH v4 1/9] qapi: Make qapi_bool_parse() gracefully handle NULL value
Quoted 8 lines · Daniel P. Berrangé
Quoted 2 lines · Ilya Leoshkevich
Use
g_strcmp0(), so that NULL is considered an invalid parameter value.Why are we calling
qapi_bool_parsewith a NULL value in the first place ? IMHO this is a sign of a bug higher up the call chain that ought to be fixed, as in general all our input parsing code would expect non-NULL input values.
The intended use case is the following (patch 7/9):
g_auto(GStrv) tokens = g_strsplit(*arg, "=", 2);
Error *err = NULL;
if (g_strcmp0(tokens[0], "suspend") == 0) {
if (!qapi_bool_parse(tokens[0], tokens[1], &suspend, &err)) {
warn_report_err(err);
[...]The idea is to uniformly handle "suspend=y", "suspend=invalid" and "suspend"; the latter requires checking whether token[1] is NULL. Of course, this can be special-cased in the caller, but this would be less elegant.
[...]
Quoted 1 line
Re: [PATCH v4 1/9] qapi: Make qapi_bool_parse() gracefully handle NULL value
Quoted 20 lines · Ilya Leoshkevich
Quoted 8 lines · Daniel P. Berrangé
Quoted 2 lines · Ilya Leoshkevich
Use
g_strcmp0(), so that NULL is considered an invalid parameter value.Why are we calling
qapi_bool_parsewith a NULL value in the first place ? IMHO this is a sign of a bug higher up the call chain that ought to be fixed, as in general all our input parsing code would expect non-NULL input values.The intended use case is the following (patch 7/9):
g_auto(GStrv) tokens = g_strsplit(*arg, "=", 2); Error *err = NULL; if (g_strcmp0(tokens[0], "suspend") == 0) { if (!qapi_bool_parse(tokens[0], tokens[1], &suspend, &err)) { warn_report_err(err); [...]
Quoted 4 lines
The idea is to uniformly handle "suspend=y", "suspend=invalid" and "suspend"; the latter requires checking whether token[1] is NULL. Of course, this can be special-cased in the caller, but this would be less elegant.
On the contrary, I think handling the latter in the caller explicitly is the correct approach.
As written this code snippet gives readers the misleading impression that 'tokens[1]' is expected to be a non-NULL bool value. It is not at all obvious that the code is intentionally trying to support a NULL value for tokens[1]. Even if we can see that qapi_bool_parse accepts NULL, a reader has no idea whether this caller has intentionally passed NULL or simply forgot to raise an error when NULL is seen.
IMHO this patch should be dropped, and the desired behaviour made explicit in patch 7.
With regards,
Daniel
Signature · 3 lines
|: https://berrange.com -o- https://www.flickr.com/photos/dberrange :| |: https://libvirt.org -o- https://fstop138.berrange.com :| |: https://entangle-photo.org -o- https://www.instagram.com/dberrange :|