From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mail-wm1-f45.google.com (mail-wm1-f45.google.com [209.85.128.45]) by sourceware.org (Postfix) with ESMTPS id 79223385B512 for ; Fri, 10 Feb 2023 23:36:14 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 79223385B512 Authentication-Results: sourceware.org; dmarc=none (p=none dis=none) header.from=palves.net Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=gmail.com Received: by mail-wm1-f45.google.com with SMTP id bg13-20020a05600c3c8d00b003d9712b29d2so7409947wmb.2 for ; Fri, 10 Feb 2023 15:36:14 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=E7QgBR7Pp+3CjkkoAGYNltQYV1K5gD6VOVnA4Fr/lDY=; b=DnJ7UwCSMtPZEvoJurP19q/UAYIplKT0JTvmu6Iumpvisep34NOc+sW0fuMiNxMk8D RIqsfDjFjHZTVHzAKKV4rJS1X1x4aUIIMlBEYRLxIm+B7J/3lHMV0/yhqdKKJX+xBFkT zzEc8odUToYdOwM+qB0TfREdLWsurwo1rFBFb2gSMeDZsvMuEJipcjhG7GH4SbaL+UOm Za6Dl6SEDw0Ro/xlxsT9snfYcqmgyYCzjp1xpVliQc68z+KCzGHkOPnQVpxU0OFZci+z NwM057wLv2xUXtYFPJEnsP2HFW2oB0lmKnqHPSPx5B/KqLgO00/HvPdZGvHHU7N3jwaA 12TQ== X-Gm-Message-State: AO0yUKWrUx9yu5m5LcTy1cyPXQH/FkwjUSJ1BRkJz41awR2OZmajR/iV K0m0MElEqbZ6vVZyQplJq0SNyTXYMAFK6g== X-Google-Smtp-Source: AK7set+vwijEgcZDgE8YYDoGxOizxQ9yDOxi1j345PuByKJkqIbSJfX147E8NWlG3VuDKACzf6rkhw== X-Received: by 2002:a05:600c:70a:b0:3d2:bca5:10a2 with SMTP id i10-20020a05600c070a00b003d2bca510a2mr13523476wmn.22.1676072172914; Fri, 10 Feb 2023 15:36:12 -0800 (PST) Received: from localhost ([2001:8a0:f92b:9e00::1fe]) by smtp.gmail.com with ESMTPSA id t15-20020a05600c328f00b003dc5b59ed7asm6076549wmp.11.2023.02.10.15.36.12 for (version=TLS1_3 cipher=TLS_AES_128_GCM_SHA256 bits=128/128); Fri, 10 Feb 2023 15:36:12 -0800 (PST) From: Pedro Alves To: gdb-patches@sourceware.org Subject: [PATCH 3/6] Add new "$_shell(CMD)" internal function Date: Fri, 10 Feb 2023 23:36:01 +0000 Message-Id: <20230210233604.2228450-4-pedro@palves.net> X-Mailer: git-send-email 2.36.0 In-Reply-To: <20230210233604.2228450-1-pedro@palves.net> References: <20230210233604.2228450-1-pedro@palves.net> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Spam-Status: No, score=-9.9 required=5.0 tests=BAYES_00,FREEMAIL_FORGED_FROMDOMAIN,FREEMAIL_FROM,GIT_PATCH_0,HEADER_FROM_DIFFERENT_DOMAINS,KAM_DMARC_STATUS,RCVD_IN_DNSWL_NONE,RCVD_IN_MSPIKE_H2,SPF_HELO_NONE,SPF_PASS,TXREP autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org List-Id: For testing a following patch, I wanted a way to send a SIGINT to GDB from a breakpoint condition. And I didn't want to do it from a Python breakpoint or Python function, as I wanted to exercise non-Python code paths. So I thought I'd add a new $_shell internal function, that runs a command under the shell, and returns the exit code. With this, I could write: (gdb) b foo if $_shell("kill -SIGINT $gdb_pid") != 0 || I think this is generally useful, hence I'm proposing it here. Here's the new function in action: (gdb) p $_shell("true") $1 = 0 (gdb) p $_shell("false") $2 = 1 (gdb) p $_shell("echo hello") hello $3 = 0 (gdb) p $_shell("foobar") bash: line 1: foobar: command not found $4 = 127 (gdb) help function _shell $_shell - execute a shell command and returns the result. Usage: $_shell (command) Returns the command's exit code: zero on success, non-zero otherwise. (gdb) NEWS and manual changes included. Change-Id: I7e36d451ee6b428cbf41fded415ae2d6b4efaa4e --- gdb/NEWS | 10 ++++ gdb/cli/cli-cmds.c | 89 ++++++++++++++++++++++++++++-- gdb/doc/gdb.texinfo | 47 ++++++++++++++++ gdb/testsuite/gdb.base/default.exp | 1 + gdb/testsuite/gdb.base/shell.exp | 36 ++++++++++++ 5 files changed, 179 insertions(+), 4 deletions(-) diff --git a/gdb/NEWS b/gdb/NEWS index b85923cf80d..0d3445438b1 100644 --- a/gdb/NEWS +++ b/gdb/NEWS @@ -56,6 +56,16 @@ maintenance info frame-unwinders List the frame unwinders currently in effect, starting with the highest priority. +* New convenience function "$_shell", to execute a shell command and + return the result. This lets you run shell commands in expressions. + Some examples: + + (gdb) p $_shell("true") + $1 = 0 + (gdb) p $_shell("false") + $2 = 1 + (gdb) break func if $_shell("some command") == 0 + * MI changes ** mi now reports 'no-history' as a stop reason when hitting the end of the diff --git a/gdb/cli/cli-cmds.c b/gdb/cli/cli-cmds.c index 6c0d780face..27fbfb035b3 100644 --- a/gdb/cli/cli-cmds.c +++ b/gdb/cli/cli-cmds.c @@ -39,6 +39,7 @@ #include "gdbsupport/filestuff.h" #include "location.h" #include "block.h" +#include "valprint.h" #include "ui-out.h" #include "interps.h" @@ -873,6 +874,9 @@ exit_status_set_internal_vars (int exit_status) clear_internalvar (var_code); clear_internalvar (var_signal); + + /* Keep the logic here in sync with shell_internal_fn. */ + if (WIFEXITED (exit_status)) set_internalvar_integer (var_code, WEXITSTATUS (exit_status)); #ifdef __MINGW32__ @@ -893,8 +897,11 @@ exit_status_set_internal_vars (int exit_status) warning (_("unexpected shell command exit status %d"), exit_status); } -static void -shell_escape (const char *arg, int from_tty) +/* Run ARG under the shell, and return the exit status. If ARG is + NULL, run an interactive shell. */ + +static int +run_under_shell (const char *arg, int from_tty) { #if defined(CANT_FORK) || \ (!defined(HAVE_WORKING_VFORK) && !defined(HAVE_WORKING_FORK)) @@ -915,7 +922,7 @@ shell_escape (const char *arg, int from_tty) the shell command we just ran changed it. */ chdir (current_directory); #endif - exit_status_set_internal_vars (rc); + return rc; #else /* Can fork. */ int status, pid; @@ -942,10 +949,21 @@ shell_escape (const char *arg, int from_tty) waitpid (pid, &status, 0); else error (_("Fork failed")); - exit_status_set_internal_vars (status); + return status; #endif /* Can fork. */ } +/* Escape out to the shell to run ARG. If ARG is NULL, launch and + interactive shell. Sets $_shell_exitcode and $_shell_exitsignal + convenience variables based on the exits status. */ + +static void +shell_escape (const char *arg, int from_tty) +{ + int status = run_under_shell (arg, from_tty); + exit_status_set_internal_vars (status); +} + /* Implementation of the "shell" command. */ static void @@ -2417,6 +2435,63 @@ gdb_maint_setting_str_internal_fn (struct gdbarch *gdbarch, return str_value_from_setting (*show_cmd->var, gdbarch); } +/* Implementation of the convenience function $_shell. */ + +static struct value * +shell_internal_fn (struct gdbarch *gdbarch, + const struct language_defn *language, + void *cookie, int argc, struct value **argv) +{ + if (argc != 1) + error (_("You must provide one argument for $_shell.")); + + value *val = argv[0]; + struct type *type = check_typedef (value_type (val)); + + if (!language->is_string_type_p (type)) + error (_("Argument must be a string.")); + + value_print_options opts; + get_no_prettyformat_print_options (&opts); + + string_file stream; + value_print (val, &stream, &opts); + + /* We should always have two quote chars, which we'll strip. */ + gdb_assert (stream.size () >= 2); + + /* Now strip them. We don't need the original string, so it's + cheaper to do it in place, avoiding a string allocation. */ + std::string str = stream.release (); + str[str.size () - 1] = 0; + const char *command = str.c_str () + 1; + + int exit_status = run_under_shell (command, 0); + + struct type *int_type = builtin_type (gdbarch)->builtin_int; + + /* Keep the logic here in sync with + exit_status_set_internal_vars. */ + + if (WIFEXITED (exit_status)) + return value_from_longest (int_type, WEXITSTATUS (exit_status)); +#ifdef __MINGW32__ + else if (WIFSIGNALED (exit_status) && WTERMSIG (exit_status) == -1) + { + /* See exit_status_set_internal_vars. */ + return value_from_longest (int_type, exit_status); + } +#endif + else if (WIFSIGNALED (exit_status)) + { + /* (0x80 | SIGNO) is what most (all?) POSIX-like shells set as + exit code on fatal signal termination. */ + return value_from_longest (int_type, 0x80 | WTERMSIG (exit_status)); + } + else + return allocate_optimized_out_value (int_type); +} + void _initialize_cli_cmds (); void _initialize_cli_cmds () @@ -2606,6 +2681,12 @@ Some integer settings accept an unlimited value, returned\n\ as 0 or -1 depending on the setting."), gdb_maint_setting_internal_fn, NULL); + add_internal_function ("_shell", _("\ +$_shell - execute a shell command and return the result.\n\ +Usage: $_shell (command)\n\ +Returns the command's exit code: zero on success, non-zero otherwise."), + shell_internal_fn, NULL); + add_cmd ("commands", no_set_class, show_commands, _("\ Show the history of commands you typed.\n\ You can supply a command number to start with, or a `+' to start after\n\ diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo index 7b128053b5a..b2552173093 100644 --- a/gdb/doc/gdb.texinfo +++ b/gdb/doc/gdb.texinfo @@ -1629,6 +1629,10 @@ the default shell (@file{/bin/sh} on GNU and Unix systems, @file{cmd.exe} on MS-Windows, @file{COMMAND.COM} on MS-DOS, etc.). @end table +You may also invoke shell commands from expressions, using the +@code{$_shell} convenience function. @xref{$_shell convenience +function}. + The utility @code{make} is often needed in development environments. You do not have to use the @code{shell} command for this purpose in @value{GDBN}: @@ -12969,6 +12973,49 @@ Like the @code{$_gdb_setting_str} function, but works with Like the @code{$_gdb_setting} function, but works with @code{maintenance set} variables. +@anchor{$_shell convenience function} +@item $_shell (@var{command-string}) +@findex $_shell@r{, convenience function} + +Invoke a standard shell to execute @var{command-string}. Returns the +command's exit status. On Unix systems, a command which exits with a +zero exit status has succeeded, and non-zero exit status indicates +failure. When a command terminates on a fatal signal whose number is +N, @value{GDBN} uses the value 128+N as the exit status, as is +standard in Unix shells. The shell to run is determined in the same +way as for the @code{shell} command. @xref{Shell Commands, ,Shell +Commands}. The shell runs on the host machine, the machine +@value{GDBN} is running on. + +@smallexample +(@value{GDBP}) print $_shell("true") +$1 = 0 +(@value{GDBP}) print $_shell("false") +$2 = 1 +(@value{GDBP}) p $_shell("echo hello") +hello +$3 = 0 +(@value{GDBP}) p $_shell("foobar") +bash: line 1: foobar: command not found +$4 = 127 +@end smallexample + +This may also be useful in breakpoint conditions. For example: + +@smallexample +(@value{GDBP}) break function if $_shell("some command") == 0 +@end smallexample + +In this scenario, you'll want to make sure that the shell command you +run in the breakpoint condition takes the least amount of time +possible. This is important to minimize the time it takes to evaluate +the condition and re-resume the program if the condition turns out to +be false. + +Note: unlike the @code{shell} command, the @code{$_shell} convenience +function does not affect the @code{$_shell_exitcode} and +@code{$_shell_exitsignal} convenience variables. + @end table The following functions require @value{GDBN} to be configured with diff --git a/gdb/testsuite/gdb.base/default.exp b/gdb/testsuite/gdb.base/default.exp index d0789a64401..7e73db0576a 100644 --- a/gdb/testsuite/gdb.base/default.exp +++ b/gdb/testsuite/gdb.base/default.exp @@ -606,6 +606,7 @@ set show_conv_list \ {$_cimag = } \ {$_creal = } \ {$_isvoid = } \ + {$_shell = } \ {$_gdb_maint_setting_str = } \ {$_gdb_maint_setting = } \ {$_gdb_setting_str = } \ diff --git a/gdb/testsuite/gdb.base/shell.exp b/gdb/testsuite/gdb.base/shell.exp index 31cdcb41af5..ba1691ea2b0 100644 --- a/gdb/testsuite/gdb.base/shell.exp +++ b/gdb/testsuite/gdb.base/shell.exp @@ -41,6 +41,42 @@ if { ! [ishost *-*-mingw*] } { gdb_test "p \$_shell_exitsignal" " = 2" "shell interrupt exitsignal" } +# Test the $_shell convenience function. + +with_test_prefix "\$_shell convenience function" { + # Simple commands, check the result code. + gdb_test "p \$_shell(\"true\")" " = 0" + gdb_test "p \$_shell(\"false\")" " = 1" + + # Test command with arguments. + gdb_test "p \$_shell(\"echo foo\")" "foo\r\n\\$${decimal} = 0" + + # Check the type of the result. + gdb_test "ptype \$_shell(\"true\")" "type = int" + + # Test passing a non-literal string as command name. + gdb_test "p \$cmd = \"echo bar\"" " = \"echo bar\"" + gdb_test "p \$_shell(\$cmd)" "bar\r\n\\$${decimal} = 0" + + # Test executing a non-existing command. The result is + # shell-dependent, but most (all?) POSIX-like shells return 127 in + # this case. + gdb_test "p \$_shell(\"non-existing-command-foo-bar-qux\")" " = 127" + + gdb_test "p \$_shell" \ + " = " + gdb_test "ptype \$_shell" \ + "type = " + + # Test error scenarios. + gdb_test "p \$_shell()" \ + "You must provide one argument for \\\$_shell\\\." + gdb_test "p \$_shell(\"a\", \"b\")" \ + "You must provide one argument for \\\$_shell\\\." + gdb_test "p \$_shell(1)" \ + "Argument must be a string\\\." +} + # Define the user command "foo", used to test "pipe" command. gdb_test_multiple "define foo" "define foo" { -re "End with" { -- 2.36.0