From nobody Sun Sep 28 16:59:01 2025 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass(p=quarantine dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1758281278; cv=none; d=zohomail.com; s=zohoarc; b=EXsYVec4G+dOv/6/MlqvK5voMpjfyO/Io1ui0ZNDyQHqv/ss9p+nJ7fWk7z+vHxJ83SKVC5NbfrTA3Itj5mAFE+BJXdO1MNboJdWldI1tCoiHaf3QFpAST5g4iVbej8xzbNOJpBz1xokqnib4JgsVp9UU68wiAxpYitrPc+LGb4= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1758281278; h=Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=0rr5q4tcjTVgZsVN6TIdP7WAcYieibLS5wbWm7OTJfI=; b=nQeff1vcaWCPy4RO89cMhqWvM7qX/pOZvUWl3d5462Jg6xrJD1X8X4GzL2dKVJVeUtqrjBwAfWiApqwRJFiD1VzjO13evME9nGZ/CtH4EpR2nCZOHx2V/8lB3OqjUEjF5HDuhMCvBY0L6UcLHqv4v2T2Wwf8ZSuMPnEMH0HvTl4= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass header.from= (p=quarantine dis=none) Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1758281278221822.2503184667971; Fri, 19 Sep 2025 04:27:58 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1uzZGJ-00020r-CO; Fri, 19 Sep 2025 07:26:47 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1uzZGI-00020U-DX for qemu-devel@nongnu.org; Fri, 19 Sep 2025 07:26:46 -0400 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 1uzZGF-0001FC-3S for qemu-devel@nongnu.org; Fri, 19 Sep 2025 07:26:46 -0400 Received: from mx-prod-mc-04.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-646-UhkDVGDJMu6s3-6ysdq3pQ-1; Fri, 19 Sep 2025 07:26:25 -0400 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (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-04.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id C3D8919560B2; Fri, 19 Sep 2025 11:26:18 +0000 (UTC) Received: from avogadro.redhat.com (unknown [10.44.33.250]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id EE8C530002C5; Fri, 19 Sep 2025 11:26:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1758281199; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=0rr5q4tcjTVgZsVN6TIdP7WAcYieibLS5wbWm7OTJfI=; b=Bv61+I+fNwY3/BbMx5d2XD7hlnJ31P0rRbm8YsurbVCyVklikBqquXJU5U1W2Dn+TLBe+S u/M7G4jgat2KKf562M5cLYIrBSOQ8g/C15OqUSeCHkfnGhCTnhIM7bf18B9OnYzE4FmXbY zxAWUTJ85Ogo8vsYUMSUYsCe2fhMV3o= X-MC-Unique: UhkDVGDJMu6s3-6ysdq3pQ-1 X-Mimecast-MFC-AGG-ID: UhkDVGDJMu6s3-6ysdq3pQ_1758281178 From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: Tanish Desai , Zhao Liu , Stefan Hajnoczi , Manos Pitsidianakis , =?UTF-8?q?Daniel=20P=20=2E=20Berrang=C3=A9?= , Mads Ynddal Subject: [PATCH 08/16] tracetool: Add Rust format support Date: Fri, 19 Sep 2025 13:25:28 +0200 Message-ID: <20250919112536.141782-9-pbonzini@redhat.com> In-Reply-To: <20250919112536.141782-1-pbonzini@redhat.com> References: <20250919112536.141782-1-pbonzini@redhat.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -21 X-Spam_score: -2.2 X-Spam_bar: -- X-Spam_report: (-2.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.105, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H5=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_PASS=-0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1758281279279116600 Content-Type: text/plain; charset="utf-8" From: Tanish Desai Generating .rs files makes it possible to support tracing in rust. This support comprises a new format, and common code that converts the C expressions in trace-events to Rust. In particular, types need to be converted, and PRI macros expanded. As of this commit no backend generates Rust code, but it is already possible to use tracetool to generate Rust sources; they are not functional but they compile and contain tracepoint functions. Signed-off-by: Tanish Desai [Move Rust argument conversion from Event to Arguments; string support. - Paolo] Signed-off-by: Paolo Bonzini --- scripts/tracetool/__init__.py | 155 +++++++++++++++++++++++++++++++++ scripts/tracetool/format/rs.py | 71 +++++++++++++++ 2 files changed, 226 insertions(+) create mode 100644 scripts/tracetool/format/rs.py diff --git a/scripts/tracetool/__init__.py b/scripts/tracetool/__init__.py index a58d7938658..ea3e83f5adf 100644 --- a/scripts/tracetool/__init__.py +++ b/scripts/tracetool/__init__.py @@ -31,6 +31,49 @@ def error(*lines): error_write(*lines) sys.exit(1) =20 +FMT_TOKEN =3D re.compile(r'''(?: + " ( (?: [^"\\] | \\[\\"abfnrt] | # a str= ing literal + \\x[0-9a-fA-F][0-9a-fA-F]) *? ) " + | ( PRI [duixX] (?:8|16|32|64|PTR|MAX) ) # a PRI= xxx macro + | \s+ # space= s (ignored) + )''', re.X) + +PRI_SIZE_MAP =3D { + '8': 'hh', + '16': 'h', + '32': '', + '64': 'll', + 'PTR': 't', + 'MAX': 'j', +} + +def expand_format_string(c_fmt, prefix=3D""): + def pri_macro_to_fmt(pri_macro): + assert pri_macro.startswith("PRI") + fmt_type =3D pri_macro[3] # 'd', 'i', 'u', or 'x' + fmt_size =3D pri_macro[4:] # '8', '16', '32', '64', 'PTR', 'MAX' + + size =3D PRI_SIZE_MAP.get(fmt_size, None) + if size is None: + raise Exception(f"unknown macro {pri_macro}") + return size + fmt_type + + result =3D prefix + pos =3D 0 + while pos < len(c_fmt): + m =3D FMT_TOKEN.match(c_fmt, pos) + if not m: + print("No match at position", pos, ":", repr(c_fmt[pos:]), fil= e=3Dsys.stderr) + raise Exception("syntax error in trace file") + if m[1]: + substr =3D m[1] + elif m[2]: + substr =3D pri_macro_to_fmt(m[2]) + else: + substr =3D "" + result +=3D substr + pos =3D m.end() + return result =20 out_lineno =3D 1 out_filename =3D '' @@ -90,6 +133,49 @@ def out(*lines, **kwargs): "ptrdiff_t", ] =20 +C_TYPE_KEYWORDS =3D {"char", "int", "void", "short", "long", "signed", "un= signed"} + +C_TO_RUST_TYPE_MAP =3D { + "int": "std::ffi::c_int", + "long": "std::ffi::c_long", + "long long": "std::ffi::c_longlong", + "short": "std::ffi::c_short", + "char": "std::ffi::c_char", + "bool": "bool", + "unsigned": "std::ffi::c_uint", + # multiple keywords, keep them sorted + "long unsigned": "std::ffi::c_long", + "long long unsigned": "std::ffi::c_ulonglong", + "short unsigned": "std::ffi::c_ushort", + "char unsigned": "u8", + "int8_t": "i8", + "uint8_t": "u8", + "int16_t": "i16", + "uint16_t": "u16", + "int32_t": "i32", + "uint32_t": "u32", + "int64_t": "i64", + "uint64_t": "u64", + "void": "()", + "size_t": "usize", + "ssize_t": "isize", + "uintptr_t": "usize", + "ptrdiff_t": "isize", +} + +# Rust requires manual casting of <32-bit types when passing them to +# variable-argument functions. +RUST_VARARGS_SMALL_TYPES =3D { + "std::ffi::c_short", + "std::ffi::c_ushort", + "std::ffi::c_char", + "i8", + "u8", + "i16", + "u16", + "bool", +} + def validate_type(name): bits =3D name.split(" ") for bit in bits: @@ -105,6 +191,38 @@ def validate_type(name): "other complex pointer types should be " "declared as 'void *'" % name) =20 +def c_type_to_rust(name): + ptr =3D False + const =3D False + name =3D name.rstrip() + if name[-1] =3D=3D '*': + name =3D name[:-1].rstrip() + ptr =3D True + if name[-1] =3D=3D '*': + # pointers to pointers are the same as void* + name =3D "void" + + bits =3D name.split() + if "const" in bits: + const =3D True + bits.remove("const") + if bits[0] in C_TYPE_KEYWORDS: + if "signed" in bits: + bits.remove("signed") + if len(bits) > 1 and "int" in bits: + bits.remove("int") + bits.sort() + name =3D ' '.join(bits) + else: + if len(bits) > 1: + raise ValueError("Invalid type '%s'." % name) + name =3D bits[0] + + ty =3D C_TO_RUST_TYPE_MAP[name.strip()] + if ptr: + ty =3D f'*{"const" if const else "mut"} {ty}' + return ty + class Arguments: """Event arguments description.""" =20 @@ -193,6 +311,43 @@ def casted(self): """List of argument names casted to their type.""" return ["(%s)%s" % (type_, name) for type_, name in self._args] =20 + def rust_decl_extern(self): + """Return a Rust argument list for an extern "C" function""" + return ", ".join((f"_{name}: {c_type_to_rust(type_)}" + for type_, name in self._args)) + + def rust_decl(self): + """Return a Rust argument list for a tracepoint function""" + def decl_type(type_): + if type_ =3D=3D "const char *": + return "&std::ffi::CStr" + return c_type_to_rust(type_) + + return ", ".join((f"_{name}: {decl_type(type_)}" + for type_, name in self._args)) + + def rust_call_extern(self): + """Return a Rust argument list for a call to an extern "C" functio= n""" + def rust_cast(name, type_): + if type_ =3D=3D "const char *": + return f"_{name}.as_ptr()" + return f"_{name}" + + return ", ".join((rust_cast(name, type_) for type_, name in self._= args)) + + def rust_call_varargs(self): + """Return a Rust argument list for a call to a C varargs function"= "" + def rust_cast(name, type_): + if type_ =3D=3D "const char *": + return f"_{name}.as_ptr()" + + type_ =3D c_type_to_rust(type_) + if type_ in RUST_VARARGS_SMALL_TYPES: + return f"_{name} as std::ffi::c_int" + return f"_{name} /* as {type_} */" + + return ", ".join((rust_cast(name, type_) for type_, name in self._= args)) + =20 class Event(object): """Event description. diff --git a/scripts/tracetool/format/rs.py b/scripts/tracetool/format/rs.py new file mode 100644 index 00000000000..c4ab0e59d85 --- /dev/null +++ b/scripts/tracetool/format/rs.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +""" +trace-DIR.rs +""" + +__author__ =3D "Tanish Desai " +__copyright__ =3D "Copyright 2025, Tanish Desai " +__license__ =3D "GPL version 2 or (at your option) any later version" + +__maintainer__ =3D "Stefan Hajnoczi" +__email__ =3D "stefanha@redhat.com" + + +from tracetool import out + + +def generate(events, backend, group): + out('// SPDX-License-Identifier: GPL-2.0-or-later', + '// This file is @generated by tracetool, do not edit.', + '', + '#[allow(unused_imports)]', + 'use std::ffi::c_char;', + '#[allow(unused_imports)]', + 'use util::bindings;', + '', + '#[inline(always)]', + 'fn trace_event_get_state_dynamic_by_id(_id: u16) -> bool {', + ' unsafe { (trace_events_enabled_count !=3D 0) && (_id !=3D 0) = }', + '}', + '', + 'extern "C" {', + ' static mut trace_events_enabled_count: u32;', + '}',) + + out('extern "C" {') + + for e in events: + out(' static mut %s: u16;' % e.api(e.QEMU_DSTATE)) + out('}') + + # static state + for e in events: + if 'disable' in e.properties: + enabled =3D "false" + else: + enabled =3D "true" + + backend.generate_begin(events, group) + + for e in events: + out('', + '#[inline(always)]', + '#[allow(dead_code)]', + 'pub fn %(api)s(%(args)s)', + '{', + api=3De.api(e.QEMU_TRACE), + args=3De.args.rust_decl()) + + if "disable" not in e.properties: + backend.generate(e, group, check_trace_event_get_state=3DFalse) + if backend.check_trace_event_get_state: + event_id =3D 'TRACE_' + e.name.upper() + out(' if trace_event_get_state_dynamic_by_id(unsafe { _= %(event_id)s_DSTATE}) {', + event_id =3D event_id, + api=3De.api()) + backend.generate(e, group, check_trace_event_get_state=3DT= rue) + out(' }') + out('}') + + backend.generate_end(events, group) --=20 2.51.0