From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from lists1p.gnu.org (lists1p.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-ECDSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id BE305606A322 for ; Thu, 3 Dec 2026 17:26:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.a=rsa-sha256 header.s=mimecast20190719 header.b=Q9p4vn0Y Received: from localhost ([::1] helo=lists1p.gnu.org) by lists1p.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1xZAZL-00033b-7i; Thu, 03 Dec 2026 12:26:07 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists1p.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1xZAZJ-000336-KV for qemu-devel@nongnu.org; Thu, 03 Dec 2026 12:26:05 -0500 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1xZAZG-0007eU-7W for qemu-devel@nongnu.org; Thu, 03 Dec 2026 12:26:05 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1796318762; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=6q1yw+zJHQACvqCm5ADiP2yOt1fBuRwVo4e3EtHWjMk=; b=Q9p4vn0Y0RmBG3ubl684YhsKEmkzZ3VvsgJl4nf8PmhJzvME31xxLfY3MuenVitzRXhaAn KuhDV0hPHi5jhCXSgXEGeIkRDc+yhZyvr4XCwby75HTzUk3kmbfLiVTJ5kBI/Kbf4Fw4tp pY5WhemMsqm73SjBvS4Vqf+fyJZ08BQ= Received: from mx-prod-mc-01.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-590-aZyBYf12Mk6ikE8IPJ5Jlw-1; Thu, 3 Dec 2026 17:25:57 +0000 X-MC-Unique: aZyBYf12Mk6ikE8IPJ5Jlw-1 X-Mimecast-MFC-AGG-ID: aZyBYf12Mk6ikE8IPJ5Jlw_1796318754 Received: from mx-prod-int-10.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-10.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.95]) (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 mx-prod-mc-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 40A661920A5C; Thu, 3 Dec 2026 17:25:54 +0000 (UTC) Received: from berrange.csb (headnet04.pony-001.prod.iad2.dc.redhat.com [10.2.32.116]) by mx-prod-int-10.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 1FEE7B95; Thu, 3 Dec 2026 17:25:51 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Cc: Markus Armbruster , "Dr. David Alan Gilbert" , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , Paolo Bonzini , =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= , Peter Maydell , Richard Henderson Subject: [PATCH 3/6] util: introduce a configurable message format template Date: Thu, 3 Dec 2026 17:25:40 +0000 Message-ID: <20261203172543.676434-4-berrange@redhat.com> In-Reply-To: <20261203172543.676434-1-berrange@redhat.com> References: <20261203172543.676434-1-berrange@redhat.com> X-Archived-By: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Scanned-By: MIMEDefang 3.6 on 10.30.177.95 Received-SPF: pass client-ip=170.10.133.124; envelope-from=berrange@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: 3 X-Spam_score: 0.3 X-Spam_bar: / X-Spam_report: (0.3 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.24, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_LOW=-0.7, RCVD_IN_MSPIKE_H3=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_SBL_CSS=3.335, SPF_HELO_PASS=-0.001, SPF_PASS=-0.001 autolearn=no autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: qemu development List-Archive: List-Post: List-Help: List-Subscribe: , Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org X-Spam-Status: No, score=-15.8 required=3.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,HEADER_FROM_DIFFERENT_DOMAINS, INCLUDES_CR_TRAILER,INCLUDES_PATCH,MAILING_LIST_MULTI,SPF_HELO_PASS, SPF_PASS autolearn=ham autolearn_force=no version=4.0.1 X-Spam-Checker-Version: SpamAssassin 4.0.1 (2024-03-26) on aws-us-west-2-korg-listserv-alma10-1 Currently error messages, generic log messages and chardev logs can all have a timestamp prepended, by using the '-msg' argument's 'timestamp' flag. There are various extra bits of information that are interesting to emit in various scenarios. Rather than adding many more flags to '-msg' and hardcoding the order they are emitted in, this introcuces a configuraable message format template. A format string template is a concatenation of the following components * literal string: text In the literal text, a '\' must be used to escape any '{', '}' or '\' characters. * a variable substition: {variablename} where variable name is one of: - 'timestamp': the ISO 8601 formatted current time - 'progname': the current program name - 'thread': the current thread name - 'tid': the thread ID - 'pid': the process ID - 'location': the current input location * an conditional expression {?{variablename}formatstring} {!{variablename}formatstring} which evaluates whether the variable is non-empty or empty respectively, and processes the nested format string. As example: "Demo {pid}{?{progname} (in program '}{progname}{?{progname}')}" Given a 'pid' value of '123' will print the following if progname is empty: "Demo 123" or, if the program name is the strnig 'qemu', will print: "Demo text (in program 'qemu')" Signed-off-by: Daniel P. Berrangé --- MAINTAINERS | 7 + include/qemu/message-format.h | 97 ++++++ tests/unit/meson.build | 1 + tests/unit/test-util-message-format.c | 226 +++++++++++++ util/meson.build | 1 + util/message-format.c | 449 ++++++++++++++++++++++++++ 6 files changed, 781 insertions(+) create mode 100644 include/qemu/message-format.h create mode 100644 tests/unit/test-util-message-format.c create mode 100644 util/message-format.c diff --git a/MAINTAINERS b/MAINTAINERS index a565919d3de..85949e91aff 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -3496,6 +3496,13 @@ F: scripts/coccinelle/remove_local_err.cocci F: scripts/coccinelle/use-error_fatal.cocci F: scripts/coccinelle/errp-guard.cocci +Message format +M: Daniel Berrangé +S: Supported +F: include/qemu/message-format.h +F: util/message-format.c +F: tests/unit/test-util-message-format.c + GDB stub M: Alex Bennée R: Philippe Mathieu-Daudé diff --git a/include/qemu/message-format.h b/include/qemu/message-format.h new file mode 100644 index 00000000000..4e38277d6cb --- /dev/null +++ b/include/qemu/message-format.h @@ -0,0 +1,97 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +#ifndef QEMU_MESSAGE_FORMAT_H +#define QEMU_MESSAGE_FORMAT_H + +#include "qapi/error.h" + + +typedef struct QMessageFormat QMessageFormat; + +typedef enum QMessageLevel { + QMESSAGE_LEVEL_DEBUG, + QMESSAGE_LEVEL_INFO, + QMESSAGE_LEVEL_WARN, + QMESSAGE_LEVEL_ERROR, + + QMESSAGE_LEVEL__MAX +} QMessageLevel; + +typedef void (*QMessageWriteFunc)(void *opaque, const char *buf, size_t len); + +/** + * qmessage_format_new_from_string: + * @formatstr: the message formatting specification + * @errp: NULL initialized pointer to an error object + * + * Create a new message format object by parsing the + * specification in @formatstr, which can contain a + * mixture of literal text and placeholders. A + * placeholder can either be a plain subsitution: + * + * {variablename} + * + * Or can have an prefix and suffix added, if-and-only-if + * the expanded variable has a value set. + * + * {?prefix{variablename}suffix} + * + * In either the literal text, or the prefix and suffix + * of a conditional placeholder, '\' can be used to + * escape the special meaning of '{', '}' and '\'. + * + * As example: + * + * "Demo {pid}{? (in program '{progname}')}" + * + * Given a 'pid' value of '123' will print + * + * "Demo 123" + * + * or, if the program name is available, will print: + * + * "Demo text (in program 'qemu')" + * + * Currently defined placeholders are: + * + * - 'timestamp': the ISO 8601 formatted current time + * - 'progname': the current program name + * - 'thread': the current thread name + * - 'tid': the thread ID + * - 'pid': the process ID + * - 'location': the current input location + * - 'guestname': the current guest name + * - 'level': the message level (debug, info, warning, error) + * - 'levelalt': as 'level' but no string printed for 'error' + * or 'debug' + * + * Returns: a new message format, or NULL on error + */ +QMessageFormat *qmessage_format_new_from_string(const char *formatstr, + Error **errp); + +/** + * qmessage_format_free: + * @format: the message format to free + * + * Free the message format + */ +void qmessage_format_free(QMessageFormat *format); + +/** + * qmessage_format_emit: + * @format: the message format to apply + * @level: the message level + * @writefn: the callback to write data with + * @opaque: data to provide to @writefn + * + * Emit a format string identified by @format to @writefn + */ +void qmessage_format_emit(QMessageFormat *format, + QMessageLevel level, + QMessageWriteFunc writefn, + void *opaque); + +G_DEFINE_AUTOPTR_CLEANUP_FUNC(QMessageFormat, qmessage_format_free); + +#endif /* QEMU_MESSAGE_H */ diff --git a/tests/unit/meson.build b/tests/unit/meson.build index 37b561d4a71..3951dfac844 100644 --- a/tests/unit/meson.build +++ b/tests/unit/meson.build @@ -50,6 +50,7 @@ tests = { 'test-interval-tree': [], 'test-fifo': [], 'test-envlist': [], + 'test-util-message-format': [], } if have_system or have_tools diff --git a/tests/unit/test-util-message-format.c b/tests/unit/test-util-message-format.c new file mode 100644 index 00000000000..403230ae56a --- /dev/null +++ b/tests/unit/test-util-message-format.c @@ -0,0 +1,226 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +#include "qemu/osdep.h" +#include "qemu/message-format.h" +#include "qemu/location.h" +#include "qemu/error-report.h" + + +/* + * functions we "mock" override to give predictable + * output for testing + */ +GDateTime *g_date_time_new_now_utc(void) +{ + return g_date_time_new_from_unix_utc(872835240); +} + + +static bool emptyprgname; +const char *g_get_prgname(void) +{ + return emptyprgname ? NULL : "skynet"; +} + + +int qemu_get_thread_id(void) +{ + return 1000; +} + + +int getpid(void) +{ + return 9003; +} + + +static void str_write(void *opaque, const char *buf, size_t len) +{ + GString *str = (GString *)opaque; + g_string_append_len(str, buf, len); +} + + +static void test_util_message_format_null(void) +{ + g_autoptr(GString) str = g_string_new(NULL); + g_autoptr(QMessageFormat) format = + qmessage_format_new_from_string(NULL, &error_abort); + + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + + g_assert_cmpstr(str->str, ==, ""); +} + + +static void test_util_message_format_empty(void) +{ + g_autoptr(GString) str = g_string_new(NULL); + g_autoptr(QMessageFormat) format = + qmessage_format_new_from_string("", &error_abort); + + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + + g_assert_cmpstr(str->str, ==, ""); +} + + +static void test_util_message_format_literal(void) +{ + g_autoptr(GString) str = g_string_new(NULL); + g_autoptr(QMessageFormat) format = + qmessage_format_new_from_string("Test", &error_abort); + + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + + g_assert_cmpstr(str->str, ==, "Test"); +} + + +static void test_util_message_format_variable(void) +{ + g_autoptr(GString) str = g_string_new(NULL); + g_autoptr(QMessageFormat) format = + qmessage_format_new_from_string("{progname}", &error_abort); + + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + + g_assert_cmpstr(str->str, ==, "skynet"); +} + + +static void test_util_message_format_expression(void) +{ + g_autoptr(GString) str = g_string_new(NULL); + g_autoptr(QMessageFormat) format = + qmessage_format_new_from_string( + "Test at {location}{?{location}: OK}{!{location} NOT OK}!", + &error_abort); + + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + loc_set_file("demo.c", 100); + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + loc_set_none(); + + g_assert_cmpstr(str->str, ==, + "Test at NOT OK!Test at demo.c:100: OK!"); +} + + +static void test_util_message_format_bad(void) +{ + const char *badformats[] = { + /* regular placeholder, no final closing '}' */ + "{message", + /* conditional placeholder, missing inner opening '{' */ + "{?message", + /* conditional placeholder, missing inner closing '}' */ + "{?some{message", + /* conditional placeholder, missing inner opening '{' */ + "{?some\\{message", + /* conditional placeholder, missing final closing '}' */ + "{?some{message}\\}", + /* conditional placeholder, missing final closing '}' */ + "{?some{message}some\\}", + }; + size_t i; + for (i = 0; i < G_N_ELEMENTS(badformats); i++) { + Error *local_err = NULL; + QMessageFormat *format; + g_test_message("Check '%s'", badformats[i]); + format = qmessage_format_new_from_string(badformats[i], &local_err); + g_assert(local_err != NULL); + g_assert(format == NULL); + error_free(local_err); + } +} + + +static void test_util_message_format_escapes(void) +{ + g_autoptr(GString) str = g_string_new(NULL); + g_autoptr(QMessageFormat) format = + qmessage_format_new_from_string( + "Test: {progname}{?{progname}\\\\\\}\\\\}!", &error_abort); + + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + + g_assert_cmpstr(str->str, ==, "Test: skynet\\}\\!"); +} + + +static void test_util_message_format_nested(void) +{ + g_autoptr(GString) str = g_string_new(NULL); + g_autoptr(QMessageFormat) format = + qmessage_format_new_from_string( + "{timestamp}: {progname}{?{progname}:" + "{!{location} }}{location}{?{location}: }OK", + &error_abort); + + emptyprgname = true; + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + loc_set_file("demo.c", 100); + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + loc_set_none(); + emptyprgname = false; + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + loc_set_file("demo.c", 100); + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + loc_set_none(); + + g_assert_cmpstr(str->str, ==, + "1997-08-29T06:14:00Z: OK" + "1997-08-29T06:14:00Z: demo.c:100: OK" + "1997-08-29T06:14:00Z: skynet: OK" + "1997-08-29T06:14:00Z: skynet:demo.c:100: OK"); +} + + +static void test_util_message_format_everything(void) +{ + g_autoptr(GString) str = g_string_new(NULL); + g_autoptr(QMessageFormat) format = + qmessage_format_new_from_string( + "{timestamp}: [{level}] {progname}:" + "{location}({pid}:[{thread}:{tid}]): {guestname}: OK", + &error_abort); + + loc_set_file("demo.c", 100); + error_guest_name = "t1000"; + qmessage_format_emit(format, QMESSAGE_LEVEL_DEBUG, str_write, str); + error_guest_name = NULL; + loc_set_none(); + + g_assert_cmpstr(str->str, ==, + "1997-08-29T06:14:00Z: [debug] " + "skynet:demo.c:100(9003:[main:1000]): t1000: OK"); +} + + +int main(int argc, char **argv) +{ + g_test_init(&argc, &argv, NULL); + + g_test_add_func("/util/message/format/null", + test_util_message_format_null); + g_test_add_func("/util/message/format/empty", + test_util_message_format_empty); + g_test_add_func("/util/message/format/literal", + test_util_message_format_literal); + g_test_add_func("/util/message/format/variable", + test_util_message_format_variable); + g_test_add_func("/util/message/format/expression", + test_util_message_format_expression); + g_test_add_func("/util/message/format/bad", + test_util_message_format_bad); + g_test_add_func("/util/message/format/escapes", + test_util_message_format_escapes); + g_test_add_func("/util/message/format/nested", + test_util_message_format_nested); + g_test_add_func("/util/message/format/everything", + test_util_message_format_everything); + + return g_test_run(); +} diff --git a/util/meson.build b/util/meson.build index 0982481177b..9e5caca2666 100644 --- a/util/meson.build +++ b/util/meson.build @@ -40,6 +40,7 @@ util_ss.add(files('bitmap.c', 'bitops.c')) util_ss.add(files('fifo8.c')) util_ss.add(files('cacheflush.c')) util_ss.add(files('location.c')) +util_ss.add(files('message-format.c')) util_ss.add(files('error.c', 'error-report.c')) util_ss.add(files('qemu-print.c')) util_ss.add(files('id.c')) diff --git a/util/message-format.c b/util/message-format.c new file mode 100644 index 00000000000..df081c5a8af --- /dev/null +++ b/util/message-format.c @@ -0,0 +1,449 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +#include "qemu/osdep.h" +#include "qemu/message-format.h" +#include "qemu/thread.h" +#include "qemu/location.h" +#include "qemu/error-report.h" + + +typedef enum QMessageFormatType { + QMESSAGE_FORMAT_TYPE_LITERAL, + QMESSAGE_FORMAT_TYPE_VARIABLE, + QMESSAGE_FORMAT_TYPE_EXPRESSION, +} QMessageFormatType; + +typedef enum QMessageFormatVariable { + QMESSAGE_FORMAT_VAR_UNKNOWN = -1, + QMESSAGE_FORMAT_VAR_TIMESTAMP, + QMESSAGE_FORMAT_VAR_PROGNAME, + QMESSAGE_FORMAT_VAR_THREAD, + QMESSAGE_FORMAT_VAR_TID, + QMESSAGE_FORMAT_VAR_PID, + QMESSAGE_FORMAT_VAR_LOCATION, + QMESSAGE_FORMAT_VAR_GUESTNAME, + QMESSAGE_FORMAT_VAR_LEVEL, + QMESSAGE_FORMAT_VAR_LEVELALT, +} QMessageFormatVariable; + +typedef struct QMessageFormatField { + QMessageFormatType type; + union { + char *literal; + QMessageFormatVariable variable; + struct { + QMessageFormatVariable variable; + bool negation; + QMessageFormat *format; + } expression; + } data; +} QMessageFormatField; + +struct QMessageFormat { + QMessageFormatField *fields; + size_t nfields; +}; + + +static QMessageFormatVariable +qmessage_format_variable_from_str(const char *formatstr, + const char *str, + Error **errp) +{ + if (g_str_equal(str, "timestamp")) { + return QMESSAGE_FORMAT_VAR_TIMESTAMP; + } else if (g_str_equal(str, "progname")) { + return QMESSAGE_FORMAT_VAR_PROGNAME; + } else if (g_str_equal(str, "thread")) { + return QMESSAGE_FORMAT_VAR_THREAD; + } else if (g_str_equal(str, "tid")) { + return QMESSAGE_FORMAT_VAR_TID; + } else if (g_str_equal(str, "pid")) { + return QMESSAGE_FORMAT_VAR_PID; + } else if (g_str_equal(str, "location")) { + return QMESSAGE_FORMAT_VAR_LOCATION; + } else if (g_str_equal(str, "guestname")) { + return QMESSAGE_FORMAT_VAR_GUESTNAME; + } else if (g_str_equal(str, "level")) { + return QMESSAGE_FORMAT_VAR_LEVEL; + } else if (g_str_equal(str, "levelalt")) { + return QMESSAGE_FORMAT_VAR_LEVELALT; + } + + error_setg(errp, "Unknown message format field '%s' in %s", + str, formatstr); + return QMESSAGE_FORMAT_VAR_UNKNOWN; +} + + +static char *qmessage_format_unescape_text(const char *text, + size_t textlen) +{ + size_t i, n; + bool escape = false; + char *rawtext = g_new0(char, textlen + 1); + for (i = 0, n = 0; i < textlen; i++) { + if (escape || text[i] != '\\') { + rawtext[n++] = text[i]; + escape = false; + } else { + escape = true; + } + } + rawtext[n] = '\0'; + rawtext = g_renew(char, rawtext, n + 1); + return rawtext; +} + + +static void qmessage_format_add_literal(QMessageFormat *format, + const char *text, + size_t textlen) +{ + format->fields = g_renew(QMessageFormatField, + format->fields, format->nfields + 1); + format->fields[format->nfields].type = QMESSAGE_FORMAT_TYPE_LITERAL; + format->fields[format->nfields].data.literal = + qmessage_format_unescape_text(text, textlen); + format->nfields++; +} + + +static void qmessage_format_add_variable(QMessageFormat *format, + QMessageFormatVariable variable) +{ + format->fields = g_renew(QMessageFormatField, + format->fields, format->nfields + 1); + format->fields[format->nfields].type = QMESSAGE_FORMAT_TYPE_VARIABLE; + format->fields[format->nfields].data.variable = variable; + format->nfields++; +} + + +static void qmessage_format_add_expression(QMessageFormat *format, + QMessageFormatVariable variable, + bool negation, + QMessageFormat *subformat) +{ + format->fields = g_renew(QMessageFormatField, + format->fields, format->nfields + 1); + format->fields[format->nfields].type = QMESSAGE_FORMAT_TYPE_EXPRESSION; + format->fields[format->nfields].data.expression.variable = variable; + format->fields[format->nfields].data.expression.negation = negation; + format->fields[format->nfields].data.expression.format = subformat; + format->nfields++; +} + + +static const char * +qmessage_format_end_of_literal(const char *formatstr, + const char *tmp, + char terminator, + Error **errp) +{ + bool escape = false; + while (1) { + if (escape) { + if (*tmp == '\0') { + error_setg(errp, + "Unterminated escape at and of format string '%s'", + formatstr); + return NULL; + } else if (*tmp != '\\' && *tmp != '{' && *tmp != '}') { + error_setg(errp, + "Unrecognised escape char '\\%c' in string '%s'", + *tmp, formatstr); + return NULL; + } + escape = false; + } else { + switch (*tmp) { + case '\\': + escape = true; + break; + case '{': + case '}': + case '\0': + return tmp; + } + } + tmp++; + } + g_assert_not_reached(); +} + + +static QMessageFormat * +qmessage_format_new_internal(const char *formatstr, + const char **tmpptr, + char terminator, + Error **errp) +{ + g_autoptr(QMessageFormat) format = g_new0(QMessageFormat, 1); + const char *tmp = *tmpptr; + + /* + * We're parsing 'formatstr' which can be a concatenation + * of any of the following + * + * a. literal text: + * + * text + * + * b. variable subsitution + * + * {variable} + * + * c. expression with literal text + * + * {?{variable}formatstr} + * {!{variable}formatstr} + * + * Literal 'text' can use '\' to escape '{', '}' or '\' + */ + + while (tmp && *tmp) { + const char *prev = tmp; + const char *start; + const char *end; + bool expression = false; + bool negation = false; + g_autofree char *varname = NULL; + QMessageFormatVariable variable; + + tmp = qmessage_format_end_of_literal(formatstr, tmp, '{', errp); + if (!tmp) { + return NULL; + } + if (tmp != prev) { + qmessage_format_add_literal(format, prev, tmp - prev); + } + if (*tmp == terminator) { + break; + } + if (*tmp != '{') { + error_setg(errp, "Unterminated format string '%s'", + formatstr); + return NULL; + } + + tmp++; /* skip over '{' */ + + if (*tmp == '?' || *tmp == '!') { + expression = true; + negation = *tmp == '!'; + + tmp++; /* skip over '?' / '!' */ + if (*tmp != '{') { + error_setg( + errp, + "Missing expression variable name in format string '%s'", + formatstr); + return NULL; + } + tmp++; /* skip over '{' */ + } + + start = tmp; + while (*tmp && *tmp != '}') { + if (!g_ascii_isalpha(*tmp)) { + error_setg( + errp, + "Non-alphanumeric variable name in format string '%s'", + formatstr); + return NULL; + } + tmp++; + } + end = strchr(tmp, '}'); + if (!end) { + error_setg(errp, + "Unterminated variable name in format string '%s'", + formatstr); + return NULL; + } + + varname = g_strndup(start, end - start); + tmp = end + 1; /* skip over variable name and '}' */ + variable = qmessage_format_variable_from_str(formatstr, varname, errp); + if (variable == QMESSAGE_FORMAT_VAR_UNKNOWN) { + return NULL; + } + + if (expression) { + QMessageFormat *subformat = + qmessage_format_new_internal(formatstr, &tmp, '}', errp); + if (!subformat) { + return NULL; + } + + tmp++; /* skip over '}' */ + qmessage_format_add_expression(format, variable, negation, + subformat); + } else { + qmessage_format_add_variable(format, variable); + } + } + + *tmpptr = tmp; + return g_steal_pointer(&format); +} + + +QMessageFormat *qmessage_format_new_from_string(const char *formatstr, + Error **errp) +{ + const char *tmp = formatstr; + return qmessage_format_new_internal(formatstr, &tmp, '\0', errp); +} + + +void qmessage_format_free(QMessageFormat *format) +{ + size_t i; + if (!format) { + return; + } + for (i = 0; i < format->nfields; i++) { + switch (format->fields[i].type) { + case QMESSAGE_FORMAT_TYPE_LITERAL: + g_free(format->fields[i].data.literal); + break; + case QMESSAGE_FORMAT_TYPE_EXPRESSION: + qmessage_format_free(format->fields[i].data.expression.format); + break; + default: + break; + } + } + g_free(format->fields); + g_free(format); +} + + +void qmessage_format_emit(QMessageFormat *format, + QMessageLevel level, + QMessageWriteFunc writefn, + void *opaque) +{ + size_t i; + +#define WRITE(str) \ + writefn(opaque, str, strlen(str)) + + for (i = 0; i < format->nfields; i++) { + QMessageFormatField *field = &(format->fields[i]); + bool empty = false; + + switch (field->type) { + case QMESSAGE_FORMAT_TYPE_LITERAL: + writefn(opaque, field->data.literal, + strlen(field->data.literal)); + break; + + case QMESSAGE_FORMAT_TYPE_VARIABLE: + switch (field->data.variable) { + case QMESSAGE_FORMAT_VAR_TIMESTAMP: + { + g_autoptr(GDateTime) dt = g_date_time_new_now_utc(); + g_autofree const char *timestr = g_date_time_format_iso8601(dt); + writefn(opaque, timestr, strlen(timestr)); + } break; + case QMESSAGE_FORMAT_VAR_PROGNAME: + { + const char *pgnamestr = g_get_prgname(); + if (pgnamestr) { + writefn(opaque, pgnamestr, strlen(pgnamestr)); + } + } break; + case QMESSAGE_FORMAT_VAR_THREAD: + { + const char *thnamestr = qemu_thread_get_name(); + if (thnamestr) { + writefn(opaque, thnamestr, strlen(thnamestr)); + } + } break; + case QMESSAGE_FORMAT_VAR_TID: + { + char buf[21]; + unsigned int tid = qemu_get_thread_id(); + snprintf(buf, sizeof(buf), "%u", tid); + writefn(opaque, buf, strlen(buf)); + } break; + case QMESSAGE_FORMAT_VAR_PID: + { + char buf[21]; + unsigned int pid = (int)getpid(); + snprintf(buf, sizeof(buf), "%u", pid); + writefn(opaque, buf, strlen(buf)); + } break; + case QMESSAGE_FORMAT_VAR_LOCATION: + { + g_autofree char *loc = loc_as_string(); + if (loc) { + writefn(opaque, loc, strlen(loc)); + } + } break; + case QMESSAGE_FORMAT_VAR_GUESTNAME: + { + if (error_guest_name) { + writefn(opaque, error_guest_name, strlen(error_guest_name)); + } + } break; + case QMESSAGE_FORMAT_VAR_LEVEL: + case QMESSAGE_FORMAT_VAR_LEVELALT: + { + const char *str; + static const char *levelstr[] = { + "debug", + "info", + "warning", + "error", + }; + QEMU_BUILD_BUG_ON(G_N_ELEMENTS(levelstr) != + QMESSAGE_LEVEL__MAX); + str = levelstr[level]; + if ((field->data.variable == QMESSAGE_FORMAT_VAR_LEVEL) || + (level != QMESSAGE_LEVEL_ERROR && + level != QMESSAGE_LEVEL_DEBUG)) { + writefn(opaque, str, strlen(str)); + } + break; + } + default: + g_assert_not_reached(); + } + break; + + case QMESSAGE_FORMAT_TYPE_EXPRESSION: + switch (field->data.expression.variable) { + case QMESSAGE_FORMAT_VAR_PROGNAME: + empty = (g_get_prgname() == NULL); + break; + case QMESSAGE_FORMAT_VAR_THREAD: + empty = (qemu_thread_get_name() == NULL); + break; + case QMESSAGE_FORMAT_VAR_LOCATION: + empty = loc_is_none(); + break; + case QMESSAGE_FORMAT_VAR_GUESTNAME: + empty = (error_guest_name == NULL); + break; + case QMESSAGE_FORMAT_VAR_LEVELALT: + empty = (level == QMESSAGE_LEVEL_ERROR || + level == QMESSAGE_LEVEL_DEBUG); + break; + default: + empty = false; + } + if (empty == + field->data.expression.negation) { + qmessage_format_emit(field->data.expression.format, + level, writefn, opaque); + } + break; + default: + g_assert_not_reached(); + } + } +} -- 2.56.1