From 95e63238386524e231fcd100b9e6db22053fd4ff Mon Sep 17 00:00:00 2001 From: Namhyung Kim Date: Wed, 1 Jul 2026 12:41:49 -0700 Subject: [PATCH] perf kvm: Check kvm_need_default_arch_event() early There's a subtle issue with option parsing in perf record. It calls the function with PARSE_OPT_STOP_AT_NON_OPTION so that it can pass later options to the external command it runs. But perf kvm record passes the default arch events after the argv. So if user calls it with command, then it passes the event to the external command and fails it like below: $ sudo perf kvm --host record sleep 1 sleep: invalid option -- 'e' Try 'sleep --help' for more information. [ perf record: Woken up 1 times to write data ] [ perf record: Captured and wrote 0.046 MB perf.data.kvm (5 samples) ] We can check if the default options are needed before passing the extra command line to make sure it's passed to perf record. Tested-by: Ian Rogers Signed-off-by: Namhyung Kim --- tools/perf/builtin-kvm.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/tools/perf/builtin-kvm.c b/tools/perf/builtin-kvm.c index 2f00cc1fd1c7..24576e4ebb02 100644 --- a/tools/perf/builtin-kvm.c +++ b/tools/perf/builtin-kvm.c @@ -1996,13 +1996,14 @@ static int __cmd_record(const char *file_name, int argc, const char **argv) { int rec_argc, i = 0, j, ret; const char **rec_argv; + int need_arch_event = !!kvm_need_default_arch_event(EM_HOST, argc, argv); /* * Besides the 2 more options "-o" and "filename", * kvm_add_default_arch_event() may add 2 extra options, - * so allocate 4 more items. + * so allocate more items conditionally. */ - rec_argc = argc + 2 + 2; + rec_argc = argc + 2 + (2 * need_arch_event); rec_argv = calloc(rec_argc + 1, sizeof(char *)); if (!rec_argv) return -ENOMEM; @@ -2010,22 +2011,22 @@ static int __cmd_record(const char *file_name, int argc, const char **argv) rec_argv[i++] = STRDUP_FAIL_EXIT("record"); rec_argv[i++] = STRDUP_FAIL_EXIT("-o"); rec_argv[i++] = STRDUP_FAIL_EXIT(file_name); - for (j = 1; j < argc; j++, i++) - rec_argv[i] = STRDUP_FAIL_EXIT(argv[j]); - - BUG_ON(i + 2 != rec_argc); - - if (kvm_need_default_arch_event(EM_HOST, argc, argv)) { + if (need_arch_event) { ret = kvm_add_default_arch_event(EM_HOST, &i, rec_argv); if (ret) goto EXIT; } + for (j = 1; j < argc; j++, i++) + rec_argv[i] = STRDUP_FAIL_EXIT(argv[j]); + + BUG_ON(i != rec_argc); + ret = cmd_record(i, rec_argv); EXIT: - for (i = 0; i < rec_argc; i++) - free((void *)rec_argv[i]); + for (j = 0; j < i; j++) + free((void *)rec_argv[j]); free(rec_argv); return ret; }