From patchwork Fri Dec 2 16:14:32 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28961 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947336wrr; Fri, 2 Dec 2022 08:17:43 -0800 (PST) X-Google-Smtp-Source: AA0mqf5imJ08DPrGiJuR2i8RzcoF96h28CiV9baAo31GlbfQ2LYLPqBTheaUz045A7FSx5+G1odY X-Received: by 2002:a17:902:f609:b0:188:a8a2:f43a with SMTP id n9-20020a170902f60900b00188a8a2f43amr63476999plg.130.1669997862720; Fri, 02 Dec 2022 08:17:42 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997862; cv=none; d=google.com; s=arc-20160816; b=PxnYGRep+F9AFfVkTcz12x2ALih73xQ4SXo0FKb5WmLoNE0ry8BuHc8VCqdavPm/p8 4pMebwDIwGSnTQB8ICnvYtMD9jUTODGwtUO8qpDU5UIOevtR5ldpRrgJn+Oyd2doBIRQ qi2vIFx7MpPY8a42IdlNLcLwrpc/WFJU0Ze5WEu/yqdc9jby37f8/qNfNeTwdnKeh33B jFEMUC2J3b+Cm6lMXZpWpL4yTC/4/S/zRKGXV/ouvsyjpOoGz+TO2Q5Qmz6lCjXvMpye gADk9l+C1vCstLJ9XygMKCdV+QrIRR+sbIp3/6iAVJfdFQE+iBHAHiDr4DR3MMbtr9g3 ytLQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=/Ohf8zV24wuuXaQRlwMY2G3Iy3P8pF+T/K2OT4EaT/Q=; b=HJVaKY+gpXDsNY9VpbiWsawLAO22xDRCvsX6D3iEvrmuLU0YL1z2km4dYph759aHm+ sbZ1kMxrDl4amZhBHfyB/evV60BSbT2u9oH5g/UH31lMFtJqL0WCamrsAwm35/Y/ObOh rxTd+PVUHJ3OOu+S2RDJ5som8wFCBV+6/zZ4QY2LnkeA4QN5JdNk4Yuu/m5fBLSDlC+o F/j7/FfDRMlnukaHbt1YFd9IMEM4/PkhjswyXirQr8Pp1GOKWph8kDNdUjXjGKRxx+Rb 1yQ603SnYiaN/4AU6MfJCXJxmfh1Oss4/TEeGGzXHZIgDpeoawYTo0QnJsz2rkDKN6+H l+MA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=beKukvFA; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id lw14-20020a17090b180e00b002135a4d80d7si8475405pjb.188.2022.12.02.08.17.28; Fri, 02 Dec 2022 08:17:42 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=beKukvFA; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233760AbiLBQPi (ORCPT + 99 others); Fri, 2 Dec 2022 11:15:38 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:52708 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233570AbiLBQPe (ORCPT ); Fri, 2 Dec 2022 11:15:34 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [IPv6:2604:1380:4601:e00::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 3CE69AD30A; Fri, 2 Dec 2022 08:15:33 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id EAAA2B821E8; Fri, 2 Dec 2022 16:15:31 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 80E1EC43470; Fri, 2 Dec 2022 16:15:28 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997730; bh=VSt+/hGabeANQLeUUkDMOId6k6ru4ZPGzmVrw2MIUuE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=beKukvFATiP3u3Xmr1v5gXIFi9wWHxS2ykMD9tlunHXc0BjJhHm/7q+kk4wJE0ZDd hZqg8ob2kXYdCh+NZA7oIOv6mMoIPjK2nTBZEo22zPv58BgXDSvVRTZeNSzmto5K6u 3FaBYP0EzT4WRCn/By0vFwDnxZpt+mODz4ADYxZGtf9aYrTSam0ZBk1iuRxxTYiswM l788yFfb5w8NzJqPmgWhfR0a6KD4pvHRZ60BjMVHyxPs9E6GbMYv9hGBsOxzmiaLY0 FKpbd2GlRVljMf5qO/NaoUzsNPUQBB8fjz1/nJFavwPt8woD+NzJ+gQdGzI1oQ6YRw gZenyb9qJdpgA== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Wei Liu Subject: [PATCH v2 01/28] rust: prelude: split re-exports into groups Date: Fri, 2 Dec 2022 17:14:32 +0100 Message-Id: <20221202161502.385525-2-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119678748939837?= X-GMAIL-MSGID: =?utf-8?q?1751119678748939837?= From: Miguel Ojeda Split the prelude re-exports into groups: first the ones coming from the `core` crate, then `alloc`, then our own crates and finally the ones from modules from `kernel` itself (i.e. `super`). We are doing this manually for the moment, but ideally, long-term, this could be automated via `rustfmt` with options such as `group_imports` and `imports_granularity` (both currently unstable). Reviewed-by: Boqun Feng Reviewed-by: Wei Liu Signed-off-by: Miguel Ojeda --- rust/kernel/prelude.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 495e22250726..f8219285d8c0 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -11,10 +11,14 @@ //! use kernel::prelude::*; //! ``` -pub use super::{ - error::{Error, Result}, - pr_emerg, pr_info, ThisModule, -}; -pub use alloc::{boxed::Box, vec::Vec}; pub use core::pin::Pin; + +pub use alloc::{boxed::Box, vec::Vec}; + pub use macros::module; + +pub use super::{pr_emerg, pr_info}; + +pub use super::error::{Error, Result}; + +pub use super::ThisModule; From patchwork Fri Dec 2 16:14:33 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28963 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947413wrr; Fri, 2 Dec 2022 08:17:47 -0800 (PST) X-Google-Smtp-Source: AA0mqf5sapnpOlg+QFojucxV4fV0xkvZOphkVVDv3AgW1WBTUwcIuer31AVQO47WthYOcmpRLxUs X-Received: by 2002:a63:2226:0:b0:478:54e2:ecb1 with SMTP id i38-20020a632226000000b0047854e2ecb1mr14083603pgi.550.1669997867503; Fri, 02 Dec 2022 08:17:47 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997867; cv=none; d=google.com; s=arc-20160816; b=XEEzyPoaZ5S9AuqQAi5UHBEqglwyRo/RiKb4cglUtrsEeb2VA2elxRR2evNRirO6aG HlwchHveMfxpkn/mBx3mIQGdYwoAZJNC6HQ2A1G4puJ6Y4alKrDY+zmOYQDpXz7HfVzZ QBU4Nld4P/wfWkE3gW7vf8K2h1I0yeBD1n/vxff7fehqEC206RkvoKyysYfd5dJsiTG2 8dnzP5CpdIYps2dFk70c0tvCCISMdDXEZvBFNNJy729u2eB3RU//sB7rqVo7vFsi8NDd DvCaFP+RIBd3AGABd5h1CHnyKpVtrzHJYusBzb1a8Yt4SpAO53tnZcmNCJ8g+4fcNpoz NELg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=py6/QzM2l2DVzLzQanfhZsEPuQZtZwMlh4974rH5abM=; b=ejnGFcg11EESeEitsvs21N+/Jzq3zQ61/RC48whMFY7YQ0lJ1R92PcX0yPwmb///Kq Da7UdXlRmwGRKlxp2Xje5rhgpmTQFxyfRElyW014xSMzIWz4JdBXXcm8vf2SqGFT/QIg 3Ua6lI0Ufk35W53dzjYcXxHpsKzYIerVA1hFJumyuseM546MPGpd6Bg5oopL0D10kCeu vMZYI9XH+Yl1bdHfhPxmC3vTLlUL5bWpuA6wPnsvukZ8ABMc5y6Hbc2c1BaEFCsrIy+9 ykOXmFqNeSwrN34aB83ev6fqxzC6++Y+IAK6g8JS2W82flZ1h0dUevMf+vD0wzVRTkWg aeCw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=dE1pDe6w; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id u6-20020a170903124600b00186ada5d4e2si8684486plh.215.2022.12.02.08.17.32; Fri, 02 Dec 2022 08:17:47 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=dE1pDe6w; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233783AbiLBQPk (ORCPT + 99 others); Fri, 2 Dec 2022 11:15:40 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:52732 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233583AbiLBQPg (ORCPT ); Fri, 2 Dec 2022 11:15:36 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 26D09AD304; Fri, 2 Dec 2022 08:15:35 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id B5FB8622E3; Fri, 2 Dec 2022 16:15:34 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5E2A7C433D6; Fri, 2 Dec 2022 16:15:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997734; bh=7z0Z9/aBWDg8zSLO+3RcUCw+p+zedYDCyRSDGcvfevk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=dE1pDe6w8AxHp1/+K2aWGBuvWfYhIil3ojm6M3ha2cTGjROUHYhV5MZv5ZQ62D8aa 2k3udFmoViSaLrQ9t0zCAtQrLMc9maUZmei9Ek1ii4txa8cJjXziDFObCk6WGKItpK 8tyiTKgbDMyFdavl2aXHURArQb2jpnYnT8DlEGzcEQN981dGDO9QInXsAkgDhjgmQ/ iz7DJ8/gFMoQ/e19ii1gxoYR38d081jfG/nXpiJO5x83AIefLAsy0Qulh0ftPLWzdd OYZJPvj/hpwTCjiZV2rdqQSUMYuWEwHtJ+hYg6BD0uQRl7ehBBF9Ma6D99+rDkePl9 P8tWFwmLCkMsw== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Adam Bratschi-Kaye , Wei Liu , Sergio Gonzalez Collado Subject: [PATCH v2 02/28] rust: print: add more `pr_*!` levels Date: Fri, 2 Dec 2022 17:14:33 +0100 Message-Id: <20221202161502.385525-3-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119683812843808?= X-GMAIL-MSGID: =?utf-8?q?1751119683812843808?= From: Miguel Ojeda Currently, only `pr_info!` (for the minimal sample) and `pr_emerg!` (for the panic handler) are there. Add the other levels as new macros, i.e. `pr_alert!`, `pr_crit!`, `pr_err!`, `pr_warn!`, `pr_notice!` and `pr_debug!`. Co-developed-by: Adam Bratschi-Kaye Signed-off-by: Adam Bratschi-Kaye Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Co-developed-by: Gary Guo Signed-off-by: Gary Guo Reviewed-by: Boqun Feng Reviewed-by: Wei Liu Reviewed-by: Sergio Gonzalez Collado Signed-off-by: Miguel Ojeda --- rust/kernel/prelude.rs | 2 +- rust/kernel/print.rs | 154 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index f8219285d8c0..6a1c6b38327f 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -17,7 +17,7 @@ pub use alloc::{boxed::Box, vec::Vec}; pub use macros::module; -pub use super::{pr_emerg, pr_info}; +pub use super::{pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn}; pub use super::error::{Error, Result}; diff --git a/rust/kernel/print.rs b/rust/kernel/print.rs index 55db5a1ba752..694f51c6da5c 100644 --- a/rust/kernel/print.rs +++ b/rust/kernel/print.rs @@ -74,7 +74,13 @@ pub mod format_strings { // Furthermore, `static` instead of `const` is used to share the strings // for all the kernel. pub static EMERG: [u8; LENGTH] = generate(false, bindings::KERN_EMERG); + pub static ALERT: [u8; LENGTH] = generate(false, bindings::KERN_ALERT); + pub static CRIT: [u8; LENGTH] = generate(false, bindings::KERN_CRIT); + pub static ERR: [u8; LENGTH] = generate(false, bindings::KERN_ERR); + pub static WARNING: [u8; LENGTH] = generate(false, bindings::KERN_WARNING); + pub static NOTICE: [u8; LENGTH] = generate(false, bindings::KERN_NOTICE); pub static INFO: [u8; LENGTH] = generate(false, bindings::KERN_INFO); + pub static DEBUG: [u8; LENGTH] = generate(false, bindings::KERN_DEBUG); } /// Prints a message via the kernel's [`_printk`]. @@ -172,6 +178,126 @@ macro_rules! pr_emerg ( ) ); +/// Prints an alert-level message (level 1). +/// +/// Use this level if action must be taken immediately. +/// +/// Equivalent to the kernel's [`pr_alert`] macro. +/// +/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and +/// `alloc::format!` for information about the formatting syntax. +/// +/// [`pr_alert`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_alert +/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html +/// +/// # Examples +/// +/// ``` +/// pr_alert!("hello {}\n", "there"); +/// ``` +#[macro_export] +macro_rules! pr_alert ( + ($($arg:tt)*) => ( + $crate::print_macro!($crate::print::format_strings::ALERT, $($arg)*) + ) +); + +/// Prints a critical-level message (level 2). +/// +/// Use this level for critical conditions. +/// +/// Equivalent to the kernel's [`pr_crit`] macro. +/// +/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and +/// `alloc::format!` for information about the formatting syntax. +/// +/// [`pr_crit`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_crit +/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html +/// +/// # Examples +/// +/// ``` +/// pr_crit!("hello {}\n", "there"); +/// ``` +#[macro_export] +macro_rules! pr_crit ( + ($($arg:tt)*) => ( + $crate::print_macro!($crate::print::format_strings::CRIT, $($arg)*) + ) +); + +/// Prints an error-level message (level 3). +/// +/// Use this level for error conditions. +/// +/// Equivalent to the kernel's [`pr_err`] macro. +/// +/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and +/// `alloc::format!` for information about the formatting syntax. +/// +/// [`pr_err`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_err +/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html +/// +/// # Examples +/// +/// ``` +/// pr_err!("hello {}\n", "there"); +/// ``` +#[macro_export] +macro_rules! pr_err ( + ($($arg:tt)*) => ( + $crate::print_macro!($crate::print::format_strings::ERR, $($arg)*) + ) +); + +/// Prints a warning-level message (level 4). +/// +/// Use this level for warning conditions. +/// +/// Equivalent to the kernel's [`pr_warn`] macro. +/// +/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and +/// `alloc::format!` for information about the formatting syntax. +/// +/// [`pr_warn`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_warn +/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html +/// +/// # Examples +/// +/// ``` +/// pr_warn!("hello {}\n", "there"); +/// ``` +#[macro_export] +macro_rules! pr_warn ( + ($($arg:tt)*) => ( + $crate::print_macro!($crate::print::format_strings::WARNING, $($arg)*) + ) +); + +/// Prints a notice-level message (level 5). +/// +/// Use this level for normal but significant conditions. +/// +/// Equivalent to the kernel's [`pr_notice`] macro. +/// +/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and +/// `alloc::format!` for information about the formatting syntax. +/// +/// [`pr_notice`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_notice +/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html +/// +/// # Examples +/// +/// ``` +/// pr_notice!("hello {}\n", "there"); +/// ``` +#[macro_export] +macro_rules! pr_notice ( + ($($arg:tt)*) => ( + $crate::print_macro!($crate::print::format_strings::NOTICE, $($arg)*) + ) +); + /// Prints an info-level message (level 6). /// /// Use this level for informational messages. @@ -196,3 +322,31 @@ macro_rules! pr_info ( $crate::print_macro!($crate::print::format_strings::INFO, $($arg)*) ) ); + +/// Prints a debug-level message (level 7). +/// +/// Use this level for debug messages. +/// +/// Equivalent to the kernel's [`pr_debug`] macro, except that it doesn't support dynamic debug +/// yet. +/// +/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and +/// `alloc::format!` for information about the formatting syntax. +/// +/// [`pr_debug`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_debug +/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html +/// +/// # Examples +/// +/// ``` +/// pr_debug!("hello {}\n", "there"); +/// ``` +#[macro_export] +#[doc(alias = "print")] +macro_rules! pr_debug ( + ($($arg:tt)*) => ( + if cfg!(debug_assertions) { + $crate::print_macro!($crate::print::format_strings::DEBUG, $($arg)*) + } + ) +); From patchwork Fri Dec 2 16:14:34 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28972 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948031wrr; Fri, 2 Dec 2022 08:19:03 -0800 (PST) X-Google-Smtp-Source: AA0mqf7mgj2e0K0iIyY8KZ5GnYnVPGYPw33hVIcOxRtChAUeRG4crloa86aZqdxgerTnzHSEJSJu X-Received: by 2002:a05:6a00:32c7:b0:565:f8bb:96f8 with SMTP id cl7-20020a056a0032c700b00565f8bb96f8mr52873180pfb.45.1669997943176; Fri, 02 Dec 2022 08:19:03 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997943; cv=none; d=google.com; s=arc-20160816; b=CDOdpMcFwbvjtFyFzY2M0OP3hqDWgyYRAnf4wl6UJis8PdCIEPvSYCBKx7V9JFELox 6/wAGtp9EGByBybd4OutlgGPqHyw/Gtn2hMrp3WTcEFwgqsNdfACeKL9ShHVOcaAGovb rgtxWJgpcQ6TncmbV0DkH6q4rP/dfpTb74QsV9gnnfVRvQK55psKm/62CxTZyAwsvQnq M91AzCCdLLYjrcKRzHu+lLlun5Crf1Fc0KPFzW40xD+1Qn++7IgtjB8+zhGoCTTkRxvw pFdIAVWtxCgE+iPn8NDij9RZs+CVXzVK9xeOTq1EAmTz2z5tBrKyzyNOflmhhnT6YzcR gmaQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=R5pWSh7qEY9z88C3y677Nqp9ptnKnyF/XTUSx+C3Yyc=; b=iW5xRGZDPMRVzcwX0d2WgKWJEGoaqcROmy1ZQOhsxgY4NluQmBsxLsXltOBFNfwa8o OOPhbrSRIXjNupy8A1A3ZY3LOZCMUu2A+ySBD7XNrpDG1Fcxfsu4dQ3qwMHjzUfnszUD /RZQEMEJqwZpZDQ2vPUkEm1Y2UKucrMJlwvYPq6WyVzEmc/5YFdYmdKbROTWbLDJ0CCO yfqBf1S5VS8a+h+DAU4kKSOGcL6FbWoSuOLmtWsF58EGLo8VZnjPxqPX5bzsj1zRMbVx cKFrD7qycWJuPlR1+TYDNfmaJ0k+9w+nZNoebo8uyUa3tKj4lhPRQttxQ4rl5lTBudH8 bL0w== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=HvSJwTYw; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id w2-20020a634742000000b0043c474c8942si7618354pgk.673.2022.12.02.08.18.44; Fri, 02 Dec 2022 08:19:03 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=HvSJwTYw; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233794AbiLBQPv (ORCPT + 99 others); Fri, 2 Dec 2022 11:15:51 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53040 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233804AbiLBQPs (ORCPT ); Fri, 2 Dec 2022 11:15:48 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id EBF77BF672; Fri, 2 Dec 2022 08:15:39 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id A77AAB82149; Fri, 2 Dec 2022 16:15:38 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B90A5C433B5; Fri, 2 Dec 2022 16:15:34 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997737; bh=KgBgOHXymfu3Q4eF7TqCl7XFCIPthuyaHkGisjhFOJU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HvSJwTYwz3NOYYnSx08OJX8VHQx7tH1bvPKzRc+tiNRu91a1p/z9Uql8RBXudanLJ 4G5wCXmEDEm62GzPAo84iWJEBbOOiNt/cNgJ6S5WMmGJwANNpyN9dRtEoUifRyWzw1 fkJlOEQ+uz6rVdyfVKfl5nijV1E9j6BeFfODghP0anUI86dh/7koMb5+rIAElNmjuk 5wd/Wf+tNLyUFQrIDrmHCdKNTafdFDpf95szcMXEPe10AIdzW9cIIUbIZA7tqGgb1p gaJ37RnxKVm87j+LwSNJ7DwInuaLhZrhPNdoX51idPSSPEjiB7bs4COzUFHqWiS8at Z9imFPWsKyLGA== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Adam Bratschi-Kaye , Wei Liu , =?utf-8?q?Sergio_Gonz=C3=A1lez_Collado?= Subject: [PATCH v2 03/28] rust: print: add `pr_cont!` macro Date: Fri, 2 Dec 2022 17:14:34 +0100 Message-Id: <20221202161502.385525-4-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119763362122874?= X-GMAIL-MSGID: =?utf-8?q?1751119763362122874?= From: Miguel Ojeda This level is a bit different from the rest since it does not pass the module name to the `_printk()` call. Thus add a new parameter to the general `print_macro!` to handle it differently. Co-developed-by: Adam Bratschi-Kaye Signed-off-by: Adam Bratschi-Kaye Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Co-developed-by: Gary Guo Signed-off-by: Gary Guo Reviewed-by: Wei Liu Reviewed-by: Sergio González Collado Signed-off-by: Miguel Ojeda --- rust/kernel/print.rs | 72 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 9 deletions(-) diff --git a/rust/kernel/print.rs b/rust/kernel/print.rs index 694f51c6da5c..29bf9c2e8aee 100644 --- a/rust/kernel/print.rs +++ b/rust/kernel/print.rs @@ -81,6 +81,7 @@ pub mod format_strings { pub static NOTICE: [u8; LENGTH] = generate(false, bindings::KERN_NOTICE); pub static INFO: [u8; LENGTH] = generate(false, bindings::KERN_INFO); pub static DEBUG: [u8; LENGTH] = generate(false, bindings::KERN_DEBUG); + pub static CONT: [u8; LENGTH] = generate(true, bindings::KERN_CONT); } /// Prints a message via the kernel's [`_printk`]. @@ -111,6 +112,26 @@ pub unsafe fn call_printk( } } +/// Prints a message via the kernel's [`_printk`] for the `CONT` level. +/// +/// Public but hidden since it should only be used from public macros. +/// +/// [`_printk`]: ../../../../include/linux/printk.h +#[doc(hidden)] +#[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))] +pub fn call_printk_cont(args: fmt::Arguments<'_>) { + // `_printk` does not seem to fail in any path. + // + // SAFETY: The format string is fixed. + #[cfg(CONFIG_PRINTK)] + unsafe { + bindings::_printk( + format_strings::CONT.as_ptr() as _, + &args as *const _ as *const c_void, + ); + } +} + /// Performs formatting and forwards the string to [`call_printk`]. /// /// Public but hidden since it should only be used from public macros. @@ -120,7 +141,7 @@ pub unsafe fn call_printk( #[allow(clippy::crate_in_macro_def)] macro_rules! print_macro ( // The non-continuation cases (most of them, e.g. `INFO`). - ($format_string:path, $($arg:tt)+) => ( + ($format_string:path, false, $($arg:tt)+) => ( // SAFETY: This hidden macro should only be called by the documented // printing macros which ensure the format string is one of the fixed // ones. All `__LOG_PREFIX`s are null-terminated as they are generated @@ -134,6 +155,13 @@ macro_rules! print_macro ( ); } ); + + // The `CONT` case. + ($format_string:path, true, $($arg:tt)+) => ( + $crate::print::call_printk_cont( + format_args!($($arg)+), + ); + ); ); /// Stub for doctests @@ -174,7 +202,7 @@ macro_rules! print_macro ( #[macro_export] macro_rules! pr_emerg ( ($($arg:tt)*) => ( - $crate::print_macro!($crate::print::format_strings::EMERG, $($arg)*) + $crate::print_macro!($crate::print::format_strings::EMERG, false, $($arg)*) ) ); @@ -198,7 +226,7 @@ macro_rules! pr_emerg ( #[macro_export] macro_rules! pr_alert ( ($($arg:tt)*) => ( - $crate::print_macro!($crate::print::format_strings::ALERT, $($arg)*) + $crate::print_macro!($crate::print::format_strings::ALERT, false, $($arg)*) ) ); @@ -222,7 +250,7 @@ macro_rules! pr_alert ( #[macro_export] macro_rules! pr_crit ( ($($arg:tt)*) => ( - $crate::print_macro!($crate::print::format_strings::CRIT, $($arg)*) + $crate::print_macro!($crate::print::format_strings::CRIT, false, $($arg)*) ) ); @@ -246,7 +274,7 @@ macro_rules! pr_crit ( #[macro_export] macro_rules! pr_err ( ($($arg:tt)*) => ( - $crate::print_macro!($crate::print::format_strings::ERR, $($arg)*) + $crate::print_macro!($crate::print::format_strings::ERR, false, $($arg)*) ) ); @@ -270,7 +298,7 @@ macro_rules! pr_err ( #[macro_export] macro_rules! pr_warn ( ($($arg:tt)*) => ( - $crate::print_macro!($crate::print::format_strings::WARNING, $($arg)*) + $crate::print_macro!($crate::print::format_strings::WARNING, false, $($arg)*) ) ); @@ -294,7 +322,7 @@ macro_rules! pr_warn ( #[macro_export] macro_rules! pr_notice ( ($($arg:tt)*) => ( - $crate::print_macro!($crate::print::format_strings::NOTICE, $($arg)*) + $crate::print_macro!($crate::print::format_strings::NOTICE, false, $($arg)*) ) ); @@ -319,7 +347,7 @@ macro_rules! pr_notice ( #[doc(alias = "print")] macro_rules! pr_info ( ($($arg:tt)*) => ( - $crate::print_macro!($crate::print::format_strings::INFO, $($arg)*) + $crate::print_macro!($crate::print::format_strings::INFO, false, $($arg)*) ) ); @@ -346,7 +374,33 @@ macro_rules! pr_info ( macro_rules! pr_debug ( ($($arg:tt)*) => ( if cfg!(debug_assertions) { - $crate::print_macro!($crate::print::format_strings::DEBUG, $($arg)*) + $crate::print_macro!($crate::print::format_strings::DEBUG, false, $($arg)*) } ) ); + +/// Continues a previous log message in the same line. +/// +/// Use only when continuing a previous `pr_*!` macro (e.g. [`pr_info!`]). +/// +/// Equivalent to the kernel's [`pr_cont`] macro. +/// +/// Mimics the interface of [`std::print!`]. See [`core::fmt`] and +/// `alloc::format!` for information about the formatting syntax. +/// +/// [`pr_cont`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html#c.pr_cont +/// [`std::print!`]: https://doc.rust-lang.org/std/macro.print.html +/// +/// # Examples +/// +/// ``` +/// # use kernel::pr_cont; +/// pr_info!("hello"); +/// pr_cont!(" {}\n", "there"); +/// ``` +#[macro_export] +macro_rules! pr_cont ( + ($($arg:tt)*) => ( + $crate::print_macro!($crate::print::format_strings::CONT, true, $($arg)*) + ) +); From patchwork Fri Dec 2 16:14:35 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28973 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948048wrr; Fri, 2 Dec 2022 08:19:05 -0800 (PST) X-Google-Smtp-Source: AA0mqf7NuXiU+4ccDeInSwT+5jI6wXS5uiGASPyPFRVW9tFkvOssqOiRGRfGPscB9u8EJ38nXlkP X-Received: by 2002:a63:1562:0:b0:41a:4bd4:f287 with SMTP id 34-20020a631562000000b0041a4bd4f287mr44892506pgv.20.1669997944767; Fri, 02 Dec 2022 08:19:04 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997944; cv=none; d=google.com; s=arc-20160816; b=wKgBBqtxMwfGl0vAOKd0KKjy618FCydfuE1UBab3fVfLtllZndWZ67faWNaOtuWevc /27CbzRpohYZs6NRYCn5Kw++6h0QjTSVRk71vkRD0pP0wHwwfHBTDYC4jqcvfcaIvuWV 6P0/CHLid5Fdn8XMThjd+u0nnfQ8NPaJQTw5dr9erHUHQu/wEr49rHP3XBn1db95Eu+R abWVytRLjnrZ7y/amCdhllcabgs2IE55P87nbuy1F52+bWSSQ7K6R30kOKiUAcMe2INv J1bw15wG5AvZMMqj4bdDhOzBJjdE/fsVoDztVPZIWpRDxkR676M2Hg5ui+Pe0sbQ3vxN g24Q== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=SqCdk7fLDYqTKUouFEQZ1SeKBeTGRXZEAtJQ4n7vElU=; b=Z273fadleQWO5NSqiFuwlEk4UPWMEIK0/m9aRkDHehqtVr38CrvSBkpj1CHv7Xp/ut PVNbqeNOeIdV0Twi3viqkhJxf62d2kUZB9/RPERUpURhZ3oF4wZz+ouZssLuMe2RUlza r8HY8I85ERSP0C0j/tb4cB2xPlfcmnFa/spTc9VWHf/XE6YQ8WA0G6uPtmjfG/oJ6fzK x+fQ4U2G6y0nZC9nvg9kr4r7wqDwng8y9dkr6p1tYJqV+G1VbyWqHc5vrxRUTQK4P1yc 6mqmkpxi4Me0e82n7bUAEpumeWGsI6ccaD4z6tO6+1OgXpsBx/ckjy1xukVPM+N3ql0f e1oQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=GBYta338; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id 130-20020a621988000000b0057346470e4fsi7249529pfz.344.2022.12.02.08.18.44; Fri, 02 Dec 2022 08:19:04 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=GBYta338; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233824AbiLBQPz (ORCPT + 99 others); Fri, 2 Dec 2022 11:15:55 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53080 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233774AbiLBQPt (ORCPT ); Fri, 2 Dec 2022 11:15:49 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id A03BEBBBD0; Fri, 2 Dec 2022 08:15:41 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 3E208622E3; Fri, 2 Dec 2022 16:15:41 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0E44DC433D6; Fri, 2 Dec 2022 16:15:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997740; bh=4UfoqML4L3IukWfvADvLkrtuQak85Ze14tDrzQ5hdwQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GBYta338nXNnuzZG7GDNq9PFxhM/cX92DH2AzsBGFI4iTieKuu1DUqzMRXV+nPWx5 7R/fiPYF8cjZQY36+UqacdBwgSgQQg8aQPTpxZ81tcSCjr4EUnhk3eo4ZZH9zDCkK+ 2o9va6KpTYjHgLKtiqZX8PwfW8wL5dc6ZsRkqTeyqU0fEC6mNzgZrod0nhUCv3WHrJ keudAiAD7Yx7UHhrOkYIUuYwdwQV+NaM+BFydjaZSSLC4hm0c/dQ0x97GqrkVCjo+K 4ZdmEA4t2NyS9PXASMMZYYPSd/cAu1gKw747T1i81cuvJX3084NFbeAAD2SyY0jlCC GFTdyIQCe2oqQ== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Finn Behrens , Wei Liu , =?utf-8?q?Sergio_Gonz=C3=A1lez_Collado?= Subject: [PATCH v2 04/28] rust: samples: add `rust_print` example Date: Fri, 2 Dec 2022 17:14:35 +0100 Message-Id: <20221202161502.385525-5-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119764790818320?= X-GMAIL-MSGID: =?utf-8?q?1751119764790818320?= From: Miguel Ojeda Add example to exercise the printing macros (`pr_*!`) introduced in the previous patches. Reviewed-by: Finn Behrens Reviewed-by: Wei Liu Tested-by: Sergio González Collado Signed-off-by: Miguel Ojeda --- samples/rust/Kconfig | 10 +++++++ samples/rust/Makefile | 1 + samples/rust/rust_print.rs | 54 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 samples/rust/rust_print.rs diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index 841e0906e943..b0f74a81c8f9 100644 --- a/samples/rust/Kconfig +++ b/samples/rust/Kconfig @@ -20,6 +20,16 @@ config SAMPLE_RUST_MINIMAL If unsure, say N. +config SAMPLE_RUST_PRINT + tristate "Printing macros" + help + This option builds the Rust printing macros sample. + + To compile this as a module, choose M here: + the module will be called rust_print. + + If unsure, say N. + config SAMPLE_RUST_HOSTPROGS bool "Host programs" help diff --git a/samples/rust/Makefile b/samples/rust/Makefile index 1daba5f8658a..03086dabbea4 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -1,5 +1,6 @@ # SPDX-License-Identifier: GPL-2.0 obj-$(CONFIG_SAMPLE_RUST_MINIMAL) += rust_minimal.o +obj-$(CONFIG_SAMPLE_RUST_PRINT) += rust_print.o subdir-$(CONFIG_SAMPLE_RUST_HOSTPROGS) += hostprogs diff --git a/samples/rust/rust_print.rs b/samples/rust/rust_print.rs new file mode 100644 index 000000000000..09f737790f3f --- /dev/null +++ b/samples/rust/rust_print.rs @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust printing macros sample. + +use kernel::pr_cont; +use kernel::prelude::*; + +module! { + type: RustPrint, + name: b"rust_print", + author: b"Rust for Linux Contributors", + description: b"Rust printing macros sample", + license: b"GPL", +} + +struct RustPrint; + +impl kernel::Module for RustPrint { + fn init(_module: &'static ThisModule) -> Result { + pr_info!("Rust printing macros sample (init)\n"); + + pr_emerg!("Emergency message (level 0) without args\n"); + pr_alert!("Alert message (level 1) without args\n"); + pr_crit!("Critical message (level 2) without args\n"); + pr_err!("Error message (level 3) without args\n"); + pr_warn!("Warning message (level 4) without args\n"); + pr_notice!("Notice message (level 5) without args\n"); + pr_info!("Info message (level 6) without args\n"); + + pr_info!("A line that"); + pr_cont!(" is continued"); + pr_cont!(" without args\n"); + + pr_emerg!("{} message (level {}) with args\n", "Emergency", 0); + pr_alert!("{} message (level {}) with args\n", "Alert", 1); + pr_crit!("{} message (level {}) with args\n", "Critical", 2); + pr_err!("{} message (level {}) with args\n", "Error", 3); + pr_warn!("{} message (level {}) with args\n", "Warning", 4); + pr_notice!("{} message (level {}) with args\n", "Notice", 5); + pr_info!("{} message (level {}) with args\n", "Info", 6); + + pr_info!("A {} that", "line"); + pr_cont!(" is {}", "continued"); + pr_cont!(" with {}\n", "args"); + + Ok(RustPrint) + } +} + +impl Drop for RustPrint { + fn drop(&mut self) { + pr_info!("Rust printing macros sample (exit)\n"); + } +} From patchwork Fri Dec 2 16:14:36 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28964 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947558wrr; Fri, 2 Dec 2022 08:18:02 -0800 (PST) X-Google-Smtp-Source: AA0mqf7DwgyvFJv9/gQQmEU/6PzTLL7rFBW3vOoH+Y6kr9L1tvAZw32soTFQmkzwDKdg1id0e/WR X-Received: by 2002:a17:90a:fc92:b0:219:1545:bc57 with SMTP id ci18-20020a17090afc9200b002191545bc57mr9339647pjb.133.1669997882199; Fri, 02 Dec 2022 08:18:02 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997882; cv=none; d=google.com; s=arc-20160816; b=j2Sd6clST9LufjhvUZ2/e6GZWVg9hbx10k3YitAIINKBp+DWloibQ9rPJr2bxq27J3 8zdVkxNUAX3sA2fB4mBGfrtgnHrMN23c0m7iJgb8VEGja/Llgul7J/5GiH0ofHblYN6N 0dVxmF9Q3/1G2vbiXAP032+gVAaxlFaU9tMg7pvYublTdTsKDubcKDHkWIMbrS0uNRkj obc7lZ4BI/QJFpm47eInSn/sjP1jwDWt32MVU7M5TDHEZX3PZzb9bQN9WLdUFRxuOIpl zeqePkxWe7LoFgPLA0Y6+3DByt3ah/ha0isGUcuqJMkWWQtLjSxIDye04A3gNhvhkrK1 s7kw== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=ulc/5ZTH5y1ngAvIvwlQrKsejNK8BOjuFh7i+czSb5E=; b=ir8o4UXxBvzbZ06IPnPFbuX8UZ5Qouxchl5usVh5Bi9W01QhKnIkG7Yw/+udtdqfdJ Fes2FdLoIt0ZzBA8GsyPPKFYT8qs7ue+yhVJRSQ2i3SHroGJrTh4SqpM4CuGSPmXxzT4 pE6w+CjR0nfaXkRM5gfaxy6S7KHqpMMuAHLhOGn+7VRNMEaEg9yNKZjtq5rJJtEhlhS1 XqxJzKNMMVUK1cExtIJ91W+xpoll9LiJmH2ZeafU3rwqYpb3OI6hmMcyYXaebF6uCC0O VTenWJSSwML+GqiKVH/BRINY3drBpEtB7BXWSo8RZsNcewY9dV8BJPuuEa8AY5RCXEWR Fuiw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=dgXNifwt; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id j5-20020a632305000000b00477b92e2773si7572267pgj.692.2022.12.02.08.17.40; Fri, 02 Dec 2022 08:18:02 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=dgXNifwt; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233888AbiLBQQV (ORCPT + 99 others); Fri, 2 Dec 2022 11:16:21 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53112 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233796AbiLBQPx (ORCPT ); Fri, 2 Dec 2022 11:15:53 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 2EB1CD96A9; Fri, 2 Dec 2022 08:15:46 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id CBBF1B821E8; Fri, 2 Dec 2022 16:15:44 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4E3E4C433C1; Fri, 2 Dec 2022 16:15:41 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997743; bh=dtOQU49yR7LQiDxvwc6HHhk83pUumrESygYwXplYSi8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=dgXNifwtz8f9FEDXONTfj3cn2QJYnm8teZte4lQpJxMPea8wUtXyATIgmMeKzTcc5 YrYJkdjvYKOSt+76f5eHIO1KRmO/Q5YLnq3bNhL4V1oRk3vebFIXrkYseYbKXSQhc/ QkLxtKZLmMnoq7K0UXyxEITHuUHw/Yyf0lpXKPYSvs8Pn71MKjqfd+6kE4l/dRTaIG xIL++tc8A2qgNGZ4SPkuxeE2MHXsVLvV4fV8/AsVb8wWxVXNd2EFu4+MKoDz0ncjtK zu+T16cjFD/nu2Jh7uD6HM4JGWLVgpvf5ae3S1TVPsbRhaMqlKGdu7ijHIwhVNePcz 3qdx+Dx684TjA== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Finn Behrens Subject: [PATCH v2 05/28] rust: macros: add `concat_idents!` proc macro Date: Fri, 2 Dec 2022 17:14:36 +0100 Message-Id: <20221202161502.385525-6-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119699112242975?= X-GMAIL-MSGID: =?utf-8?q?1751119699112242975?= From: Björn Roy Baron This macro provides similar functionality to the unstable feature `concat_idents` without having to rely on it. For instance: let x_1 = 42; let x_2 = concat_idents!(x, _1); assert!(x_1 == x_2); It has different behavior with respect to macro hygiene. Unlike the unstable `concat_idents!` macro, it allows, for example, referring to local variables by taking the span of the second macro as span for the output identifier. Signed-off-by: Björn Roy Baron Reviewed-by: Finn Behrens [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Gary Guo --- rust/macros/concat_idents.rs | 23 +++++++++++++++++++ rust/macros/lib.rs | 44 ++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 rust/macros/concat_idents.rs diff --git a/rust/macros/concat_idents.rs b/rust/macros/concat_idents.rs new file mode 100644 index 000000000000..7e4b450f3a50 --- /dev/null +++ b/rust/macros/concat_idents.rs @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0 + +use proc_macro::{token_stream, Ident, TokenStream, TokenTree}; + +use crate::helpers::expect_punct; + +fn expect_ident(it: &mut token_stream::IntoIter) -> Ident { + if let Some(TokenTree::Ident(ident)) = it.next() { + ident + } else { + panic!("Expected Ident") + } +} + +pub(crate) fn concat_idents(ts: TokenStream) -> TokenStream { + let mut it = ts.into_iter(); + let a = expect_ident(&mut it); + assert_eq!(expect_punct(&mut it), ','); + let b = expect_ident(&mut it); + assert!(it.next().is_none(), "only two idents can be concatenated"); + let res = Ident::new(&format!("{a}{b}"), b.span()); + TokenStream::from_iter([TokenTree::Ident(res)]) +} diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 91764bfb1f89..15555e7ff487 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -2,6 +2,7 @@ //! Crate for all kernel procedural macros. +mod concat_idents; mod helpers; mod module; @@ -70,3 +71,46 @@ use proc_macro::TokenStream; pub fn module(ts: TokenStream) -> TokenStream { module::module(ts) } + +/// Concatenate two identifiers. +/// +/// This is useful in macros that need to declare or reference items with names +/// starting with a fixed prefix and ending in a user specified name. The resulting +/// identifier has the span of the second argument. +/// +/// # Examples +/// +/// ```ignore +/// use kernel::macro::concat_idents; +/// +/// macro_rules! pub_no_prefix { +/// ($prefix:ident, $($newname:ident),+) => { +/// $(pub(crate) const $newname: u32 = kernel::macros::concat_idents!($prefix, $newname);)+ +/// }; +/// } +/// +/// pub_no_prefix!( +/// binder_driver_return_protocol_, +/// BR_OK, +/// BR_ERROR, +/// BR_TRANSACTION, +/// BR_REPLY, +/// BR_DEAD_REPLY, +/// BR_TRANSACTION_COMPLETE, +/// BR_INCREFS, +/// BR_ACQUIRE, +/// BR_RELEASE, +/// BR_DECREFS, +/// BR_NOOP, +/// BR_SPAWN_LOOPER, +/// BR_DEAD_BINDER, +/// BR_CLEAR_DEATH_NOTIFICATION_DONE, +/// BR_FAILED_REPLY +/// ); +/// +/// assert_eq!(BR_OK, binder_driver_return_protocol_BR_OK); +/// ``` +#[proc_macro] +pub fn concat_idents(ts: TokenStream) -> TokenStream { + concat_idents::concat_idents(ts) +} From patchwork Fri Dec 2 16:14:37 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28967 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947743wrr; Fri, 2 Dec 2022 08:18:25 -0800 (PST) X-Google-Smtp-Source: AA0mqf4oMoDx74HwgALyMceSQ1RGRIYQ6ymDL8xKrvHzed6Kq65CZuqCPlULlLWmCkiqrqXRir7Z X-Received: by 2002:a17:903:2407:b0:17f:3da:f19d with SMTP id e7-20020a170903240700b0017f03daf19dmr55920288plo.147.1669997905177; Fri, 02 Dec 2022 08:18:25 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997905; cv=none; d=google.com; s=arc-20160816; b=QA/gfyK4m8HW/c2PHpZfVd+x0atJiLps70JCthKEeTaE1LZr5Rw6LawTqiuvU81YN2 rdWnprVdzSMJ/wPttT9Tvj2uEXPiFTSj96a+q+0MPT6nV5z7G5GiJZBTXgdCUGK70AaW /wD82Y2G4OR2mqDNCvYQQiBm8KQEAWOWZNN+42z4U5U9tkFPFp5gE5NGFx16m9zCVoYb NymetMMf3pFQ7fU5SxkK8CFeRCW8ssotUTu8U400iYMdGer0h1shUcz9j6Hb1117g85H vqz6zxxbkf3I3cOA+QJ3J+KkNPBJ0obopGJtE5PXrnELSGedx3Vbj7y9di+1Hp8/VLPa 42ww== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=RjLGWeRPJ8hgc0HRIV2im4kbJ60Iid6vvIeYEmsYPAU=; b=pGh5AcQaDd+2d6m5hCWqMwiLB6pV1n4OgvgtjzY9+5+MMkywZ3uGdzhY74ifrGl+gJ c7fkegdggGXRT6ZCPGySu0FibhPh0+I2fnT0PoAUsSdiMa86e12btPTAf0V47Wt6zuaI lXvpufiIikHd4XFo6A9YogvLJT7D165LZeq6spnE9nEp37ScgCOdHBQBegmede0U/Kkn q1vZr6Ao8sJVWsnG3MNkbD8YOs1papurr8sVN2ws1RQSniN2raFZnYlWLyXGNzxKdcW8 1so6Dj09uWP7TgTiffUH03Y0G4chvZesTkekR39nzkR49KX2ioFjLLHxxKn2L6BtVxko n8FA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=EZbLtNCw; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id x18-20020a17090300d200b0018983e6c429si6670928plc.3.2022.12.02.08.18.09; Fri, 02 Dec 2022 08:18:25 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=EZbLtNCw; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233960AbiLBQQ3 (ORCPT + 99 others); Fri, 2 Dec 2022 11:16:29 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53130 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233840AbiLBQQB (ORCPT ); Fri, 2 Dec 2022 11:16:01 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 9B4CFD6796; Fri, 2 Dec 2022 08:15:47 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 247A462322; Fri, 2 Dec 2022 16:15:47 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2A9DFC433D7; Fri, 2 Dec 2022 16:15:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997746; bh=N9xIU8sHH23NdLn+DWGLMxxQ8DUCPXG+6JF3lVqrUEQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=EZbLtNCwmhU8xS2so2fhn2yZrtw7LGAKhWwFwbhyGNuK2aqoZ1goBxC0ZLststZ8g wVOtwdwpFLaoppmzJW+U0VpyNfVLK9K/YuY4qO9pREd6xP8p41yaCE3ntnQ6oVVIyr PK/VXlzRvAnyexkoD1Sf6GZprtRWZgwRs/GaiuNRxyyr8WoI2Wqq226GfazZirKivK t9I0aCysJhq862FL544IS4n4d1CBfhU8LoNzDgPnXObzZC41iIPvUyPuo4Yk15ZhAy YUmloqTzIeoOzFfXyUXScNRRMeSZIe6zKtLd3y+Nj8y4xFsjcblX+u6nrRUWYc5T72 Y2gMYyw/K1d3A== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, =?utf-8?q?Sergio_Gonz=C3=A1lez_Collado?= Subject: [PATCH v2 06/28] rust: macros: add `#[vtable]` proc macro Date: Fri, 2 Dec 2022 17:14:37 +0100 Message-Id: <20221202161502.385525-7-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119723444305414?= X-GMAIL-MSGID: =?utf-8?q?1751119723444305414?= From: Gary Guo This procedural macro attribute provides a simple way to declare a trait with a set of operations that later users can partially implement, providing compile-time `HAS_*` boolean associated constants that indicate whether a particular operation was overridden. This is useful as the Rust counterpart to structs like `file_operations` where some pointers may be `NULL`, indicating an operation is not provided. For instance: #[vtable] trait Operations { fn read(...) -> Result { Err(EINVAL) } fn write(...) -> Result { Err(EINVAL) } } #[vtable] impl Operations for S { fn read(...) -> Result { ... } } assert_eq!(::HAS_READ, true); assert_eq!(::HAS_WRITE, false); Signed-off-by: Gary Guo Reviewed-by: Sergio González Collado [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Finn Behrens --- rust/kernel/prelude.rs | 2 +- rust/macros/lib.rs | 52 +++++++++++++++++++++++ rust/macros/vtable.rs | 95 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 rust/macros/vtable.rs diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 6a1c6b38327f..7c4c35bf3c66 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -15,7 +15,7 @@ pub use core::pin::Pin; pub use alloc::{boxed::Box, vec::Vec}; -pub use macros::module; +pub use macros::{module, vtable}; pub use super::{pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn}; diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 15555e7ff487..e40caaf0a656 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -5,6 +5,7 @@ mod concat_idents; mod helpers; mod module; +mod vtable; use proc_macro::TokenStream; @@ -72,6 +73,57 @@ pub fn module(ts: TokenStream) -> TokenStream { module::module(ts) } +/// Declares or implements a vtable trait. +/// +/// Linux's use of pure vtables is very close to Rust traits, but they differ +/// in how unimplemented functions are represented. In Rust, traits can provide +/// default implementation for all non-required methods (and the default +/// implementation could just return `Error::EINVAL`); Linux typically use C +/// `NULL` pointers to represent these functions. +/// +/// This attribute is intended to close the gap. Traits can be declared and +/// implemented with the `#[vtable]` attribute, and a `HAS_*` associated constant +/// will be generated for each method in the trait, indicating if the implementor +/// has overridden a method. +/// +/// This attribute is not needed if all methods are required. +/// +/// # Examples +/// +/// ```ignore +/// use kernel::prelude::*; +/// +/// // Declares a `#[vtable]` trait +/// #[vtable] +/// pub trait Operations: Send + Sync + Sized { +/// fn foo(&self) -> Result<()> { +/// Err(EINVAL) +/// } +/// +/// fn bar(&self) -> Result<()> { +/// Err(EINVAL) +/// } +/// } +/// +/// struct Foo; +/// +/// // Implements the `#[vtable]` trait +/// #[vtable] +/// impl Operations for Foo { +/// fn foo(&self) -> Result<()> { +/// # Err(EINVAL) +/// // ... +/// } +/// } +/// +/// assert_eq!(::HAS_FOO, true); +/// assert_eq!(::HAS_BAR, false); +/// ``` +#[proc_macro_attribute] +pub fn vtable(attr: TokenStream, ts: TokenStream) -> TokenStream { + vtable::vtable(attr, ts) +} + /// Concatenate two identifiers. /// /// This is useful in macros that need to declare or reference items with names diff --git a/rust/macros/vtable.rs b/rust/macros/vtable.rs new file mode 100644 index 000000000000..34d5e7fb5768 --- /dev/null +++ b/rust/macros/vtable.rs @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: GPL-2.0 + +use proc_macro::{Delimiter, Group, TokenStream, TokenTree}; +use std::collections::HashSet; +use std::fmt::Write; + +pub(crate) fn vtable(_attr: TokenStream, ts: TokenStream) -> TokenStream { + let mut tokens: Vec<_> = ts.into_iter().collect(); + + // Scan for the `trait` or `impl` keyword. + let is_trait = tokens + .iter() + .find_map(|token| match token { + TokenTree::Ident(ident) => match ident.to_string().as_str() { + "trait" => Some(true), + "impl" => Some(false), + _ => None, + }, + _ => None, + }) + .expect("#[vtable] attribute should only be applied to trait or impl block"); + + // Retrieve the main body. The main body should be the last token tree. + let body = match tokens.pop() { + Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace => group, + _ => panic!("cannot locate main body of trait or impl block"), + }; + + let mut body_it = body.stream().into_iter(); + let mut functions = Vec::new(); + let mut consts = HashSet::new(); + while let Some(token) = body_it.next() { + match token { + TokenTree::Ident(ident) if ident.to_string() == "fn" => { + let fn_name = match body_it.next() { + Some(TokenTree::Ident(ident)) => ident.to_string(), + // Possibly we've encountered a fn pointer type instead. + _ => continue, + }; + functions.push(fn_name); + } + TokenTree::Ident(ident) if ident.to_string() == "const" => { + let const_name = match body_it.next() { + Some(TokenTree::Ident(ident)) => ident.to_string(), + // Possibly we've encountered an inline const block instead. + _ => continue, + }; + consts.insert(const_name); + } + _ => (), + } + } + + let mut const_items; + if is_trait { + const_items = " + /// A marker to prevent implementors from forgetting to use [`#[vtable]`](vtable) + /// attribute when implementing this trait. + const USE_VTABLE_ATTR: (); + " + .to_owned(); + + for f in functions { + let gen_const_name = format!("HAS_{}", f.to_uppercase()); + // Skip if it's declared already -- this allows user override. + if consts.contains(&gen_const_name) { + continue; + } + // We don't know on the implementation-site whether a method is required or provided + // so we have to generate a const for all methods. + write!( + const_items, + "/// Indicates if the `{f}` method is overridden by the implementor. + const {gen_const_name}: bool = false;", + ) + .unwrap(); + } + } else { + const_items = "const USE_VTABLE_ATTR: () = ();".to_owned(); + + for f in functions { + let gen_const_name = format!("HAS_{}", f.to_uppercase()); + if consts.contains(&gen_const_name) { + continue; + } + write!(const_items, "const {gen_const_name}: bool = true;").unwrap(); + } + } + + let new_body = vec![const_items.parse().unwrap(), body.stream()] + .into_iter() + .collect(); + tokens.push(TokenTree::Group(Group::new(Delimiter::Brace, new_body))); + tokens.into_iter().collect() +} From patchwork Fri Dec 2 16:14:38 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28978 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948222wrr; Fri, 2 Dec 2022 08:19:21 -0800 (PST) X-Google-Smtp-Source: AA0mqf6VFHCxXuY7Yt1tvWvEuWfYeXkXONOn7roU7VlaVpy5XvvSTMlTTX6mobPJzHZ1i6Rk5/je X-Received: by 2002:a05:6a00:4205:b0:56b:a7cd:f47a with SMTP id cd5-20020a056a00420500b0056ba7cdf47amr73040915pfb.22.1669997961561; Fri, 02 Dec 2022 08:19:21 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997961; cv=none; d=google.com; s=arc-20160816; b=bquEnRh4iueStGannZHymEjNfjWjW0wl3SWeDEBh74joTkYowRkkkToMQbfej6FMcG 8IhBMJlPEhBAeJ36ym9Tz0foWSkMrOgkD1Yb/cC5WuWTeFPIi26XkkglLVbsV9enp8Gq zPrAAy9VwEIKcqrsBAdCrXVfiUIcLCYSZXeJ6eDkXltK/GXdiA+JKRLzr9Sgueizge0r Aj61vVCxU28J0rI4Ysou89WO1WWFvIaue6j46LM3c6PrW/JYfsedh6I60FY8ktBZnRVd 6S88abLZ8/918UnvqfVYdXVK1nMhO1izg6sex0UAXc/SiVj8TCYgKbw/M9dA464y8CzE q6Tw== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=4fyXOcj5pyhmYbtwyIowDOV2+zKKBxZMw4w9HYWOKWU=; b=ux6iQ3SwNe5Uz/95qKZel5dL/1iJFnKljVd3BXuCVp4cZ0aHPjpkByzOW8HevNnxme pIevGS6tW+lXQxScsSdwgcZmRLWpPrcoSke4DnQ5oxhnLYcSXnPyHH772sQu2dxwVFOr msfxACRHlKTKep/WEl6abMko6xv5kz5E46OkBKn60hrn50BFwSgdJo+9gSo6+WQuau8z Dl6mIcXIoDCI4fYRwTKCtMq3PAe0i92groL0/1w7S4qW0VSzDJRtISZPk9rRL1oZ4hXS BvBT/zklhBf2vanFu/6XeImPgi758ct/KsBO3Etg99O8Z3jMtqEmTXsywo0grCcIx86A 0fwQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=W62IFszh; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id 10-20020a63040a000000b0047688fc8acdsi7957078pge.474.2022.12.02.08.18.20; Fri, 02 Dec 2022 08:19:21 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=W62IFszh; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233809AbiLBQQc (ORCPT + 99 others); Fri, 2 Dec 2022 11:16:32 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53394 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233862AbiLBQQD (ORCPT ); Fri, 2 Dec 2022 11:16:03 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 54C36C5E23; Fri, 2 Dec 2022 08:15:50 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id D673B622E3; Fri, 2 Dec 2022 16:15:49 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 477E9C433C1; Fri, 2 Dec 2022 16:15:47 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997749; bh=sgzLAxpoWYOhhz1qABiMpx4C/FWitRtqVHgbxRNmqTw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=W62IFszhpXHSCCbVqzJqtBKmVgNo0dJPiLLrHgywJew1CTonjCHX8LwZJWuQ5Fj6v beN362k47MOfSDmMg+SPQ44vJlYiHIWNoKnaQNcKA7E+Sa3Kv+j/ekDSZuA3qVNB0g vx26evEACo7hi4P15XbUnqz9pp1NYPBESkY4Ao3GJubuu0tYK7g3XVODjhyQ8fWu3t ee+68mHIFRraI7SWta4Z26IjStxhYX8OXj/alA6YU/3q/UAmbmUrWxRHqBAtPrGYTp Ku7MjWS94W9RpLWCYPoEUfx9ZL9cdipOCVwghVTx1JekOnZTQ8j0p32a7dZDQ/lrck oPFDndrRJHMSQ== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 07/28] rust: macros: take string literals in `module!` Date: Fri, 2 Dec 2022 17:14:38 +0100 Message-Id: <20221202161502.385525-8-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119782473418377?= X-GMAIL-MSGID: =?utf-8?q?1751119782473418377?= From: Gary Guo Instead of taking binary string literals, take string ones instead, making it easier for users to define a module, i.e. instead of calling `module!` like: module! { ... name: b"rust_minimal", ... } now it is called as: module! { ... name: "rust_minimal", ... } Module names, aliases and license strings are restricted to ASCII only. However, the author and the description allows UTF-8. For simplicity (avoid parsing), escape sequences and raw string literals are not yet handled. Link: https://github.com/Rust-for-Linux/linux/issues/252 Link: https://lore.kernel.org/lkml/YukvvPOOu8uZl7+n@yadro.com/ Signed-off-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/macros/helpers.rs | 24 ++++++++++++++++++------ rust/macros/lib.rs | 12 ++++++------ rust/macros/module.rs | 10 +++++----- samples/rust/rust_minimal.rs | 8 ++++---- samples/rust/rust_print.rs | 8 ++++---- 5 files changed, 37 insertions(+), 25 deletions(-) diff --git a/rust/macros/helpers.rs b/rust/macros/helpers.rs index cdc7dc6135d2..cf7ad950dc1e 100644 --- a/rust/macros/helpers.rs +++ b/rust/macros/helpers.rs @@ -18,10 +18,16 @@ pub(crate) fn try_literal(it: &mut token_stream::IntoIter) -> Option { } } -pub(crate) fn try_byte_string(it: &mut token_stream::IntoIter) -> Option { - try_literal(it).and_then(|byte_string| { - if byte_string.starts_with("b\"") && byte_string.ends_with('\"') { - Some(byte_string[2..byte_string.len() - 1].to_string()) +pub(crate) fn try_string(it: &mut token_stream::IntoIter) -> Option { + try_literal(it).and_then(|string| { + if string.starts_with('\"') && string.ends_with('\"') { + let content = &string[1..string.len() - 1]; + if content.contains('\\') { + panic!("Escape sequences in string literals not yet handled"); + } + Some(content.to_string()) + } else if string.starts_with("r\"") { + panic!("Raw string literals are not yet handled"); } else { None } @@ -40,8 +46,14 @@ pub(crate) fn expect_punct(it: &mut token_stream::IntoIter) -> char { } } -pub(crate) fn expect_byte_string(it: &mut token_stream::IntoIter) -> String { - try_byte_string(it).expect("Expected byte string") +pub(crate) fn expect_string(it: &mut token_stream::IntoIter) -> String { + try_string(it).expect("Expected string") +} + +pub(crate) fn expect_string_ascii(it: &mut token_stream::IntoIter) -> String { + let string = try_string(it).expect("Expected string"); + assert!(string.is_ascii(), "Expected ASCII string"); + string } pub(crate) fn expect_end(it: &mut token_stream::IntoIter) { diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index e40caaf0a656..c1d385e345b9 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -25,20 +25,20 @@ use proc_macro::TokenStream; /// /// module!{ /// type: MyModule, -/// name: b"my_kernel_module", -/// author: b"Rust for Linux Contributors", -/// description: b"My very own kernel module!", -/// license: b"GPL", +/// name: "my_kernel_module", +/// author: "Rust for Linux Contributors", +/// description: "My very own kernel module!", +/// license: "GPL", /// params: { /// my_i32: i32 { /// default: 42, /// permissions: 0o000, -/// description: b"Example of i32", +/// description: "Example of i32", /// }, /// writeable_i32: i32 { /// default: 42, /// permissions: 0o644, -/// description: b"Example of i32", +/// description: "Example of i32", /// }, /// }, /// } diff --git a/rust/macros/module.rs b/rust/macros/module.rs index 186a5b8be23c..a7e363c2b044 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -108,11 +108,11 @@ impl ModuleInfo { match key.as_str() { "type" => info.type_ = expect_ident(it), - "name" => info.name = expect_byte_string(it), - "author" => info.author = Some(expect_byte_string(it)), - "description" => info.description = Some(expect_byte_string(it)), - "license" => info.license = expect_byte_string(it), - "alias" => info.alias = Some(expect_byte_string(it)), + "name" => info.name = expect_string_ascii(it), + "author" => info.author = Some(expect_string(it)), + "description" => info.description = Some(expect_string(it)), + "license" => info.license = expect_string_ascii(it), + "alias" => info.alias = Some(expect_string_ascii(it)), _ => panic!( "Unknown key \"{}\". Valid keys are: {:?}.", key, EXPECTED_KEYS diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs index 54ad17685742..dc05f4bbe27e 100644 --- a/samples/rust/rust_minimal.rs +++ b/samples/rust/rust_minimal.rs @@ -6,10 +6,10 @@ use kernel::prelude::*; module! { type: RustMinimal, - name: b"rust_minimal", - author: b"Rust for Linux Contributors", - description: b"Rust minimal sample", - license: b"GPL", + name: "rust_minimal", + author: "Rust for Linux Contributors", + description: "Rust minimal sample", + license: "GPL", } struct RustMinimal { diff --git a/samples/rust/rust_print.rs b/samples/rust/rust_print.rs index 09f737790f3f..8b39d9cef6d1 100644 --- a/samples/rust/rust_print.rs +++ b/samples/rust/rust_print.rs @@ -7,10 +7,10 @@ use kernel::prelude::*; module! { type: RustPrint, - name: b"rust_print", - author: b"Rust for Linux Contributors", - description: b"Rust printing macros sample", - license: b"GPL", + name: "rust_print", + author: "Rust for Linux Contributors", + description: "Rust printing macros sample", + license: "GPL", } struct RustPrint; From patchwork Fri Dec 2 16:14:39 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28983 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948519wrr; Fri, 2 Dec 2022 08:19:59 -0800 (PST) X-Google-Smtp-Source: AA0mqf4P3n+yXOaC7LwOqnW8CiS8JwmVBG6PGebFFerAvaNIoitFWNvJhfOUWD8rA6i8GC7oHlSo X-Received: by 2002:a17:902:d652:b0:189:a770:6eab with SMTP id y18-20020a170902d65200b00189a7706eabmr15248718plh.135.1669997999364; Fri, 02 Dec 2022 08:19:59 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997999; cv=none; d=google.com; s=arc-20160816; b=XKIto/yMfK8zVT0zEdXfk/A7Zb2TRmzFWJjy5tTD7REGMsA+n7kMQMHoWN/prUdD3T RgCkCiHNdL20S78SP7n03BWEkQRXaTQwDUvT5Q5IQf+L/wBAZXzUvxhmfmUSsNgk745z 6Z49IIiv72cYSTVXfi3pUX5x4MwhXVerr5JdXTEsNUVy1wOn9fDmcE2HpIOxnMwFnPjF 1kUdo1TVecZHpdmppxFJ0ZrUkQ/JsNlRddCUsmN4V8jdm6Xt6HNXUcXBiq1R7PUt3uYZ oZ36FC1n7TXzxema9+1evC07/Xml83PPQI3fojSxjAZ4yODfW90YFRTJ6HTrAJyvbtO7 FtRw== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=5lTc7/D3JX8xntYefWsiTSlrCd646eqIcghNpHLHPlE=; b=AXFDLFiSDEkrajPSFAnaY/mArWAFcCPmqMWrYdEGHd2tZVymjN5PyizR9aGLPWKKO0 7ALY35yYkdbzKK2CY8GRDRbHAy1/jDWXL1lOyopOPLDkv48C0D/YbpDJnuhuHnSf5sid LqhZxYumlo0pPQtc7HGImV6CE3dnShYCa67FaPOtGMQAHPPR2b16ZGHwxaTX2Kl/XkV4 ChZP0brJecL6ZC476NB+4ehwGD76ej1qTn2GyMHOTbLYcAK5BBMeoclGzOpUGSdqtvgF 9tp3rlgLafo6FhpwiCCKJno/PEX5HX/MTDtxhM5JMKkdCqop9SMnI7BKFv266ZrRznnh zB8w== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=XrlQLClC; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id nk11-20020a17090b194b00b0020a755f2b83si10310662pjb.100.2022.12.02.08.19.37; Fri, 02 Dec 2022 08:19:59 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=XrlQLClC; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233932AbiLBQQq (ORCPT + 99 others); Fri, 2 Dec 2022 11:16:46 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53516 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233877AbiLBQQK (ORCPT ); Fri, 2 Dec 2022 11:16:10 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 0FF46BF67C; Fri, 2 Dec 2022 08:15:53 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 9E7EF62331; Fri, 2 Dec 2022 16:15:52 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id DB730C433D7; Fri, 2 Dec 2022 16:15:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997752; bh=3ozUOhrx52YHTps33arj4MB6UyVgxyGlHJRWzGu7eJ0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=XrlQLClCl6lfpp1Axk7H9bFmwhtWQUtAGk45+2MVLgUfucuVL18toqPILDZqakMEa q4xgxTxkPKcVEnR0ei12ZpVF5v/5KQJN95pGG057rOFV8OHNC0F1sCPQYCUL7Gm2aC wKGHcsNz8rLyKzXdBcbB4tfsWHLI1dZ+DsoEJA8Uw9htPCOgbyRp3UmA90bFBysBvU 06Fuw2TDtnG1pWBBPQkchyWi6t9Mkz6GNIVDFQs4S90BBbDjn3cPwJktAlOd/3AcOZ G/J0pvRKUlBjyAtKsYF/bPGO74BvwLz1phTne5YnvFDUZ4jhXZ/mMbf683kZjvaJlN emn0duyZHTbug== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Finn Behrens Subject: [PATCH v2 08/28] rust: error: declare errors using macro Date: Fri, 2 Dec 2022 17:14:39 +0100 Message-Id: <20221202161502.385525-9-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119822180405600?= X-GMAIL-MSGID: =?utf-8?q?1751119822180405600?= From: Finn Behrens Add a macro to declare errors, which simplifies the work needed to add each one, avoids repetition of the code and makes it easier to change the way they are declared. Signed-off-by: Finn Behrens Reviewed-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/error.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 466b2a8fe569..b843f3445483 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -8,8 +8,16 @@ use alloc::collections::TryReserveError; /// Contains the C-compatible error codes. pub mod code { - /// Out of memory. - pub const ENOMEM: super::Error = super::Error(-(crate::bindings::ENOMEM as i32)); + macro_rules! declare_err { + ($err:tt $(,)? $($doc:expr),+) => { + $( + #[doc = $doc] + )* + pub const $err: super::Error = super::Error(-(crate::bindings::$err as i32)); + }; + } + + declare_err!(ENOMEM, "Out of memory."); } /// Generic integer kernel error. From patchwork Fri Dec 2 16:14:40 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28965 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947644wrr; Fri, 2 Dec 2022 08:18:14 -0800 (PST) X-Google-Smtp-Source: AA0mqf7nT0iyfig52yTzw+aJpEwwQENpKIGJiC3jL6kJyVzQjsQMErs5Wey/1SuvioIFjJnR39+m X-Received: by 2002:a17:902:7c82:b0:189:760d:c5f2 with SMTP id y2-20020a1709027c8200b00189760dc5f2mr33765945pll.90.1669997893832; Fri, 02 Dec 2022 08:18:13 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997893; cv=none; d=google.com; s=arc-20160816; b=ArGDT2VsAi7z4rdcp9UuLDe98UVLggoT/VtPhgSm3wUvPpzWAnoHzuixrRrlsjhDIZ W8RI+wRTU2thbcUJmnCje6tjqO9et5pTZgb4ehQpLVpcakMhGQx1t0Bz00SJBjFdNu01 ph242Fr67i5uEBuFIuLY1vwFX4ez5VwaAbygEdP0F8BnfbIHoKLFbUHB7DT8J9DBSVth Grfh9iNRA/bSSuWsXCe7j/9YanxdM/AwRCMUXWl4ucMwDL3tWci0Nz/3q+w4heiZKLRe iovSkb+9hNgSCE9VKcJXdKFx536UWZGsggm2bDpyleGtz6LPhXcifP/QD23D23zclxjH WKBQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=h5zCuKbiH55yMkcupNhz1upwfPmTsxxE8ej8UeSomwI=; b=vU2zd/aj7zn0HLdY2/zX3IxFxsuOtJN1bJ45CGlQUre3GcVXwW6YFBbJZpBNwI4EIv GYe17TjumCiJo/bcF9ucsJpK4WzJd/fVUIJSrrw0jFItiJLvigcD9WhiQywBK94x8Y1R II0NDl9v/a6iFlZ/LRHMDlT38Tb60Msdi9iAV0DvmPgNNTtqLoW+OAQS+Tc3Q4dvq9zH Yii8seN4aqOQ5fKjbdtaPeuee4HuO5zG60F0iFQBWgOPizhCtoYsYQ3sw3LXuZ+D5hfr /Lh7H6z/09ZjQzucPUUZTCuCcZ2YsKB4gAjgAjOQn7gKlKrdxhHcUqMum4JRzsqRZ9Z+ EoFg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=YYwF93ZC; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id ng18-20020a17090b1a9200b00202c7f4631esi8420775pjb.19.2022.12.02.08.17.57; Fri, 02 Dec 2022 08:18:13 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=YYwF93ZC; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233950AbiLBQQt (ORCPT + 99 others); Fri, 2 Dec 2022 11:16:49 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53724 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233941AbiLBQQX (ORCPT ); Fri, 2 Dec 2022 11:16:23 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [IPv6:2604:1380:4641:c500::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id D0C83DFB59; Fri, 2 Dec 2022 08:15:55 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 7085262333; Fri, 2 Dec 2022 16:15:55 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A2F36C43146; Fri, 2 Dec 2022 16:15:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997754; bh=8fgcMdAohdJYjCkWzYvRkRAqAWDQxKAVkDLoxRdowB4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=YYwF93ZCf7UzzXELsUSmRSnkfBJntXg8aLS8HuPV3a2J+ECFCY4+zLfWSyTjUBbV9 mZu5WpsHUtugXp36Jntkp3lfpE9LfC2GoSA9wID41WKDBmeNor1D8dm5lDkqEOjn71 x7fESbWVL3HkGd/xljpCodYSqtujtN16IbAID2aPCoPT2/PuMEqtF/Yj4DJcKCUZZL Qk7cXQf7FiwsrgXAaWpWyOPvTJx2COYvaGQXhyHiwnGsAP+HQyAUZ9JSDBpN8lQb+8 IZJ4pBSL2MDljf1Pvo0z4TfbWyBDCzvtNexWqV8QHlrbFEn4wyLl+MNx9eOCCBOLZW rSvYxHlQuZ8yA== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Viktor Garske Subject: [PATCH v2 09/28] rust: error: add codes from `errno-base.h` Date: Fri, 2 Dec 2022 17:14:40 +0100 Message-Id: <20221202161502.385525-10-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119711465868140?= X-GMAIL-MSGID: =?utf-8?q?1751119711465868140?= From: Viktor Garske Only a few codes were added so far. With the `declare_err!` macro in place, add the remaining ones (which is most of them) from `include/uapi/asm-generic/errno-base.h`. Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Signed-off-by: Viktor Garske Reviewed-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Finn Behrens --- rust/kernel/error.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index b843f3445483..861746f2422d 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -17,7 +17,40 @@ pub mod code { }; } + declare_err!(EPERM, "Operation not permitted."); + declare_err!(ENOENT, "No such file or directory."); + declare_err!(ESRCH, "No such process."); + declare_err!(EINTR, "Interrupted system call."); + declare_err!(EIO, "I/O error."); + declare_err!(ENXIO, "No such device or address."); + declare_err!(E2BIG, "Argument list too long."); + declare_err!(ENOEXEC, "Exec format error."); + declare_err!(EBADF, "Bad file number."); + declare_err!(ECHILD, "Exec format error."); + declare_err!(EAGAIN, "Try again."); declare_err!(ENOMEM, "Out of memory."); + declare_err!(EACCES, "Permission denied."); + declare_err!(EFAULT, "Bad address."); + declare_err!(ENOTBLK, "Block device required."); + declare_err!(EBUSY, "Device or resource busy."); + declare_err!(EEXIST, "File exists."); + declare_err!(EXDEV, "Cross-device link."); + declare_err!(ENODEV, "No such device."); + declare_err!(ENOTDIR, "Not a directory."); + declare_err!(EISDIR, "Is a directory."); + declare_err!(EINVAL, "Invalid argument."); + declare_err!(ENFILE, "File table overflow."); + declare_err!(EMFILE, "Too many open files."); + declare_err!(ENOTTY, "Not a typewriter."); + declare_err!(ETXTBSY, "Text file busy."); + declare_err!(EFBIG, "File too large."); + declare_err!(ENOSPC, "No space left on device."); + declare_err!(ESPIPE, "Illegal seek."); + declare_err!(EROFS, "Read-only file system."); + declare_err!(EMLINK, "Too many links."); + declare_err!(EPIPE, "Broken pipe."); + declare_err!(EDOM, "Math argument out of domain of func."); + declare_err!(ERANGE, "Math result not representable."); } /// Generic integer kernel error. From patchwork Fri Dec 2 16:14:41 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28966 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947688wrr; Fri, 2 Dec 2022 08:18:18 -0800 (PST) X-Google-Smtp-Source: AA0mqf4fl4ShPHOB/cenOQRMiWApXslbn16LLEvl2HoSOtby86Gb5G0ypqsAqvcOJ+dWYh0wlgE2 X-Received: by 2002:a17:902:7105:b0:186:ff4a:a1f0 with SMTP id a5-20020a170902710500b00186ff4aa1f0mr67449575pll.57.1669997897355; Fri, 02 Dec 2022 08:18:17 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997897; cv=none; d=google.com; s=arc-20160816; b=BGVf3HOqUpVq7YzVWmnukM+i3qi8WPS3LhXlnADk6OrAiCSi/FwfbZHYn5rdZLjHyh NyV9X1LMLqtz6EuOqh0m+dsO+z40hw8N3L1Ff8h908TPgv/VCIJYuJP5rthSdFa7YLjF +aZ5XowZ7u0m+sKcvsWkP/d1CbJxEMFGrm73D4nhYQqsiM8OofKH1AFaSuBieSDsloCY 652dP2t4RohRlmhdzvcUA2Aww4kWz+aHHmLtOfZrEShtWTlWkA0Yo05yxJQx0kAgG04a Z5apcHajkL5Aqbbw/M95/7lXnc3MXTa6xNcDN3QmE9Xr9B/ekB2w3Z0lEkXnTyuEimYW 0+uQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=EkNrpAFqjipBzdHQQXtLZS8Vobai3szRR8mHotjHa0A=; b=UBSjlA46Ao0t+VlqvfgWJjgKEOmjZGVJU2J+FF4txgYbBafTHKhSQymh9f2kU+6iFd dEiOx4UdE8LUOqc8yh5VpQa1xkb5ccKdyC9mjDtc+7wQxePbEkPMj5hCh0McArStpv2Q foTboYfgHAcqYuZmiZMeBlfiAcSs4Fflbt3DNko8HpTi41jep+RIBVfJvroxBdxjdOdE yHV0HXwUWlRYXhRRWbpRPCJyGz05k1Hxrs7c5DDZnLbeeprnMk083wgm09QPzWGZ6zA8 UWqOVt1EyKmxZr7D+I/c7fJlI90aBu4EBBdFRoWxKeom3gt1nMyOPo8Pc8z4wrQepeEY qUrA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=CaLL6Fg6; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id z1-20020a056a00240100b0057593ed4874si8456807pfh.315.2022.12.02.08.18.03; Fri, 02 Dec 2022 08:18:17 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=CaLL6Fg6; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233961AbiLBQQ4 (ORCPT + 99 others); Fri, 2 Dec 2022 11:16:56 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53134 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233895AbiLBQQ2 (ORCPT ); Fri, 2 Dec 2022 11:16:28 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [IPv6:2604:1380:4601:e00::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id B2457DF62F; Fri, 2 Dec 2022 08:16:00 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id 75525B821EF; Fri, 2 Dec 2022 16:15:59 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 788FAC433D7; Fri, 2 Dec 2022 16:15:55 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997758; bh=LHdw9TfUAyqQhYug7LeGlRw9Sq8mQsT00lw24iqeNao=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=CaLL6Fg6EFH72SLa7DwuDVUZqmHFJMaZ7EzzJVbe4oDzaplP1xRuLk9saKkzY1qT8 +j/GZdi+3tbWT9/clKmNH8MOXegnJvagR8NW03O92ux16Y/gym2zV54UV9qqmqEcv7 QSSCN935YzhVvdOlrb8iU48O66LiAmJWY0QEJFR9Ohh/KPfwDQvvs6/zOtxlImXrOL kPjTgeOhsGrsnL4FI2dt0SIJSsdQ21YLkFaetBE5KjX/zC4weTPfAAxV+tw23y+Sxe r8A24ohFgqTwMJW3qltF4xhWMxAX/3/z3ql4RGBdDXy082LWz8bzLQ9sWf/TiL/MUi 776M4eiEvRmow== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Adam Bratschi-Kaye , =?utf-8?b?TsOhbmRvciBJc3R2w6FuIEtyw6Fjc2Vy?= , Finn Behrens Subject: [PATCH v2 10/28] rust: error: add `From` implementations for `Error` Date: Fri, 2 Dec 2022 17:14:41 +0100 Message-Id: <20221202161502.385525-11-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119715371251046?= X-GMAIL-MSGID: =?utf-8?q?1751119715371251046?= From: Wedson Almeida Filho Add a set of `From` implementations for the `Error` kernel type. These implementations allow to easily convert from standard Rust error types to the usual kernel errors based on one of the `E*` integer codes. On top of that, the question mark Rust operator (`?`) implicitly performs a conversion on the error value using the `From` trait when propagating. Thus it is extra convenient to use. For instance, a kernel function that needs to convert a `i64` into a `i32` and to bubble up the error as a kernel error may write: fn f(x: i64) -> Result<...> { ... let y = i32::try_from(x)?; ... } which will transform the `TryFromIntError` into an `Err(EINVAL)`. Co-developed-by: Adam Bratschi-Kaye Signed-off-by: Adam Bratschi-Kaye Co-developed-by: Nándor István Krácser Signed-off-by: Nándor István Krácser Signed-off-by: Wedson Almeida Filho Reviewed-by: Finn Behrens [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/error.rs | 45 +++++++++++++++++++++++++++++++++++++++++++- rust/kernel/lib.rs | 1 + 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 861746f2422d..5b9751d7ff1d 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -4,7 +4,14 @@ //! //! C header: [`include/uapi/asm-generic/errno-base.h`](../../../include/uapi/asm-generic/errno-base.h) -use alloc::collections::TryReserveError; +use alloc::{ + alloc::{AllocError, LayoutError}, + collections::TryReserveError, +}; + +use core::convert::From; +use core::num::TryFromIntError; +use core::str::Utf8Error; /// Contains the C-compatible error codes. pub mod code { @@ -71,12 +78,48 @@ impl Error { } } +impl From for Error { + fn from(_: AllocError) -> Error { + code::ENOMEM + } +} + +impl From for Error { + fn from(_: TryFromIntError) -> Error { + code::EINVAL + } +} + +impl From for Error { + fn from(_: Utf8Error) -> Error { + code::EINVAL + } +} + impl From for Error { fn from(_: TryReserveError) -> Error { code::ENOMEM } } +impl From for Error { + fn from(_: LayoutError) -> Error { + code::ENOMEM + } +} + +impl From for Error { + fn from(_: core::fmt::Error) -> Error { + code::EINVAL + } +} + +impl From for Error { + fn from(e: core::convert::Infallible) -> Error { + match e {} + } +} + /// A [`Result`] with an [`Error`] error type. /// /// To be used as the return type for functions that may fail. diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index abd46261d385..ffc6626a6d29 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -12,6 +12,7 @@ //! do so first instead of bypassing this crate. #![no_std] +#![feature(allocator_api)] #![feature(core_ffi_c)] // Ensure conditional compilation based on the kernel configuration works; From patchwork Fri Dec 2 16:14:42 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28975 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948143wrr; Fri, 2 Dec 2022 08:19:14 -0800 (PST) X-Google-Smtp-Source: AA0mqf4WQvqrXh2Ck11dQaje+iOwMOkVn+BEltfBgZvt2rzzb1dmHK0Xzf7em1XObJRDCgRgkSv1 X-Received: by 2002:a17:902:ab8d:b0:187:1e83:2505 with SMTP id f13-20020a170902ab8d00b001871e832505mr58114282plr.132.1669997954164; Fri, 02 Dec 2022 08:19:14 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997954; cv=none; d=google.com; s=arc-20160816; b=M9zqYGAAAIsRyL65B2h1NJ5/c3DKlyxX4QnRrmrHh8ABtRyGrfteHRQDYzuMukjph+ /VE60Ec6q82OzR3qMcEmqDgqaVAcCe9pKtTAcMgTnWEdbFmg6YprqHSwNs4VGGpq9icl svox1cCYvTfhKnhCghFJ3gshOGLq3GcQ/LO5wzkKvppYWbThCDUFVRnTs55VK80sqlkz cRUp+keSm/wv+cfQQe+KoWQbqUEubx+wIg5HMyBaGA8xtSzRb8hu29vFhFQPeuaIwnWh /qZm4vZc1HA/R85T6QIsbNwfgxE34Qn9xNCBOroh0kAuG4U+CiBYGEK/woDZgx1TjkMD H8wA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=A0qpI7EYsSqghJalaKu3MDYcXxwvBLDAou/nUldtk6c=; b=QOeAliA/OabO3La3TqH++K5rusxRj3y1+TXm1vzbJ9IMXD9wDeoAzey/XD97CaLaNr B6FUnrZzyZ2mLCByXP2hmMLeB0HPm+uFUaWQ+ZxV05D5ZlgrKfRt5giVj6oYegqTkbcK S+vycQAS9LkhBHfkd0far1uMWRWPoQH2i6/tSnVUwoyR1LwPnlsp224NIxScC+jGrQl3 3mUQUwbtL9czegazJL8/q8zmo9YSpclBKx4n44Zu9BdSeKnzjhorICFVszjVOqhW0Lmw 4QCXanZPHxs1fL8WYii1//9TStwcLp1M/WwV6RwSUfzZa9ggVl/6qiS1nWEzGHowK5fx Gt4A== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=RV0FORfM; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id h9-20020aa79f49000000b00575a76e60a0si7401092pfr.83.2022.12.02.08.19.00; Fri, 02 Dec 2022 08:19:14 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=RV0FORfM; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S234000AbiLBQQ7 (ORCPT + 99 others); Fri, 2 Dec 2022 11:16:59 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53820 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233625AbiLBQQ3 (ORCPT ); Fri, 2 Dec 2022 11:16:29 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 680E0CC65A; Fri, 2 Dec 2022 08:16:03 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id 1E516B821F0; Fri, 2 Dec 2022 16:16:02 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C939EC43152; Fri, 2 Dec 2022 16:15:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997760; bh=Fu0cQySj6UrPLD5hDPAQuIBqC91+Uyo9Z9HV2mYAaok=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RV0FORfM/sgu1IT0HI/gc8w6bR0fwFSxo5jG4QS2W+B3fltkS0gl5tZUSXr4MmGGE IDOVl0VTFvK3xbvQuIuhsBU7sWjwn5PW4QKicCEwbD5w9hHZu0p0tqbvlIHhCQulpr ynzBlpngUBX0n6FP2A7TNmAOLKiPRtDTYOhmTtsOoKQJkvOd+VzMhFYKSp8y3YQwwB 1fGmbGvvU0q0vWAmTK4EphZ9H+pKZuqBP+GJPAR6K8JU8ANdyzYHNXidCgJmg1fWwz pTzX65kWdJFhveTMW2GZk6zZobgt2z8MblGS2EmWx4eBVbDXKYa0/hjv93ZXxryUZw WXVDAmk7+p4WQ== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 11/28] rust: prelude: add `error::code::*` constant items Date: Fri, 2 Dec 2022 17:14:42 +0100 Message-Id: <20221202161502.385525-12-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119775192772841?= X-GMAIL-MSGID: =?utf-8?q?1751119775192772841?= From: Wedson Almeida Filho It is convenient to have all the `Error` constant items (such as `EINVAL`) available as-is everywhere (i.e. for code using the kernel prelude such as kernel modules). Therefore, add all of them to the prelude. For instance, this allows to write `Err(EINVAL)` to create a kernel `Result`: fn f() -> Result<...> { ... Err(EINVAL) } Signed-off-by: Wedson Almeida Filho Reviewed-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 7c4c35bf3c66..1e08b08e9420 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -19,6 +19,6 @@ pub use macros::{module, vtable}; pub use super::{pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn}; -pub use super::error::{Error, Result}; +pub use super::error::{code::*, Error, Result}; pub use super::ThisModule; From patchwork Fri Dec 2 16:14:43 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28970 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947836wrr; Fri, 2 Dec 2022 08:18:38 -0800 (PST) X-Google-Smtp-Source: AA0mqf4zzIWjNpZvYJpff0Du1542I9ziRqDUX/yNQMPEf4+c1kKeZbYfagqwITH4TA3Z7ITXV5gK X-Received: by 2002:a17:906:158f:b0:78d:45e9:97be with SMTP id k15-20020a170906158f00b0078d45e997bemr58446000ejd.565.1669997918193; Fri, 02 Dec 2022 08:18:38 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997918; cv=none; d=google.com; s=arc-20160816; b=tdOCJWOmlRcB1nxTQiuWcTjKYS4qjJvmQparGdalxIT3mdufgbenOWUn70F+4D4BAQ jvA8IHyDV+X7LSA7UpH631nRZguMYgsTXBRie5ySokIr0Rmf+aE9+rTrKgLkz/+AGKUL XK0hFhOyLCqrNz7fQS/cy+U41PFcZM5cwML1SxNg4wrfqEijcPbtumfM+n+GJVu/lZbl /4Y9qvOMl5enjJgvrUdE/gfl2sgLlgWP2u39kZM5TO6ytOT1PWlWH6AfO52XuWaLOecw ShHO3Ak4mtFyUcATTipESxG7hBIHZGhYg41pvbgyDUsokIgXcp9IfXb6h76bb01LKLfX 2yzA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=v9FYS2cltDjwMDceAGbVK0nzIJuGiSPpmfouroMSSaE=; b=kMOLj3apshhOHcDQQk+dfIYilH7E8YnjGQFtY7jHkYciircFhM5KF+nyf1H6Mllp5G movk56nocO9hYFfIDNvs+cRZyRy+wuQvU2al39uEcOt/dkgxc2Zh63d9lnNKad5/ywKo OCpehxNXZCAYbDymANEoKZ5yp3DQop3bhst9Z/Vxcoi6BQW6BAFwth4FeG36TY+tiGD/ Or6+lO4fx2PSHowCjyV1ijZJnIn9tDeXp4EnH3CINj+/4+S/QOtltNtkibztZM7h3dwo wGngMhaqiQsnjX58sfGmbsgwXjD/ALdo/pgAXcUQ8dUhUYKDEsuB+bn+B+GUiZhegpNp 4IIg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b="CiJAL/O5"; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id z11-20020a056402274b00b004673015ab88si6610018edd.19.2022.12.02.08.18.13; Fri, 02 Dec 2022 08:18:38 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b="CiJAL/O5"; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233920AbiLBQRL (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:11 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53836 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233763AbiLBQQa (ORCPT ); Fri, 2 Dec 2022 11:16:30 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [IPv6:2604:1380:4641:c500::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 7CF9DE0741; Fri, 2 Dec 2022 08:16:04 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 1B1A06232F; Fri, 2 Dec 2022 16:16:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7045DC433D6; Fri, 2 Dec 2022 16:16:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997763; bh=BWxOvrWLIfwcfu7Jhuioqwg9jJ3x2xImME+v7sDyUfw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=CiJAL/O5nYOueC3kMzcu/WJ9tWK+syLi//zvidOY+ZbCvng0QEwaqhkIBAOkYZ6tF YL7NSmDYhSNwX7NKIdzoWnnnLOayWhLxk5LTnuaailbdpw10e8uOH78PhaK2smqIS4 5O6UYG3YS36WY07VHR5UNR+/9chYtNBmz1vcrQ1X5fnQHX+efxhXGZaXwp0Xw6Rt4h Axq2gozL7rgL2B48BeL/4z44odbI4wGlHRgvS34zlMaD6xYL98ph7cOV/awkD30FfK C828xpj1c+5fimCjg/KdsMZuiszP93w3mdSfsQFlXETPlLbcQiLxJ8sOJVbgPziFlH aFWxShjqHeZKQ== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 12/28] rust: alloc: add `RawVec::try_with_capacity_in()` constructor Date: Fri, 2 Dec 2022 17:14:43 +0100 Message-Id: <20221202161502.385525-13-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119736686657200?= X-GMAIL-MSGID: =?utf-8?q?1751119736686657200?= From: Miguel Ojeda Add the `RawVec::try_with_capacity_in()` constructor as the fallible version of `RawVec::with_capacity_in()`. The implementation follows the original. The infallible constructor is implemented in terms of the private `RawVec::allocate_in()` constructor, thus also add the private `RawVec::try_allocate_in()` constructor following the other. It will be used to implement `Vec::try_with_capacity{,_in}()` in the next patch. Reviewed-by: Gary Guo Signed-off-by: Miguel Ojeda --- rust/alloc/raw_vec.rs | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/rust/alloc/raw_vec.rs b/rust/alloc/raw_vec.rs index daf5f2da7168..c342f3843972 100644 --- a/rust/alloc/raw_vec.rs +++ b/rust/alloc/raw_vec.rs @@ -20,11 +20,11 @@ use crate::collections::TryReserveErrorKind::*; #[cfg(test)] mod tests; -#[cfg(not(no_global_oom_handling))] enum AllocInit { /// The contents of the new memory are uninitialized. Uninitialized, /// The new memory is guaranteed to be zeroed. + #[allow(dead_code)] Zeroed, } @@ -133,6 +133,14 @@ impl RawVec { Self::allocate_in(capacity, AllocInit::Uninitialized, alloc) } + /// Like `try_with_capacity`, but parameterized over the choice of + /// allocator for the returned `RawVec`. + #[allow(dead_code)] + #[inline] + pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { + Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc) + } + /// Like `with_capacity_zeroed`, but parameterized over the choice /// of allocator for the returned `RawVec`. #[cfg(not(no_global_oom_handling))] @@ -203,6 +211,30 @@ impl RawVec { } } + fn try_allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Result { + // Don't allocate here because `Drop` will not deallocate when `capacity` is 0. + if mem::size_of::() == 0 || capacity == 0 { + return Ok(Self::new_in(alloc)); + } + + let layout = Layout::array::(capacity).map_err(|_| CapacityOverflow)?; + alloc_guard(layout.size())?; + let result = match init { + AllocInit::Uninitialized => alloc.allocate(layout), + AllocInit::Zeroed => alloc.allocate_zeroed(layout), + }; + let ptr = result.map_err(|_| AllocError { layout, non_exhaustive: () })?; + + // Allocators currently return a `NonNull<[u8]>` whose length + // matches the size requested. If that ever changes, the capacity + // here should change to `ptr.len() / mem::size_of::()`. + Ok(Self { + ptr: unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }, + cap: capacity, + alloc, + }) + } + /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator. /// /// # Safety From patchwork Fri Dec 2 16:14:44 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28968 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947819wrr; Fri, 2 Dec 2022 08:18:35 -0800 (PST) X-Google-Smtp-Source: AA0mqf4GotR4uGzalRSsqm0g3ZY058eQXl+hiB/jITGybNS3JfSirFCvBWVD/PzLV2HeMpxQfe6V X-Received: by 2002:aa7:c2d6:0:b0:46c:38a4:a54c with SMTP id m22-20020aa7c2d6000000b0046c38a4a54cmr2480525edp.393.1669997915823; Fri, 02 Dec 2022 08:18:35 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997915; cv=none; d=google.com; s=arc-20160816; b=PxpUNDb0id4uTdbHziNBTrIiriy+OI0HDcSvFHLri9t068lTqtBBzETlPWFLVIrX85 KK5Nuc1mp0nuii9jsPdNiJLiL0BvxM23yojVSE0F1kJZP91Z1/+VB1stJfZBz78jeZw6 EmraHaFaTZasKa08dFGU/+v7tcwpugCiQewY0Z2jONi4cUwOCK+Qcst9HD6sOTuqTeK9 6Egihd+NIcgtvNyOXwPyHJkLbFWDvtUTvPqxeEn/JPlhBpik2FieJzL4ydSdBGRWmFGO plJiAB/qE/fVwQW5ZUt1zezpBmV9D9p6Ks+j13O27xtHlPh6AkjdTEBZry2x2gqPrUEa wRlQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=xNUDI3Zu8DgTqPldgTIuf8eJlS/9XRTq9TOIImrKYzc=; b=FlhO4us+3ajVOHqgWi1AE0UUC6XU/0lxV+4lVRRZo+Ab5/w8wJdNmNVfTjjc58jVEe aeHoiZnWUxElxWJ+7VCttXlNBmHUwQnRLV5iOgkFjSH6IRKMrquWsZsWnV9PXd9eDXg7 gsPs4CLYSv18ZbTRDlCOlF2Ja+EjzGFexl3MsmzoV+gcxMI+xXeOmt+hvySQaag9vbCC jfU2jlWUdOdwkB2qYiR3b+zNTpL9sX+gXJo1uLlmJ3bN9xgfyEUyFUS3JxiysWgAZ6rR 2Y96bmj/eMPzRgX7l2oK/l1R6HlfRaHECYkC+o0NMOL8UKn/aiquaBYo0xGRjes3etEN WoYQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=eZzKRlTs; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id hp12-20020a1709073e0c00b007c07f7713d7si7721558ejc.99.2022.12.02.08.18.10; Fri, 02 Dec 2022 08:18:35 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=eZzKRlTs; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233677AbiLBQRJ (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:09 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53844 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233975AbiLBQQa (ORCPT ); Fri, 2 Dec 2022 11:16:30 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [IPv6:2604:1380:4641:c500::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 075DAD208B; Fri, 2 Dec 2022 08:16:07 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id D90E562331; Fri, 2 Dec 2022 16:16:06 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 23525C43470; Fri, 2 Dec 2022 16:16:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997766; bh=2kl4siMs2CiGNBXEZpLt5Bkk+dmVvKDxrC3ndkxJ8nE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eZzKRlTsLe+l4byy89diKfAYGW9gr1GxcrGfLMdowMTdFbapJswUpLyrVVyMFWbo8 nhk0YPlJgcqDriXywi2C7Zw8JuJ0jh9n7KlBk6lAjjY9uWjuYyugHjwLAYWpfCIy2p tb8LNf6EKbYFWQ4GBZheYuFM8j945A3k55dDEBHfKG2vylvqpfjaMlfnaUxPIHLiI/ r8xdzY2y2mmB0jH2VK+lP7AaSoB3Emt3gw5hdKF0ljfbx1QY+S7hYHofcUgW20htQo Dkx3NcXamstan9FGeYI+3ZA1htUUU0U3DA9f54Bgu+5XX29VRgOHHQBkbLctLQGDJC ugz2s0P5LHqXg== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 13/28] rust: alloc: add `Vec::try_with_capacity{,_in}()` constructors Date: Fri, 2 Dec 2022 17:14:44 +0100 Message-Id: <20221202161502.385525-14-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119734865434690?= X-GMAIL-MSGID: =?utf-8?q?1751119734865434690?= From: Miguel Ojeda Add `Vec::try_with_capacity()` and `Vec::try_with_capacity_in()` as the fallible versions of `Vec::with_capacity()` and `Vec::with_capacity_in()`, respectively. The implementations follow the originals and use the previously added `RawVec::try_with_capacity_in()`. In turn, `Vec::try_with_capacity()` will be used to implement the `CString` type (which wraps a `Vec`) in a later patch. Reviewed-by: Gary Guo Signed-off-by: Miguel Ojeda Reviewed-by: Finn Behrens --- rust/alloc/raw_vec.rs | 1 - rust/alloc/vec/mod.rs | 89 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/rust/alloc/raw_vec.rs b/rust/alloc/raw_vec.rs index c342f3843972..eb77db5def55 100644 --- a/rust/alloc/raw_vec.rs +++ b/rust/alloc/raw_vec.rs @@ -135,7 +135,6 @@ impl RawVec { /// Like `try_with_capacity`, but parameterized over the choice of /// allocator for the returned `RawVec`. - #[allow(dead_code)] #[inline] pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc) diff --git a/rust/alloc/vec/mod.rs b/rust/alloc/vec/mod.rs index 540787804cc2..8ac6c1e3b2a8 100644 --- a/rust/alloc/vec/mod.rs +++ b/rust/alloc/vec/mod.rs @@ -472,6 +472,48 @@ impl Vec { Self::with_capacity_in(capacity, Global) } + /// Tries to construct a new, empty `Vec` with the specified capacity. + /// + /// The vector will be able to hold exactly `capacity` elements without + /// reallocating. If `capacity` is 0, the vector will not allocate. + /// + /// It is important to note that although the returned vector has the + /// *capacity* specified, the vector will have a zero *length*. For an + /// explanation of the difference between length and capacity, see + /// *[Capacity and reallocation]*. + /// + /// [Capacity and reallocation]: #capacity-and-reallocation + /// + /// # Examples + /// + /// ``` + /// let mut vec = Vec::try_with_capacity(10).unwrap(); + /// + /// // The vector contains no items, even though it has capacity for more + /// assert_eq!(vec.len(), 0); + /// assert_eq!(vec.capacity(), 10); + /// + /// // These are all done without reallocating... + /// for i in 0..10 { + /// vec.push(i); + /// } + /// assert_eq!(vec.len(), 10); + /// assert_eq!(vec.capacity(), 10); + /// + /// // ...but this may make the vector reallocate + /// vec.push(11); + /// assert_eq!(vec.len(), 11); + /// assert!(vec.capacity() >= 11); + /// + /// let mut result = Vec::try_with_capacity(usize::MAX); + /// assert!(result.is_err()); + /// ``` + #[inline] + #[stable(feature = "kernel", since = "1.0.0")] + pub fn try_with_capacity(capacity: usize) -> Result { + Self::try_with_capacity_in(capacity, Global) + } + /// Creates a `Vec` directly from the raw components of another vector. /// /// # Safety @@ -617,6 +659,53 @@ impl Vec { Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } } + /// Tries to construct a new, empty `Vec` with the specified capacity + /// with the provided allocator. + /// + /// The vector will be able to hold exactly `capacity` elements without + /// reallocating. If `capacity` is 0, the vector will not allocate. + /// + /// It is important to note that although the returned vector has the + /// *capacity* specified, the vector will have a zero *length*. For an + /// explanation of the difference between length and capacity, see + /// *[Capacity and reallocation]*. + /// + /// [Capacity and reallocation]: #capacity-and-reallocation + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_api)] + /// + /// use std::alloc::System; + /// + /// let mut vec = Vec::try_with_capacity_in(10, System).unwrap(); + /// + /// // The vector contains no items, even though it has capacity for more + /// assert_eq!(vec.len(), 0); + /// assert_eq!(vec.capacity(), 10); + /// + /// // These are all done without reallocating... + /// for i in 0..10 { + /// vec.push(i); + /// } + /// assert_eq!(vec.len(), 10); + /// assert_eq!(vec.capacity(), 10); + /// + /// // ...but this may make the vector reallocate + /// vec.push(11); + /// assert_eq!(vec.len(), 11); + /// assert!(vec.capacity() >= 11); + /// + /// let mut result = Vec::try_with_capacity_in(usize::MAX, System); + /// assert!(result.is_err()); + /// ``` + #[inline] + #[stable(feature = "kernel", since = "1.0.0")] + pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { + Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 }) + } + /// Creates a `Vec` directly from the raw components of another vector. /// /// # Safety From patchwork Fri Dec 2 16:14:45 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28969 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947825wrr; Fri, 2 Dec 2022 08:18:36 -0800 (PST) X-Google-Smtp-Source: AA0mqf4Xk6CZ3aSEvtoNInUY0RYhp9JnbKXoI+KJHMGVgP/4CD0+ib6nhADeMI4vpDJGizH59A23 X-Received: by 2002:a63:eb16:0:b0:477:5f10:204f with SMTP id t22-20020a63eb16000000b004775f10204fmr46052712pgh.144.1669997916263; Fri, 02 Dec 2022 08:18:36 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997916; cv=none; d=google.com; s=arc-20160816; b=Mh9UJDDHjLo1LBeMpwrx2u4MTxtujoHYKxpvT3vJEbIqn+AAiI6esJSY27ALU98apl JY9cnh17l+7FCMYNzjqKEzsk7EK559etYv7wMyudw1WYvBP7a8B2yKh+7BrUtxkpDRP1 dRnUpitLmg2egiSLZ45rf9M+Ppq4OAKuHzDfY6OVgu7nLWhk5QjnT4auLEek02bWFbGl jSSiKIViJZfxhObwIAW5QGUaBYPIgmP19XmxDROOgBtafvo92vvYrRrNzC2BJQRMwGcS GUigb8yslyuTtI7WtVV57P9lMg+TE4suaHjWLhM9qm91sqgL9bLUmHwx8HraeWAgnDyE h8Pg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=8FrNuK0IkU0HL5bgRPrz8xUBzj5CJaBgy53d1Jgff8I=; b=snV5ywF1W5NZTgm8TyYc3h0KUlfzxCxGLDvxz6XR+zMbckWTLLhU5ax4ZOfgdjFY7L AX96U93wZWmZI4Wq8Yfkz137zOs6MdofoGuAUxDozrPnk3r5e8uW+9xrrl1YOK8giIht 8tUHG1eZSvuNBZBxA6KQkMTOLQK5EDccdlQymMvlEDAOPNSDJCbAm6+U/c03O2thduOv 9XEPi2G0Ytyaf5dwOpuMG8Cxx2AAkjs/sNoejRFtSM+a3+2Tk2AJGoQFFMud/e7V/B4X 8WhfGHYvfheLCwcqxjEzew6aKWWoapCNId6rWf/rQBeoXFK5YJ84WaSYAB258De59x2u 2C/A== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=GSXqOdyv; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id d12-20020a17090ab30c00b0021978dd7104si4787465pjr.89.2022.12.02.08.18.20; Fri, 02 Dec 2022 08:18:36 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=GSXqOdyv; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233664AbiLBQRO (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:14 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53164 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233904AbiLBQQb (ORCPT ); Fri, 2 Dec 2022 11:16:31 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id D4A3FD96A5; Fri, 2 Dec 2022 08:16:09 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 717F062321; Fri, 2 Dec 2022 16:16:09 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id DF922C433D6; Fri, 2 Dec 2022 16:16:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997768; bh=H8GrOu07IRuGrUGFNBmi30U0LGPQsGBzhM2gPsNjUkU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GSXqOdyvoi8n6XgrzYEVF4fhRH5tBbsPS7tPg3IrH4f/YUi3ehHMrKcQl2ulQ/Kop XEQoyYJuaPY9MWeMLa5swvgmArnT5mNqjne8069nzMrXH9An5X8Hsv9aa4fgWZruPw v5eiihrOunn5lnROLNG7vBCwouR95qcm+C7ctlR14lAs3iewozoi8RA31YmSBBfxzK KoOcheBvdRW7gelraQ/dzHya7zURlnBmn9909XlxyvrIg/Wg01jxUpxIOZDgXp8toF Q4DmdoaBMRV26zZjzNGTpwLmKwOx7hT1Fm6cKp2FDR/3/ZQAx/yZ6nnOrJ6EyUM/A8 wc7KBED35y1cw== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 14/28] rust: str: add `BStr` type Date: Fri, 2 Dec 2022 17:14:45 +0100 Message-Id: <20221202161502.385525-15-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119735418382398?= X-GMAIL-MSGID: =?utf-8?q?1751119735418382398?= From: Gary Guo Add the `BStr` type, which is a byte string without UTF-8 validity guarantee. It is simply an alias to `[u8]`, but has a more evident semantical meaning. Signed-off-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index e45ff220ae50..3aa1a0cb9bf8 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -4,6 +4,11 @@ use core::fmt; +/// Byte string without UTF-8 validity guarantee. +/// +/// `BStr` is simply an alias to `[u8]`, but has a more evident semantical meaning. +pub type BStr = [u8]; + /// Allows formatting of [`fmt::Arguments`] into a raw buffer. /// /// It does not fail if callers write past the end of the buffer so that they can calculate the From patchwork Fri Dec 2 16:14:46 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28989 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp949631wrr; Fri, 2 Dec 2022 08:22:05 -0800 (PST) X-Google-Smtp-Source: AA0mqf7ShQWTlFPV5K/vI27fQ77eImhX9LT/xV/6r08wZE5ZUNttlnvFBfRjLFn5HmWd4iU2ZHmN X-Received: by 2002:a63:c41:0:b0:46f:81cc:5ecb with SMTP id 1-20020a630c41000000b0046f81cc5ecbmr46049707pgm.459.1669998125083; Fri, 02 Dec 2022 08:22:05 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669998125; cv=none; d=google.com; s=arc-20160816; b=dttpEwFO3KTiLsCu7sOgbtS8+o0XZHlVjMuhKCQoHYsBhMBGvgFTwdTbJGhA0ZONTE z4JhcmAecIpSmBBKjeHtyC/61n1CYy6j7fCpoIVR0tyeUkiJ3AdEUYzyjpWN6sQbzzsA y0E9oHMV2pAXvxRSWJpZFQIZLkMlCP4PM0E//XFybGFpEZ52ZVlJ7uy5wQXfcGOEtD0K SZnAapIEMWCxnmSWXA2FMqUT2I0dH0tv2LCaB1ozDIL+u9ZsHC39nPHpIFz02fTh/BnP Wa2kDul+MgPc/Z1yQIMrtF2NybmoZ70INozbdKo8UaqInnFFR4m8weEYdm76PmyGdtR+ PElQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=IyPWy02EE0dpTq9qkVjDt+wOCLTSekhAmKKv/tjb4m4=; b=ydoJUqXazgwnWbaMlFDwhYIhc0ksVvWGxMqlWTgV7OHzr5AeIgXZ+SpuNixxd9jWq5 jZTzZqi18l43JgFjVg+8bYRefFY7fuz2leZ7ZX0/rTcidhcWVuU5UI0Hp9GYyG90yUW2 R2oZG4HYVWURo8Xpqz2gVPif2yjc9EYkRXF+YMYKHAJPSoKDRndsMFkBlETFeDCCf++X ++9qa/GJF7Qg9KOK/62/jZ+Ru3BUS8k1kMgxgfOSUdt0HEvULxjbbXel6zH0Dwq3zmcJ YEtmnY4sRs0LgI+RYyCAiq0xKtSHugnuPpPxTRcFts/EQcqthpK1kYgHg795hcjsjnUy P5bQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=fky4ZsDJ; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id b10-20020a170902d88a00b00188712fdf88si7156430plz.46.2022.12.02.08.21.51; Fri, 02 Dec 2022 08:22:05 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=fky4ZsDJ; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233974AbiLBQTA (ORCPT + 99 others); Fri, 2 Dec 2022 11:19:00 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53170 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233911AbiLBQQb (ORCPT ); Fri, 2 Dec 2022 11:16:31 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 717BAE0753; Fri, 2 Dec 2022 08:16:12 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 0A54062333; Fri, 2 Dec 2022 16:16:12 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 73AAAC43470; Fri, 2 Dec 2022 16:16:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997771; bh=Pqv7nrnSw/i2nkLoHhZe36xor+0aWZ+RAfK3x5lb5qk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fky4ZsDJiU3etZhLmzF50RMo1Y6FOs5obZoZgvhHWPXb8facOP7VEFr4Vbq/zrBQR FE2/+nVF2wE3qw+KzUdijKQbNSLTznHojE3xp7hR++wAAwz9vAr4yosMQQKblualkO 0MpAJMnouHyArC23yrUXCRkJoCzS6rUaD8nFEFSUe8gP86xCz/mzyIuKZ2oag3jX0N KlTyl1gSJ4ID2Nh/WND4JAuXxS+P3i6vfLBYEyHz1zU4NTLlHcB0RupT7yExgcgWQq P5SnUwok4tIbVVl/N+RiT853BgCTYF4NNyDUbxYC1hXpyy7VLaxj7/52MaQsuJfWui EICKYz3IfPfew== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 15/28] rust: str: add `b_str!` macro Date: Fri, 2 Dec 2022 17:14:46 +0100 Message-Id: <20221202161502.385525-16-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119954213808496?= X-GMAIL-MSGID: =?utf-8?q?1751119954213808496?= From: Gary Guo Add the `b_str!` macro, which creates a new `BStr` from a string literal. It is usable in const contexts, for instance: const X: &BStr = b_str!("Example"); Signed-off-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 3aa1a0cb9bf8..95eb757c619d 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -9,6 +9,27 @@ use core::fmt; /// `BStr` is simply an alias to `[u8]`, but has a more evident semantical meaning. pub type BStr = [u8]; +/// Creates a new [`BStr`] from a string literal. +/// +/// `b_str!` converts the supplied string literal to byte string, so non-ASCII +/// characters can be included. +/// +/// # Examples +/// +/// ``` +/// # use kernel::b_str; +/// # use kernel::str::BStr; +/// const MY_BSTR: &BStr = b_str!("My awesome BStr!"); +/// ``` +#[macro_export] +macro_rules! b_str { + ($str:literal) => {{ + const S: &'static str = $str; + const C: &'static $crate::str::BStr = S.as_bytes(); + C + }}; +} + /// Allows formatting of [`fmt::Arguments`] into a raw buffer. /// /// It does not fail if callers write past the end of the buffer so that they can calculate the From patchwork Fri Dec 2 16:14:47 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28982 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948491wrr; Fri, 2 Dec 2022 08:19:56 -0800 (PST) X-Google-Smtp-Source: AA0mqf6gyliGJ30/8XlCZHjFh45s1K9RZIrkYau0AAs+xyIC0XIx84CB/4LVZHc2JTJV1qaHOtw+ X-Received: by 2002:a17:906:a89:b0:7bd:cc82:9abe with SMTP id y9-20020a1709060a8900b007bdcc829abemr18387901ejf.452.1669997996319; Fri, 02 Dec 2022 08:19:56 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997996; cv=none; d=google.com; s=arc-20160816; b=ybY2Fd4jSHWtrMsOljoxihPYMNetuQLqD6fXf7kfcXOCgrskTsT73avhxOhrUYvGZS ke+0JdCc1muYJlrOrkjG5sC4ks91m8l0DeZ2YTgadLKcXDjmd3YF2jNCToOD5LGU5UDP 5Wu5KN2RsZUJJn9MHEbhczCXzP29T8dS42cqKqooOSUPI4DSBBiI5F1dRh6kRBv/Up3B IT7/ptg69twnsrZ/Wvjcvef+arrMk7JE/BaET5AtbtGOU1SB9GJ11pbfbof4EyGNknSd Dd0Zu4bB2qq+0w6N3rPjLyLrmvg1uPWh6rETzWg7XEIgrcBAIv4Y3nbwk4pHC3trv+sV BKEQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=uGTpXwp4/Ud76Kgx/CSdrktdRrmkrxBhJ/lXIoLhWZY=; b=pwP0ECS1rEVImrL0Labb55GZAk3f0zfEpmO9ROSBR0tOyEC0i0hPlWsTAjYjDMNwhO Xpb2b5Nf8+sjmHjCNsjjN/Hy7TcuiY3LM2MblHcpAnhvhGfrSKTdDxuIkPiy0ryeSXUC NCxM/oI0eieDZUlAM+iZVm9wF9bbDRtz91gny9nnPTnq0+CGLSnA9izXFEfzAZvl9n35 qPKnijHDiSt0/1AZ+r70FYNa4dI9kYtcTeO2HR7pJlBYlS12aRlbW4ViWlQzM1a0Jqct GNw6b7srARQsBttPPnRRJtG+reepuJNLX8elOV0FmdJzl381y3grF/+vXb3MvapeOGlQ +p+Q== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=RO2tRiGg; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id f7-20020a170906138700b007c0a8ff3384si4210537ejc.763.2022.12.02.08.19.31; Fri, 02 Dec 2022 08:19:56 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=RO2tRiGg; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233839AbiLBQRX (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:23 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53672 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233982AbiLBQQp (ORCPT ); Fri, 2 Dec 2022 11:16:45 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id C0B48E0765; Fri, 2 Dec 2022 08:16:16 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id 746B0B821EF; Fri, 2 Dec 2022 16:16:15 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0E6F0C433D6; Fri, 2 Dec 2022 16:16:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997774; bh=JUlBWWC3mMeuYO9e7TQWTKj0jrpvH43QY5gJsfCQcio=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RO2tRiGgG/Ms9YLc+VilTZG50h2DgsKYnwKmVZ8YR8l8X3XBm5wSXymHu7CvZ7ZnS NYoQm6S57oEZAm9aX2MEWiLzmnrYOmkvPk8x8fzg6vtOPmi4rIGUPAZWrKpSTPn0CX WSNM/g/8ZJOE1B+6V0zxvK3bLJCJSTEM+jrns3GNl+FF9FAjNL5tv6Tt4bdlSUX8ml vvlTtnVU5kmPSsWxFWRZ2beNCDR9tSwNAASADCHBTa918AH7V1/RcLH8w4yeStkcam Bw8E4FyH1TYyEBNctUjXAqjn16k/pX58wImhoMnOCJO7hXk4b1kBF+5LRGr0KMpfrs idpOaz2UutPOA== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Milan Landaverde Subject: [PATCH v2 16/28] rust: str: add `CStr` type Date: Fri, 2 Dec 2022 17:14:47 +0100 Message-Id: <20221202161502.385525-17-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119819215106552?= X-GMAIL-MSGID: =?utf-8?q?1751119819215106552?= From: Gary Guo Add the `CStr` type, which is a borrowed string that is guaranteed to have exactly one `NUL` byte, which is at the end. It is used for interoperability with kernel APIs that take C strings. Add it to the prelude too. Co-developed-by: Alex Gaynor Signed-off-by: Alex Gaynor Co-developed-by: Milan Landaverde Signed-off-by: Milan Landaverde Signed-off-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/prelude.rs | 2 +- rust/kernel/str.rs | 169 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 170 insertions(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 1e08b08e9420..89c2c9f4e7a7 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -21,4 +21,4 @@ pub use super::{pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notic pub use super::error::{code::*, Error, Result}; -pub use super::ThisModule; +pub use super::{str::CStr, ThisModule}; diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 95eb757c619d..d66565f92f71 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -4,6 +4,11 @@ use core::fmt; +use crate::{ + bindings, + error::{code::*, Error}, +}; + /// Byte string without UTF-8 validity guarantee. /// /// `BStr` is simply an alias to `[u8]`, but has a more evident semantical meaning. @@ -30,6 +35,170 @@ macro_rules! b_str { }}; } +/// Possible errors when using conversion functions in [`CStr`]. +#[derive(Debug, Clone, Copy)] +pub enum CStrConvertError { + /// Supplied bytes contain an interior `NUL`. + InteriorNul, + + /// Supplied bytes are not terminated by `NUL`. + NotNulTerminated, +} + +impl From for Error { + #[inline] + fn from(_: CStrConvertError) -> Error { + EINVAL + } +} + +/// A string that is guaranteed to have exactly one `NUL` byte, which is at the +/// end. +/// +/// Used for interoperability with kernel APIs that take C strings. +#[repr(transparent)] +pub struct CStr([u8]); + +impl CStr { + /// Returns the length of this string excluding `NUL`. + #[inline] + pub const fn len(&self) -> usize { + self.len_with_nul() - 1 + } + + /// Returns the length of this string with `NUL`. + #[inline] + pub const fn len_with_nul(&self) -> usize { + // SAFETY: This is one of the invariant of `CStr`. + // We add a `unreachable_unchecked` here to hint the optimizer that + // the value returned from this function is non-zero. + if self.0.is_empty() { + unsafe { core::hint::unreachable_unchecked() }; + } + self.0.len() + } + + /// Returns `true` if the string only includes `NUL`. + #[inline] + pub const fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Wraps a raw C string pointer. + /// + /// # Safety + /// + /// `ptr` must be a valid pointer to a `NUL`-terminated C string, and it must + /// last at least `'a`. When `CStr` is alive, the memory pointed by `ptr` + /// must not be mutated. + #[inline] + pub unsafe fn from_char_ptr<'a>(ptr: *const core::ffi::c_char) -> &'a Self { + // SAFETY: The safety precondition guarantees `ptr` is a valid pointer + // to a `NUL`-terminated C string. + let len = unsafe { bindings::strlen(ptr) } + 1; + // SAFETY: Lifetime guaranteed by the safety precondition. + let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len as _) }; + // SAFETY: As `len` is returned by `strlen`, `bytes` does not contain interior `NUL`. + // As we have added 1 to `len`, the last byte is known to be `NUL`. + unsafe { Self::from_bytes_with_nul_unchecked(bytes) } + } + + /// Creates a [`CStr`] from a `[u8]`. + /// + /// The provided slice must be `NUL`-terminated, does not contain any + /// interior `NUL` bytes. + pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> { + if bytes.is_empty() { + return Err(CStrConvertError::NotNulTerminated); + } + if bytes[bytes.len() - 1] != 0 { + return Err(CStrConvertError::NotNulTerminated); + } + let mut i = 0; + // `i + 1 < bytes.len()` allows LLVM to optimize away bounds checking, + // while it couldn't optimize away bounds checks for `i < bytes.len() - 1`. + while i + 1 < bytes.len() { + if bytes[i] == 0 { + return Err(CStrConvertError::InteriorNul); + } + i += 1; + } + // SAFETY: We just checked that all properties hold. + Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) }) + } + + /// Creates a [`CStr`] from a `[u8]` without performing any additional + /// checks. + /// + /// # Safety + /// + /// `bytes` *must* end with a `NUL` byte, and should only have a single + /// `NUL` byte (or the string will be truncated). + #[inline] + pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr { + // SAFETY: Properties of `bytes` guaranteed by the safety precondition. + unsafe { core::mem::transmute(bytes) } + } + + /// Returns a C pointer to the string. + #[inline] + pub const fn as_char_ptr(&self) -> *const core::ffi::c_char { + self.0.as_ptr() as _ + } + + /// Convert the string to a byte slice without the trailing 0 byte. + #[inline] + pub fn as_bytes(&self) -> &[u8] { + &self.0[..self.len()] + } + + /// Convert the string to a byte slice containing the trailing 0 byte. + #[inline] + pub const fn as_bytes_with_nul(&self) -> &[u8] { + &self.0 + } + + /// Yields a [`&str`] slice if the [`CStr`] contains valid UTF-8. + /// + /// If the contents of the [`CStr`] are valid UTF-8 data, this + /// function will return the corresponding [`&str`] slice. Otherwise, + /// it will return an error with details of where UTF-8 validation failed. + /// + /// # Examples + /// + /// ``` + /// # use kernel::str::CStr; + /// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap(); + /// assert_eq!(cstr.to_str(), Ok("foo")); + /// ``` + #[inline] + pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> { + core::str::from_utf8(self.as_bytes()) + } + + /// Unsafely convert this [`CStr`] into a [`&str`], without checking for + /// valid UTF-8. + /// + /// # Safety + /// + /// The contents must be valid UTF-8. + /// + /// # Examples + /// + /// ``` + /// # use kernel::c_str; + /// # use kernel::str::CStr; + /// // SAFETY: String literals are guaranteed to be valid UTF-8 + /// // by the Rust compiler. + /// let bar = c_str!("ツ"); + /// assert_eq!(unsafe { bar.as_str_unchecked() }, "ツ"); + /// ``` + #[inline] + pub unsafe fn as_str_unchecked(&self) -> &str { + unsafe { core::str::from_utf8_unchecked(self.as_bytes()) } + } +} + /// Allows formatting of [`fmt::Arguments`] into a raw buffer. /// /// It does not fail if callers write past the end of the buffer so that they can calculate the From patchwork Fri Dec 2 16:14:48 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28971 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp947950wrr; Fri, 2 Dec 2022 08:18:53 -0800 (PST) X-Google-Smtp-Source: AA0mqf71iKrRPfOJSZiGUuimyKjYKkPiA/uE1gIxZWHok7SHNDtWmGl4JeZMquounrfqXnlDPzrH X-Received: by 2002:aa7:c9d0:0:b0:458:ed79:ed5 with SMTP id i16-20020aa7c9d0000000b00458ed790ed5mr49233171edt.374.1669997933372; Fri, 02 Dec 2022 08:18:53 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997933; cv=none; d=google.com; s=arc-20160816; b=gnZGQ+uu997dv2NLExioB1rGc0fE8kR9K1GunzL/6oM/t7RUTKjIxbeIxqHEe/fHG5 HfgY2d9BdbLN6uMXp3fbdzOy7tAn/Lmc6j/wXHpN2XnAwJtd9RSCr/skHrfFAlljrSDH x+DR22YctktZ5OJSWKAZN8u0oiHltcK7xwPIIsQ9khkjlpiFIL8Xl10kLbVEMYx5Mvo5 5uYfDRiVWV1RkXvAoqAfPn+qzLnfquYQvhqCES+V9A4AuRWuOetWjXuQmV2HoKRfLnJs 9D6KAiM7IPRMiJKGBV+gagNotYYoWEjoARWj9LyOn06a975zt8wq5nSYpVd4xPc0l2iw XsUA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=IqCDQzIn8PmU18Zo/aENvJsgJezqjD8PzkMlbpxej+E=; b=lSUlqywJgYXhVkw2oeM18jyas3QDcNNveiQQKqDBKG9thZHMyLZK7CUKvvdEjgfVti 1Jz3RIrsry2xqjynqyCg9Mz+YsgVUD8t3MzD1SasI6uVp+GtVVTuqvmNSbXNWsXiQdGL zKGRwEJGefx29mBr5wJbiWscwPoFDwX+PuUKzl4EIYbgDLRtPYxUNhkRdjVxbIXTITdZ Htefr/h+NF7coal/S0UHtV7DgT+Xu7ZNL8oqQVlxSslB4IlEuB4X1E0Ylg0UpPcVe95G /GCND3gGi8/NXIDWF//+IWaNmmIS8q5N09sTOGCcBhTT7rO+YxFJg0mXvZbluQj6x4my EiKA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b="gFYHA5/t"; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id nb30-20020a1709071c9e00b007acf3aed468si6842766ejc.786.2022.12.02.08.18.26; Fri, 02 Dec 2022 08:18:53 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b="gFYHA5/t"; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233850AbiLBQRS (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:18 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53212 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233883AbiLBQQq (ORCPT ); Fri, 2 Dec 2022 11:16:46 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [IPv6:2604:1380:4641:c500::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 2655BAD9AC; Fri, 2 Dec 2022 08:16:18 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id AA01862321; Fri, 2 Dec 2022 16:16:17 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D479AC4314F; Fri, 2 Dec 2022 16:16:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997777; bh=lSrHt+F2Ze+/0shcXyGqT2iYHkhHUzJS18BpgwZFKfQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=gFYHA5/tQJfrLY2tIEHdQ9SHhxkxhRakBLeDbRT0zxpv7dx9kQLQtuJazH6m6aVXf gnKkepKJPuKvfcuB+2X2jvp5nyDj+F6CRXRHzsc9xxdl5fD+uqVQACAuL+HBDYLfhA cZws+wpA/mtCbx2+K8HrvbpURAtnDTV7VEDKZmDKZ+GlnUV1NunRfGyBdTCeVwecce 8S5JEe5HR6yPWnaeesWeC+sKAqzLPdF6sjP5TIWLeSBKu/ynoy1Pzr3fN4gkdD3U9B c8n9On8iuaxdeTN4ShAFSbhU3ezYZ6NvicvI+dCMmS9AWRHvnTW38tF1CZJ1SOoHLZ /KyNk796JJ6PQ== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Morgan Bartlett Subject: [PATCH v2 17/28] rust: str: implement several traits for `CStr` Date: Fri, 2 Dec 2022 17:14:48 +0100 Message-Id: <20221202161502.385525-18-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119752981624946?= X-GMAIL-MSGID: =?utf-8?q?1751119752981624946?= From: Gary Guo Implement `Debug`, `Display`, `Deref` (into `BStr`), `AsRef` and a set of `Index<...>` traits. This makes it `CStr` more convenient to use (and closer to `str`). Co-developed-by: Alex Gaynor Signed-off-by: Alex Gaynor Co-developed-by: Morgan Bartlett Signed-off-by: Morgan Bartlett Signed-off-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 124 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 123 insertions(+), 1 deletion(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index d66565f92f71..11d297c1a61c 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -2,7 +2,8 @@ //! String representations. -use core::fmt; +use core::fmt::{self, Write}; +use core::ops::{self, Deref, Index}; use crate::{ bindings, @@ -199,6 +200,127 @@ impl CStr { } } +impl fmt::Display for CStr { + /// Formats printable ASCII characters, escaping the rest. + /// + /// ``` + /// # use kernel::c_str; + /// # use kernel::str::CStr; + /// # use kernel::str::CString; + /// let penguin = c_str!("🐧"); + /// let s = CString::try_from_fmt(fmt!("{}", penguin)).unwrap(); + /// assert_eq!(s.as_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes()); + /// + /// let ascii = c_str!("so \"cool\""); + /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap(); + /// assert_eq!(s.as_bytes_with_nul(), "so \"cool\"\0".as_bytes()); + /// ``` + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for &c in self.as_bytes() { + if (0x20..0x7f).contains(&c) { + // Printable character. + f.write_char(c as char)?; + } else { + write!(f, "\\x{:02x}", c)?; + } + } + Ok(()) + } +} + +impl fmt::Debug for CStr { + /// Formats printable ASCII characters with a double quote on either end, escaping the rest. + /// + /// ``` + /// # use kernel::c_str; + /// # use kernel::str::CStr; + /// # use kernel::str::CString; + /// let penguin = c_str!("🐧"); + /// let s = CString::try_from_fmt(fmt!("{:?}", penguin)).unwrap(); + /// assert_eq!(s.as_bytes_with_nul(), "\"\\xf0\\x9f\\x90\\xa7\"\0".as_bytes()); + /// + /// // Embedded double quotes are escaped. + /// let ascii = c_str!("so \"cool\""); + /// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap(); + /// assert_eq!(s.as_bytes_with_nul(), "\"so \\\"cool\\\"\"\0".as_bytes()); + /// ``` + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("\"")?; + for &c in self.as_bytes() { + match c { + // Printable characters. + b'\"' => f.write_str("\\\"")?, + 0x20..=0x7e => f.write_char(c as char)?, + _ => write!(f, "\\x{:02x}", c)?, + } + } + f.write_str("\"") + } +} + +impl AsRef for CStr { + #[inline] + fn as_ref(&self) -> &BStr { + self.as_bytes() + } +} + +impl Deref for CStr { + type Target = BStr; + + #[inline] + fn deref(&self) -> &Self::Target { + self.as_bytes() + } +} + +impl Index> for CStr { + type Output = CStr; + + #[inline] + fn index(&self, index: ops::RangeFrom) -> &Self::Output { + // Delegate bounds checking to slice. + // Assign to _ to mute clippy's unnecessary operation warning. + let _ = &self.as_bytes()[index.start..]; + // SAFETY: We just checked the bounds. + unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) } + } +} + +impl Index for CStr { + type Output = CStr; + + #[inline] + fn index(&self, _index: ops::RangeFull) -> &Self::Output { + self + } +} + +mod private { + use core::ops; + + // Marker trait for index types that can be forward to `BStr`. + pub trait CStrIndex {} + + impl CStrIndex for usize {} + impl CStrIndex for ops::Range {} + impl CStrIndex for ops::RangeInclusive {} + impl CStrIndex for ops::RangeToInclusive {} +} + +impl Index for CStr +where + Idx: private::CStrIndex, + BStr: Index, +{ + type Output = >::Output; + + #[inline] + fn index(&self, index: Idx) -> &Self::Output { + &self.as_bytes()[index] + } +} + /// Allows formatting of [`fmt::Arguments`] into a raw buffer. /// /// It does not fail if callers write past the end of the buffer so that they can calculate the From patchwork Fri Dec 2 16:14:49 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28979 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948342wrr; Fri, 2 Dec 2022 08:19:38 -0800 (PST) X-Google-Smtp-Source: AA0mqf7jlkNVuqvWqXIpIWwC/3bLsIIkxW3VLV5ddce9Eh06ghWFwKrSy+Hg2LPm0W54gXnN5ZEJ X-Received: by 2002:a05:6a00:4396:b0:575:1493:88d0 with SMTP id bt22-20020a056a00439600b00575149388d0mr28665049pfb.70.1669997977725; Fri, 02 Dec 2022 08:19:37 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997977; cv=none; d=google.com; s=arc-20160816; b=G5KxKGbMAOZI5XWIatIHwmR1vPqLgb20ocL/9EpfPq0gabHhhIFGEme+ffj2pvGPwO QR+DEmgq+hvSMOKAHXHfIygjggdgbnmKuXY+RSn08JFGsRIMfNzaFkOzE5KVnfHTVlUy X7/CGi0JL2eELePoMqpWfrYo9EKx2uKwGMeuQEoFJlLz0U4eBRw8QC/IhOm7i20KAXgy PLUN/L59VsV5bdDovL+FpxQde2qBZ2zIwd0htpuVQCOOb7ENzFUB1MKoTaE9UCmQ9R4G xsyC42BPC0hj2aaUWw20WuowmvapqLK52iTdcbeDAsViDxLL7E7pR55Bpv8OF7Oajqj/ KnmA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=rqIoOiosdNVnt6bctFzhXBJCZtOw+pblXMRa9R1VfP4=; b=ZZaXOZIBae/68U0Tl6YT1BWkgWs+U73pR5NlEFBunyiUsJyXzU1QmFJ/aGim/1yUbL rB8iVJIGDANZ8d0erX7pzHAk/dm8AL0hk/qkWbm14/yh8lL5O8qs1ibMOnQt6CwuTv/g Kc3DiE49R/ckdCkNQRuZDCCWhON5MkGa5+Z0Zjl41KuYhYacdlxJthO1OuJSm7MrCaCm SQ9OJwRRbPNH47bZy+eRTJ6tCruXyUIOSGx+0D3LIU8uSNNYGFDJxVlRJ8/u0OYwi6/d +29sD/2MHDNbe+eZhUFmOXvznLXp085LEkbnOQgLJVJbU+WZpXShi6W8ZIK9Txned0+q LHig== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=RWEPSFt+; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id nu3-20020a17090b1b0300b0020a47a4c951si8528762pjb.147.2022.12.02.08.19.24; Fri, 02 Dec 2022 08:19:37 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=RWEPSFt+; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233973AbiLBQR1 (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:27 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53704 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233930AbiLBQQq (ORCPT ); Fri, 2 Dec 2022 11:16:46 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 6F48FD96A7; Fri, 2 Dec 2022 08:16:22 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id 234FCB821F0; Fri, 2 Dec 2022 16:16:21 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id AB17CC433D6; Fri, 2 Dec 2022 16:16:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997779; bh=McON9F/ZloZh668lpPUE38B16LOD0pkq/6vZiAe96vI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RWEPSFt+U4afB3ouQrOI1dLiNWj3KsyQrFnMe6wXclW9FaDMwanxU+sSaojYWuOfs 35U/6EixklK6+dHznILLTTZUQ+02HcE89fQkAbYwqMtsLsaGz06G5yQQuLwNZbbwAW l0R/1d//A1po2ye7IzgGzH8YEIhamMRWQKFj93NMgVxRrGZR5QknhIM4bh0OhHWiQ8 tLzZ7fnaW338OGOWQ6OgQ0iM92aJUl2ccLt5ZlbD9kffjzE1c+srOlAe8p2CgiQRey OFJGPprap12XvVxfEWApZfBxhkdTF7iNCGlbUVKZFhA7mbQmthzoY9EYa2TwCBkF0N 4wg11YkLdQYwQ== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Milan Landaverde Subject: [PATCH v2 18/28] rust: str: add `CStr` unit tests Date: Fri, 2 Dec 2022 17:14:49 +0100 Message-Id: <20221202161502.385525-19-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119799532127020?= X-GMAIL-MSGID: =?utf-8?q?1751119799532127020?= From: Milan Landaverde Add unit tests for `CStr::from_bytes_with_nul()` and `CStr::from_bytes_with_nul_unchecked()`. These serve as an example of the first unit tests for Rust code (i.e. different from documentation tests). Signed-off-by: Milan Landaverde [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 11d297c1a61c..3ed685cb5a3c 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -321,6 +321,35 @@ where } } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_cstr_to_str() { + let good_bytes = b"\xf0\x9f\xa6\x80\0"; + let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap(); + let checked_str = checked_cstr.to_str().unwrap(); + assert_eq!(checked_str, "🦀"); + } + + #[test] + #[should_panic] + fn test_cstr_to_str_panic() { + let bad_bytes = b"\xc3\x28\0"; + let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap(); + checked_cstr.to_str().unwrap(); + } + + #[test] + fn test_cstr_as_str_unchecked() { + let good_bytes = b"\xf0\x9f\x90\xA7\0"; + let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap(); + let unchecked_str = unsafe { checked_cstr.as_str_unchecked() }; + assert_eq!(unchecked_str, "🐧"); + } +} + /// Allows formatting of [`fmt::Arguments`] into a raw buffer. /// /// It does not fail if callers write past the end of the buffer so that they can calculate the From patchwork Fri Dec 2 16:14:50 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28985 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948868wrr; Fri, 2 Dec 2022 08:20:37 -0800 (PST) X-Google-Smtp-Source: AA0mqf4bdUU4RQIl5mx+hRZYg/pJ9kcZFPCUNeHZrDcHRzEEHA3wX28Np/5PYFuT68Hs9hYCnB/j X-Received: by 2002:a17:902:ce90:b0:186:b46d:da5e with SMTP id f16-20020a170902ce9000b00186b46dda5emr54034633plg.92.1669998036764; Fri, 02 Dec 2022 08:20:36 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669998036; cv=none; d=google.com; s=arc-20160816; b=lKS/P5EkOnbqCo7ovKKoKZIMILjYmKZMEKiSH7Xt6N66fBH0V02Hk01ew+eMdkw+Zl qPYZViayjigCqP2TaC6RNgO7E/Wkf0Dy1sAjO84OnrtPqyQNtUqe/s4yAWgpmepGVX9i fO2WJWB6h+GcLFh3GSr3JaxT6v3+1NNVxPINfh/OSk7Eh7f3AyIaEdPI+nZHWD7agta+ 6Q3iP5sSaPE/DS/Hcvc/vpAqKz/vnrWe/C22l9ksNIm3enag4c0JEoQ7JEkl23o9gcRj iP15nHXNAJeqJxmBvEqlhYL85ZLpVEEX+XRjZe4kEyLByXLC5YKnCQWDpPPofUWM9W5z optw== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=X459mjYQMhHgNGjScvZUf41IYsPRRuS/HAL1lgTwBGc=; b=y+5u98GcGCqRdl++ZpI22Q0iNjdIhvKkJNXngDimnyTP8Q1FggYvVUIWiexIHMcNMA ZHJ1MvOZRR8sQEyAcpGnMd3B/L/6fDbUaaJKEMj4gw1zFH+grmt+eLg+fa+VC7SZkuBp IzPtVoeLfW1vJVqxmkP2+Li7jyZ5PLBOVsiuEmzaE8eEw5Mwiw3ZkV407G4ECOLbARcZ 7H8vcnAmLBSjxib6UhQtqqGeTcDpHO+FR16GOdflT62jbcVXVmUo+C8DDn7iRM/po33g t7yGQmdqTAo/wb6BAABDBV5u8nt2rdukCW/e9HASSr5Bu5xh9NmwkypHNlN+R1hbzVse gTbA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=qdHfVr+f; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id i64-20020a638743000000b00477ba9e69b9si7517826pge.533.2022.12.02.08.20.21; Fri, 02 Dec 2022 08:20:36 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=qdHfVr+f; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233621AbiLBQRd (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:33 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53750 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233774AbiLBQQs (ORCPT ); Fri, 2 Dec 2022 11:16:48 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 16659E076D; Fri, 2 Dec 2022 08:16:25 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id A93AEB821E6; Fri, 2 Dec 2022 16:16:23 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 74B15C43470; Fri, 2 Dec 2022 16:16:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997782; bh=rwwioSQhWGlbsSveUMx0tqInUdVD+U2ybxu5VIpUbRs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qdHfVr+fC3u1HwOHRGvxny6qMSmv3OfyzAhLmZZ7j/F/TrmrzFJ6s84m7LjHucTKp TS6N0rnkE/xFe1YstIfnTSkEtUqfzhf0Y3qhLKhskGzpmr4TufyQo5Lo15ee+2mOdu w4g14HgGx1uIsrYgu8IOD/bER8fvYm7UKyHup70UaX4ujOnAuh7eqHhtaq8B4J8xsb sqOwnD2etHNPp7uYQbIwvuUoJEtbMYOtvPy0F70Psnxd/aRK0xIwzi4V7rXs+8RDg3 8orTszzXRwKeY2xuyDMhN0jRiGl4LzpZQIaUShQLDRngz93H5W5Fb7QV73cnoUzqVX ARc6ohQ3LMCtw== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 19/28] rust: str: add `c_str!` macro Date: Fri, 2 Dec 2022 17:14:50 +0100 Message-Id: <20221202161502.385525-20-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119861458003992?= X-GMAIL-MSGID: =?utf-8?q?1751119861458003992?= From: Gary Guo Add `c_str!`, which is a convenience macro that creates a new `CStr` from a string literal. It is designed to be similar to a `str` in usage, and it is usable in const contexts, for instance: const X: &CStr = c_str!("Example"); Co-developed-by: Alex Gaynor Signed-off-by: Alex Gaynor Signed-off-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 3ed685cb5a3c..a995db36486f 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -321,6 +321,29 @@ where } } +/// Creates a new [`CStr`] from a string literal. +/// +/// The string literal should not contain any `NUL` bytes. +/// +/// # Examples +/// +/// ``` +/// # use kernel::c_str; +/// # use kernel::str::CStr; +/// const MY_CSTR: &CStr = c_str!("My awesome CStr!"); +/// ``` +#[macro_export] +macro_rules! c_str { + ($str:expr) => {{ + const S: &str = concat!($str, "\0"); + const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) { + Ok(v) => v, + Err(_) => panic!("string contains interior NUL"), + }; + C + }}; +} + #[cfg(test)] mod tests { use super::*; From patchwork Fri Dec 2 16:14:51 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28977 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948218wrr; Fri, 2 Dec 2022 08:19:21 -0800 (PST) X-Google-Smtp-Source: AA0mqf5Nj+VxF6i2NU53+Xku0RyUKiwr9532ztvAnca46xZxIvIkR8VlYc4kKJ/7sqHyqRcPZFZM X-Received: by 2002:a17:906:dfe8:b0:7c0:8711:7a4 with SMTP id lc8-20020a170906dfe800b007c0871107a4mr16373212ejc.667.1669997961313; Fri, 02 Dec 2022 08:19:21 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997961; cv=none; d=google.com; s=arc-20160816; b=KF6jyu3EYJqlvfSad9J/kGtVWjAhp5BrUnI7VQWGi2gyxueLfIRjFyhJbyyiR8m6XE Co7a/3uzisCvXSDNZNvbz4wgFbF7luE0qbRyt3rXvtdqQInzr+bnd1Yxd5oM78RSofZM Yb88Y1JBLXYP9b1Eu2CR/DPaCRE6QuoCwpVnuEybxcwQsp62eb4GN8w0qHBeGubv+L9v +o0pxQADCTqB+WteuzFbuVBU0fI5fhhuYnfiJEkQXOCIVRCiv9XMndw0PtNg+aaH3ba8 Fc9yftEVyftOEfXZH2/7DRhsL+U2w0XOun/aJeIxDqS9FcoFV96MVJDoT2JjzyicV57g 9KTg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=WU2Bapy8NrQadUjLKlB9GfwCe5rNMp+0+TMym3iKpTc=; b=QSs6MomupO/HWqf1W5eV4/MUbe51O2I3Pj5vQ4KKor6Dmrh0kzVnPzlLgFL6M/K0RF fmm2Pqx5UXcPcrQwqfQSdiojS2V7Tms9njNMMvGlWkgUS+kiTrFze9pHR/L3sQcrwago vIsM0QdnZd3g3C7qsTBpGwvC8Gc7U2OTWYfa7txEpBBMdOJGwjv2zRBGAaepui/4yZzS NQ/EJ4rJnNyiDNAPRIc/wvBgCJMqLgYXQFRHYvXOLFQnn6hqtuzL2HxPPf64TTtf+HWd Sdi72bMXab40OkyWL2gUtpRowYrtSBAD6baEyWAr4QA0gKlCwQDdkVVqajedtYFKs5Qv m9VA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=eZA4rWwQ; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id u11-20020aa7d88b000000b0046a279823d6si6050610edq.298.2022.12.02.08.18.56; Fri, 02 Dec 2022 08:19:21 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=eZA4rWwQ; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233979AbiLBQRg (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:36 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53764 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233937AbiLBQQs (ORCPT ); Fri, 2 Dec 2022 11:16:48 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [IPv6:2604:1380:4601:e00::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id C34DDBE6A1; Fri, 2 Dec 2022 08:16:27 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id 7C22BB821EF; Fri, 2 Dec 2022 16:16:26 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0B1C9C433D6; Fri, 2 Dec 2022 16:16:22 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997785; bh=lNOFPVRbAKVrfjnVGGlh1mHXRjctVq4x9YbdvqaJ5Pc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eZA4rWwQlLf/QhcBhrlLCwVeLdG0tbiNvtMljCe5GPUaS1snLGeCqEF0fOQBXL7lc O2Ou8zvs6Vta595iqoUkxn4qyPgwQuNC5GP2RciAUllOKsi6dtrrQYCKCo9U0jkxh+ sxWfFO04JADRtp9ZcKcTKc7ap54ysr+Z8tjDdc+I1gtNedTFaZU7/OHjDSQdVfGCl5 xhAkSvQCowbAgvVNgnOAehjsD8GEYd/OPcBMJIl5vfBqi7Nm3LBbA9yDFVqDVTKnFT 1+SBvnDxZ77h5m0ZRF2lCbhdTzUhYh1tR7kSG4rMVVbTib/D3BnZcwOWS/UJ/C1Hq6 lqzZKBgD4TMFg== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Adam Bratschi-Kaye Subject: [PATCH v2 20/28] rust: str: add `Formatter` type Date: Fri, 2 Dec 2022 17:14:51 +0100 Message-Id: <20221202161502.385525-21-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119782429416579?= X-GMAIL-MSGID: =?utf-8?q?1751119782429416579?= From: Wedson Almeida Filho Add the `Formatter` type, which leverages `RawFormatter`, but fails if callers attempt to write more than will fit in the buffer. In order to so, implement the `RawFormatter::from_buffer()` constructor as well. Co-developed-by: Adam Bratschi-Kaye Signed-off-by: Adam Bratschi-Kaye Signed-off-by: Wedson Almeida Filho Reviewed-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index a995db36486f..ce207d1b3d2a 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -406,6 +406,23 @@ impl RawFormatter { } } + /// Creates a new instance of [`RawFormatter`] with the given buffer. + /// + /// # Safety + /// + /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes + /// for the lifetime of the returned [`RawFormatter`]. + pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { + let pos = buf as usize; + // INVARIANT: We ensure that `end` is never less then `buf`, and the safety requirements + // guarantees that the memory region is valid for writes. + Self { + pos, + beg: pos, + end: pos.saturating_add(len), + } + } + /// Returns the current insert position. /// /// N.B. It may point to invalid memory. @@ -439,3 +456,43 @@ impl fmt::Write for RawFormatter { Ok(()) } } + +/// Allows formatting of [`fmt::Arguments`] into a raw buffer. +/// +/// Fails if callers attempt to write more than will fit in the buffer. +pub(crate) struct Formatter(RawFormatter); + +impl Formatter { + /// Creates a new instance of [`Formatter`] with the given buffer. + /// + /// # Safety + /// + /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes + /// for the lifetime of the returned [`Formatter`]. + #[allow(dead_code)] + pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { + // SAFETY: The safety requirements of this function satisfy those of the callee. + Self(unsafe { RawFormatter::from_buffer(buf, len) }) + } +} + +impl Deref for Formatter { + type Target = RawFormatter; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl fmt::Write for Formatter { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.0.write_str(s)?; + + // Fail the request if we go past the end of the buffer. + if self.0.pos > self.0.end { + Err(fmt::Error) + } else { + Ok(()) + } + } +} From patchwork Fri Dec 2 16:14:52 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28974 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948129wrr; Fri, 2 Dec 2022 08:19:13 -0800 (PST) X-Google-Smtp-Source: AA0mqf7sW6mmEXO7yX4htad5MFRc/nlSAV5I3lB/pM/BYXSHElBp7GjyJFKkxOR1ntlPT7olnzfz X-Received: by 2002:aa7:8250:0:b0:56b:fe1d:5735 with SMTP id e16-20020aa78250000000b0056bfe1d5735mr72592241pfn.24.1669997953180; Fri, 02 Dec 2022 08:19:13 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997953; cv=none; d=google.com; s=arc-20160816; b=BUXLc63rsFysErbw5vvGbba3OoLxXHSSWYE352Ugloj3wxL7Vf5vh7sqTDDlckfFQc CCdgg7ddoVDWyEh6ykec1ydiZe/cFnRRcMmOZRZJ+3hFEprKsNOgCkQKe1i7zzzzkusw wD1R1LxbLPmhSBg4VsIPg01ozgvkhxdxETXK4ZA/Zf/24o95omWTtAlqDfn1h0b5i2lQ egRnq1A4yipmG86Cb/E9tsyByjGGf+kgPfCJ6FR0dccHDcJQh5Ybdqj6+donLAl9x4GO b8vwBW+jYBCOpQl5TrsxcqxHse4fXmorBG9lN0wXZm0ozGHFdyJHGnWdHPaglr6vukMr 3dOQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=djJf389MCljGKDr5goBzN1hIDcJx9OzcBdYO52eGY/Y=; b=i69duT8SAQk6pUwX+Y6hI4L8nDEgxouwoUG9ZLwIz7dcQfMyUZZf0SaGqq6mMzgVDv cEVmZunOMP6MShMiepoetYSvFxntDeLy67eoBOOR60+pumkprWHbg+coTTrhfv497Ta6 MW/c/EFcmp2R2UsAwtSON+kJLB/3BqDRCkpT4AkOHjMQnhXR6jYssLIK/lPxUD9IFIMX QlDTiEuBbyQrmAWoYpVdUOMlgYEaBFjl4FIksfPdo0syVgUgkNDAT/b4D1lXvdrsTBbH EIXKkEICKscKz58ttJpbL2ov6r2wPb3GRt4pJL6q0mxHx6bTWcAoXuyN+VlYdiR533UI mG/A== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=ZwWOTuAJ; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id d11-20020a056a0010cb00b005746b284963si8232988pfu.290.2022.12.02.08.18.57; Fri, 02 Dec 2022 08:19:13 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=ZwWOTuAJ; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233986AbiLBQRi (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:38 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53312 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233806AbiLBQQs (ORCPT ); Fri, 2 Dec 2022 11:16:48 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [IPv6:2604:1380:4641:c500::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id C69C8D11DE; Fri, 2 Dec 2022 08:16:28 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 646B4622E3; Fri, 2 Dec 2022 16:16:28 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id CC616C433D7; Fri, 2 Dec 2022 16:16:25 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997787; bh=DYkcTUv5/lPaD/adaMiKk/N3Pcv655DbMeZ9Xrx7hYQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ZwWOTuAJw4gHJZ2bp+Can+Q60PDd2B0VwNoqffCGlUi8Us275cyhXsKLTgjq2oMdb oQ10UVVYNtuou+Nq8p4RHZudJfT46E6JQYKauxmgAQF+4qEQqRmtibjWs5Pwkg6Lo4 tebWkFdxt5FcDsn2/irAIokyTifad9UyZaVOzWWJRESfV3okAkQyrDgpCz40o44qx9 19kCUAvty7MSH31aYqCjJbbU+VcTseOFlBCNKV8gkw0IBEGAvYTRzzvp+8NSu7uwUj aRHI41oRmqQ48jVxiG0kTWwvjyMhDVaQegIKXn5yUUTZPLb18UAs7tG9iVtwcOM5QG 52J3hVsXoldBg== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 21/28] rust: str: add `CString` type Date: Fri, 2 Dec 2022 17:14:52 +0100 Message-Id: <20221202161502.385525-22-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119774040325764?= X-GMAIL-MSGID: =?utf-8?q?1751119774040325764?= From: Wedson Almeida Filho Add the `CString` type, which is an owned string that is guaranteed to have exactly one `NUL` byte at the end, i.e. the owned equivalent to `CStr` introduced earlier. It is used for interoperability with kernel APIs that take C strings. In order to do so, implement the `RawFormatter::new()` constructor and the `RawFormatter::bytes_written()` method as well. Signed-off-by: Wedson Almeida Filho [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 91 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 2 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index ce207d1b3d2a..17dc8d273302 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -2,6 +2,7 @@ //! String representations. +use alloc::vec::Vec; use core::fmt::{self, Write}; use core::ops::{self, Deref, Index}; @@ -384,13 +385,22 @@ mod tests { /// is less than `end`. pub(crate) struct RawFormatter { // Use `usize` to use `saturating_*` functions. - #[allow(dead_code)] beg: usize, pos: usize, end: usize, } impl RawFormatter { + /// Creates a new instance of [`RawFormatter`] with an empty buffer. + fn new() -> Self { + // INVARIANT: The buffer is empty, so the region that needs to be writable is empty. + Self { + beg: 0, + pos: 0, + end: 0, + } + } + /// Creates a new instance of [`RawFormatter`] with the given buffer pointers. /// /// # Safety @@ -429,6 +439,11 @@ impl RawFormatter { pub(crate) fn pos(&self) -> *mut u8 { self.pos as _ } + + /// Return the number of bytes written to the formatter. + pub(crate) fn bytes_written(&self) -> usize { + self.pos - self.beg + } } impl fmt::Write for RawFormatter { @@ -469,7 +484,6 @@ impl Formatter { /// /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes /// for the lifetime of the returned [`Formatter`]. - #[allow(dead_code)] pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { // SAFETY: The safety requirements of this function satisfy those of the callee. Self(unsafe { RawFormatter::from_buffer(buf, len) }) @@ -496,3 +510,76 @@ impl fmt::Write for Formatter { } } } + +/// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end. +/// +/// Used for interoperability with kernel APIs that take C strings. +/// +/// # Invariants +/// +/// The string is always `NUL`-terminated and contains no other `NUL` bytes. +/// +/// # Examples +/// +/// ``` +/// use kernel::str::CString; +/// +/// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20)).unwrap(); +/// assert_eq!(s.as_bytes_with_nul(), "abc1020\0".as_bytes()); +/// +/// let tmp = "testing"; +/// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123)).unwrap(); +/// assert_eq!(s.as_bytes_with_nul(), "testing123\0".as_bytes()); +/// +/// // This fails because it has an embedded `NUL` byte. +/// let s = CString::try_from_fmt(fmt!("a\0b{}", 123)); +/// assert_eq!(s.is_ok(), false); +/// ``` +pub struct CString { + buf: Vec, +} + +impl CString { + /// Creates an instance of [`CString`] from the given formatted arguments. + pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result { + // Calculate the size needed (formatted string plus `NUL` terminator). + let mut f = RawFormatter::new(); + f.write_fmt(args)?; + f.write_str("\0")?; + let size = f.bytes_written(); + + // Allocate a vector with the required number of bytes, and write to it. + let mut buf = Vec::try_with_capacity(size)?; + // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes. + let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) }; + f.write_fmt(args)?; + f.write_str("\0")?; + + // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is + // `buf`'s capacity. The contents of the buffer have been initialised by writes to `f`. + unsafe { buf.set_len(f.bytes_written()) }; + + // Check that there are no `NUL` bytes before the end. + // SAFETY: The buffer is valid for read because `f.bytes_written()` is bounded by `size` + // (which the minimum buffer size) and is non-zero (we wrote at least the `NUL` terminator) + // so `f.bytes_written() - 1` doesn't underflow. + let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, (f.bytes_written() - 1) as _) }; + if !ptr.is_null() { + return Err(EINVAL); + } + + // INVARIANT: We wrote the `NUL` terminator and checked above that no other `NUL` bytes + // exist in the buffer. + Ok(Self { buf }) + } +} + +impl Deref for CString { + type Target = CStr; + + fn deref(&self) -> &Self::Target { + // SAFETY: The type invariants guarantee that the string is `NUL`-terminated and that no + // other `NUL` bytes exist. + unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) } + } +} From patchwork Fri Dec 2 16:14:53 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28976 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948157wrr; Fri, 2 Dec 2022 08:19:15 -0800 (PST) X-Google-Smtp-Source: AA0mqf76V8lNi+4csha+0OAWoWaju7KyM6SdqpGcqJEcqHh90A7ucwo5OIaBbmPuHJZHIT9zebtl X-Received: by 2002:a05:6a00:4c8f:b0:575:4bb2:d67d with SMTP id eb15-20020a056a004c8f00b005754bb2d67dmr23313271pfb.32.1669997955350; Fri, 02 Dec 2022 08:19:15 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997955; cv=none; d=google.com; s=arc-20160816; b=Vz1bmW2cj1Y1v3/hCjQH2zBhrXGHfvR02TQA7fYa36PRXxXn8kmJ9xo1NKTSC1S8r6 demOINaFyezB1f9ULmFMoVv2VbY49+wIieBpPD47I8EBGB/UDMve2FUcVDwvonOoBTtu 9Ef41LVKi/QPiwTKO3/+3/hdQP3a4dUr64zc+vKmiK7v7B+rpuLfX5VXz9HqBjYMlg0i zjIFF+oODriJDYV8GOWKprHi5WcCgQOMiPGuuncVZ/T/3H6O3Yecp05RVAYqq9BduJwI B4vwptHvhb6a/CzeoaEush/M0POjMXFeox5qcIfz1xzIfojRjq6JcrIkoX0Mu3wSrwMV wyfw== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=BncKxf0FEIAlVkIEBfCYUlf6ZbD9V9hy57O1k44WBhY=; b=ulc3IasD9rFeT5CW0YBBepbJcnGHjAk2cLLW/iRaHbc3GmDBxUV+NmtngXgZBgonF3 N2tD94+fR9FDYGMJ67VEnXjHBc6LhZCUkXvH9CFGeB5j09rg5E9zvV+M0WAZrMLLXbI8 lHKqkHy/lVwc9kOIDUQqrb3FNihJxvyb6JPiUyqfV3pWrfGVINT/T4qd4VZiaO9/7XSs NlY9ukPMqNQvu1UFcohtzKSAWSCaxiuzvbUSCSd/6426XVVrPdEKdCw1OoTJo5FjY0oM bH7bDk91E1qAkl7a0ga5af8CEgr7AL/N2W9B16EKLhGeqmv59Snse8T4pjhyTUIDnYni eixA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=NYvNrJtW; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id k35-20020a634b63000000b004705b0ca9f1si7411486pgl.545.2022.12.02.08.19.01; Fri, 02 Dec 2022 08:19:15 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=NYvNrJtW; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S234057AbiLBQRl (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:41 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53784 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233728AbiLBQQx (ORCPT ); Fri, 2 Dec 2022 11:16:53 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [IPv6:2604:1380:4641:c500::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 5D1BDBF672; Fri, 2 Dec 2022 08:16:31 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id F1B4262333; Fri, 2 Dec 2022 16:16:30 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 68981C43470; Fri, 2 Dec 2022 16:16:28 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997790; bh=PSDlDgg7arSCRfOwK63AE+RLja44ZMgKq2KzkCToYdA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=NYvNrJtWUxlmlj2bF+g+67oP10HdYPd3vqoltQvQaziRXrHKkVy2tkS6KJZgGVRmu Kta1SMRVQjrauuhHyZUGsfZ+gFeo/9OUqHhhFhW4aZouyYM2BWGdG4FbZTH2aBa601 FA24RpWeUlmG/uGJYFgattK88Bs7+wkWpY01RzG2UTKVIVPK0svLEiOagWpFns2qIQ vys8Mt8rXbOr2+yK8inBGfFjgQ3XoQIwW9/qVNbVBD/sA9dfZNdc4vyGSE2WZUlr25 8p4XtNdivPdFdHb8BgDoe0ylmCJ69ZCruINqgFBuqFc/RLCbv4+Wsk/ebd6wOCAFjh d97wO5cO2KqBw== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 22/28] rust: str: add `fmt!` macro Date: Fri, 2 Dec 2022 17:14:53 +0100 Message-Id: <20221202161502.385525-23-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119775808412181?= X-GMAIL-MSGID: =?utf-8?q?1751119775808412181?= From: Wedson Almeida Filho Add the `fmt!` macro, which is a convenience alias for the Rust `core::format_args!` macro. For instance, it may be used to create a `CString`: CString::try_from_fmt(fmt!("{}{}", "abc", 42))? Signed-off-by: Wedson Almeida Filho Reviewed-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 17dc8d273302..b771310fa4a4 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -583,3 +583,9 @@ impl Deref for CString { unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) } } } + +/// A convenience alias for [`core::format_args`]. +#[macro_export] +macro_rules! fmt { + ($($f:tt)*) => ( core::format_args!($($f)*) ) +} From patchwork Fri Dec 2 16:14:54 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28986 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948869wrr; Fri, 2 Dec 2022 08:20:37 -0800 (PST) X-Google-Smtp-Source: AA0mqf5g/q0G45b263oCcic/Bh3pKBAiObGQziVN1dsy4pFZyeTDcEv1wDHWapSMm75n/7pI5Hqg X-Received: by 2002:a17:90b:d13:b0:217:ecbd:5ae with SMTP id n19-20020a17090b0d1300b00217ecbd05aemr53144981pjz.17.1669998036749; Fri, 02 Dec 2022 08:20:36 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669998036; cv=none; d=google.com; s=arc-20160816; b=ULR2CMMieis0NvHjTJMcpDDqHnTglmuYLPhiCjra071GIB/9kpr/S+4V+0ZLdDBM4F nAtueqzv8EeL2tIS0SGnw+l7eQaPbwxYIycs4eWgnnOE02BTtKXdAWeWR9qHMv1h57VS T9xMC+rAaw+bKnY2B+qlOgpdrjrntTZgXR6DMjdLL//9zVeF6HqudIhsej8uVPTrwpmR 8/O8NvLT7H3KVrNSK2eJPf/dqb7jfBFy31fZNde1oEXrKf5l8vXdsJ215RDHO4xEFRGa rjV6a+8sSCdIh6ZPCSodm3m7ky5Uy6GlaNZLXMCjJAJArSUBr13eswEShK8e/iyXtZYa zPgA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=T/F9nQxq1sb4Fr4eRbE8ewZ77S9n5oNOusHDr6uouB8=; b=FIQ8ZIUYNnEE0zLgy5OT+T9/NgOx45cxnMqyV6DYJ1+yWiJto1QAlgi2C7YT+zAa/e 7voQZmZn2ohFFkXOjbPSr1H2IeaYIxGeGYD6eW512zUh3t818avKHND/EnOI3C1GRsiy mwRUHgJ0bkAu15FfO9MzEfUVamfutIIlPWHSpCayCfqt9xWUxxcubBe0oxFLh2RcON1f f5Soy2Vc20SOBQSJAyMmV80gtktQ3dPywDaksXYHrw30gC08Y/XRedvLwGQkhzfmpNhA adQ7OGJGGj6axibk8P1hcUUEcnwiM0Hjhp/d/2chJfU6CrdqdFiJyCBnzPCWip1s0rcU Gzsw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=piZC5fI+; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id oc12-20020a17090b1c0c00b0021929c63260si9033189pjb.8.2022.12.02.08.20.16; Fri, 02 Dec 2022 08:20:36 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=piZC5fI+; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233991AbiLBQRx (ORCPT + 99 others); Fri, 2 Dec 2022 11:17:53 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53382 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233993AbiLBQQ5 (ORCPT ); Fri, 2 Dec 2022 11:16:57 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id A2B0EE0777; Fri, 2 Dec 2022 08:16:34 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id D1C3662333; Fri, 2 Dec 2022 16:16:33 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 14BAEC433D7; Fri, 2 Dec 2022 16:16:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997793; bh=Uz7KZaflvYhbQVM6K8z3z1Og+VT76a4o8l7UhNbcRqo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=piZC5fI+mMK9laO2CWFrUa+F8m2JRcPS4V7dY75UeuRgbk7H4QaB/aOhc5Hcr4/qB Ku67P0FBoLgFKBRq9mQWeyW6WJ5OsYjURCwOK1y7jLanx6t+kCaBNb3qzmqGLPu/In aDWWapfkMwKu9toC8dBTD4CUwngE5qaQzNbUXaonA1rlYm/o4EyKe4vyZLUoIYwBJG cBYC5UldxMV7lZ8xJduAvgL0ohayvLPz+vics0YV0QrJPR72p9swWPRxm6/5Mznb2s ChLm0lVMMMWGARguWgjUeQ9HYx0TgAFrI0jSnzlwroAjUBpxllJ4cHOO4ZUE67LOA7 eYno+WKdAB6AQ== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Niklas Mohrin Subject: [PATCH v2 23/28] rust: std_vendor: add `dbg!` macro based on `std`'s one Date: Fri, 2 Dec 2022 17:14:54 +0100 Message-Id: <20221202161502.385525-24-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS,WEIRD_PORT autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119861530226966?= X-GMAIL-MSGID: =?utf-8?q?1751119861530226966?= From: Niklas Mohrin The Rust standard library has a really handy macro, `dbg!` [1,2]. It prints the source location (filename and line) along with the raw source code that is invoked with and the `Debug` representation of the given expression, e.g.: let a = 2; let b = dbg!(a * 2) + 1; // ^-- prints: [src/main.rs:2] a * 2 = 4 assert_eq!(b, 5); Port the macro over to the `kernel` crate inside a new module called `std_vendor`, using `pr_info!` instead of `eprintln!` and make the rules about committing uses of `dbg!` into version control more concrete (i.e. tailored for the kernel). Since the source code for the macro is taken from the standard library source (with only minor adjustments), the new file is licensed under `Apache 2.0 OR MIT`, just like the original [3,4]. Link: https://doc.rust-lang.org/std/macro.dbg.html [1] Link: https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs#L212 [2] Link: https://github.com/rust-lang/rust/blob/master/library/std/Cargo.toml [3] Link: https://github.com/rust-lang/rust/blob/master/COPYRIGHT [4] Signed-off-by: Niklas Mohrin [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/lib.rs | 2 + rust/kernel/prelude.rs | 2 +- rust/kernel/std_vendor.rs | 163 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/std_vendor.rs diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index ffc6626a6d29..d6371c9c8453 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -26,6 +26,8 @@ mod allocator; pub mod error; pub mod prelude; pub mod print; +#[doc(hidden)] +pub mod std_vendor; pub mod str; #[doc(hidden)] diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 89c2c9f4e7a7..345fc9075d1f 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -17,7 +17,7 @@ pub use alloc::{boxed::Box, vec::Vec}; pub use macros::{module, vtable}; -pub use super::{pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn}; +pub use super::{dbg, pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn}; pub use super::error::{code::*, Error, Result}; diff --git a/rust/kernel/std_vendor.rs b/rust/kernel/std_vendor.rs new file mode 100644 index 000000000000..b3e68b24a8c6 --- /dev/null +++ b/rust/kernel/std_vendor.rs @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! The contents of this file come from the Rust standard library, hosted in +//! the repository, licensed under +//! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details, +//! see . + +/// [`std::dbg`], but using [`pr_info`] instead of [`eprintln`]. +/// +/// Prints and returns the value of a given expression for quick and dirty +/// debugging. +/// +/// An example: +/// +/// ```rust +/// let a = 2; +/// # #[allow(clippy::dbg_macro)] +/// let b = dbg!(a * 2) + 1; +/// // ^-- prints: [src/main.rs:2] a * 2 = 4 +/// assert_eq!(b, 5); +/// ``` +/// +/// The macro works by using the `Debug` implementation of the type of +/// the given expression to print the value with [`printk`] along with the +/// source location of the macro invocation as well as the source code +/// of the expression. +/// +/// Invoking the macro on an expression moves and takes ownership of it +/// before returning the evaluated expression unchanged. If the type +/// of the expression does not implement `Copy` and you don't want +/// to give up ownership, you can instead borrow with `dbg!(&expr)` +/// for some expression `expr`. +/// +/// The `dbg!` macro works exactly the same in release builds. +/// This is useful when debugging issues that only occur in release +/// builds or when debugging in release mode is significantly faster. +/// +/// Note that the macro is intended as a temporary debugging tool to be +/// used during development. Therefore, avoid committing `dbg!` macro +/// invocations into the kernel tree. +/// +/// For debug output that is intended to be kept in the kernel tree, +/// use [`pr_debug`] and similar facilities instead. +/// +/// # Stability +/// +/// The exact output printed by this macro should not be relied upon +/// and is subject to future changes. +/// +/// # Further examples +/// +/// With a method call: +/// +/// ```rust +/// # #[allow(clippy::dbg_macro)] +/// fn foo(n: usize) { +/// if dbg!(n.checked_sub(4)).is_some() { +/// // ... +/// } +/// } +/// +/// foo(3) +/// ``` +/// +/// This prints to the kernel log: +/// +/// ```text,ignore +/// [src/main.rs:4] n.checked_sub(4) = None +/// ``` +/// +/// Naive factorial implementation: +/// +/// ```rust +/// # #[allow(clippy::dbg_macro)] +/// # { +/// fn factorial(n: u32) -> u32 { +/// if dbg!(n <= 1) { +/// dbg!(1) +/// } else { +/// dbg!(n * factorial(n - 1)) +/// } +/// } +/// +/// dbg!(factorial(4)); +/// # } +/// ``` +/// +/// This prints to the kernel log: +/// +/// ```text,ignore +/// [src/main.rs:3] n <= 1 = false +/// [src/main.rs:3] n <= 1 = false +/// [src/main.rs:3] n <= 1 = false +/// [src/main.rs:3] n <= 1 = true +/// [src/main.rs:4] 1 = 1 +/// [src/main.rs:5] n * factorial(n - 1) = 2 +/// [src/main.rs:5] n * factorial(n - 1) = 6 +/// [src/main.rs:5] n * factorial(n - 1) = 24 +/// [src/main.rs:11] factorial(4) = 24 +/// ``` +/// +/// The `dbg!(..)` macro moves the input: +/// +/// ```ignore +/// /// A wrapper around `usize` which importantly is not Copyable. +/// #[derive(Debug)] +/// struct NoCopy(usize); +/// +/// let a = NoCopy(42); +/// let _ = dbg!(a); // <-- `a` is moved here. +/// let _ = dbg!(a); // <-- `a` is moved again; error! +/// ``` +/// +/// You can also use `dbg!()` without a value to just print the +/// file and line whenever it's reached. +/// +/// Finally, if you want to `dbg!(..)` multiple values, it will treat them as +/// a tuple (and return it, too): +/// +/// ``` +/// # #[allow(clippy::dbg_macro)] +/// assert_eq!(dbg!(1usize, 2u32), (1, 2)); +/// ``` +/// +/// However, a single argument with a trailing comma will still not be treated +/// as a tuple, following the convention of ignoring trailing commas in macro +/// invocations. You can use a 1-tuple directly if you need one: +/// +/// ``` +/// # #[allow(clippy::dbg_macro)] +/// # { +/// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored +/// assert_eq!((1,), dbg!((1u32,))); // 1-tuple +/// # } +/// ``` +/// +/// [`std::dbg`]: https://doc.rust-lang.org/std/macro.dbg.html +/// [`eprintln`]: https://doc.rust-lang.org/std/macro.eprintln.html +/// [`printk`]: https://www.kernel.org/doc/html/latest/core-api/printk-basics.html +#[macro_export] +macro_rules! dbg { + // NOTE: We cannot use `concat!` to make a static string as a format argument + // of `pr_info!` because `file!` could contain a `{` or + // `$val` expression could be a block (`{ .. }`), in which case the `pr_info!` + // will be malformed. + () => { + $crate::pr_info!("[{}:{}]\n", ::core::file!(), ::core::line!()) + }; + ($val:expr $(,)?) => { + // Use of `match` here is intentional because it affects the lifetimes + // of temporaries - https://stackoverflow.com/a/48732525/1063961 + match $val { + tmp => { + $crate::pr_info!("[{}:{}] {} = {:#?}\n", + ::core::file!(), ::core::line!(), ::core::stringify!($val), &tmp); + tmp + } + } + }; + ($($val:expr),+ $(,)?) => { + ($($crate::dbg!($val)),+,) + }; +} From patchwork Fri Dec 2 16:14:55 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28981 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948389wrr; Fri, 2 Dec 2022 08:19:44 -0800 (PST) X-Google-Smtp-Source: AA0mqf4rCuAE9CywEF1PIampCP6NPhyys2EyXT6DsiGdMeSSh59s9hVL4JasQ262UKTAWSCoohhf X-Received: by 2002:aa7:dd0e:0:b0:46b:9dee:1e09 with SMTP id i14-20020aa7dd0e000000b0046b9dee1e09mr13166008edv.390.1669997984421; Fri, 02 Dec 2022 08:19:44 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997984; cv=none; d=google.com; s=arc-20160816; b=EXvSOeZ/78oZrutjMdgKZ1WjaxZWDQyQMPWAFEw4ZfEEoVgKBEPR6KvhOQWaneRSNN 17LOc1iJTXQGfMUl88Ch3kURK/4XDfwQg4Hk4/RZLPfTbhP+UXgqZZSJDBNATaMk2qiN VTEi5fhB2v8zH7/Tc8R9O0UHm+HXW+84WLhvzN1BccJLP2kkApZfbI1n9L9WoxiSonS9 RfpsuRsLMagD62zgRsJ0y2S2otvhOCqBREIdILRmm2qox6bdOLgvA7xyFSIv3OtNg0vr LlUoJXbJkWQ43TPwqSoaD5ta5zjEhsC2gbDBUuvIuhY9m/s2luW0fmkjoZAU3GPiHAZP Ldsg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=2r8yRciLz/zLOdY+CcyixgkvhpUVu0vf9nzwOLVNSWs=; b=lkl4IVrQHaLrBbCnFpQoC8S09q9hIWxEJ0BHKnTBKCz01jx1AHQ4SwuMbamfDVysyH 66fikLxbNmsN2bQr14l+QVMoR6gkpd2m4Z2th0o/n8menPSfrLlg/tDCqtfit58XpoZu wUJ9RSGsBhv5EMtLd+5XKjjgYyxwHukWzrEJwupmsKWOGan2QZ26ZzEvpfLo7Tw8h04E KDzYaEuGdxB8j55+LugJcpLS51j6QvGQK5Vvrvsp/wHNgXVlDbeYDyby+lKX4iKSZHhN lxMTeOpWwO6MNgty70G2Ra3fvxPu2PZNraE4B7WDRg3dL38AXxFalDzQfiiCW7HQCZjI GvCw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=Q0pa2gxE; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id q14-20020a1709060e4e00b0078db89b2566si4830586eji.699.2022.12.02.08.19.20; Fri, 02 Dec 2022 08:19:44 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=Q0pa2gxE; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S234033AbiLBQSL (ORCPT + 99 others); Fri, 2 Dec 2022 11:18:11 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53110 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S234028AbiLBQRC (ORCPT ); Fri, 2 Dec 2022 11:17:02 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 8FD61E2546; Fri, 2 Dec 2022 08:16:38 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id 32B19B821E8; Fri, 2 Dec 2022 16:16:37 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id ED068C433D6; Fri, 2 Dec 2022 16:16:33 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997796; bh=jbFFwN1XbpZoDSezKmpFYsV4hQRLNxhA6Wyw/KC6oWw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Q0pa2gxEprAPjTUOTcae3ubV+WpDQtNMpmX5UWyloHT7Ohb740+tEAt+1aFtikVvK GYfKMwPTEc7I1xtnY/TESBfUVk80EMTIm8F7+YUUwr0imfpqC2gX3k3VfWBCw93fiC Y3JxWSe1z5DXZCdONVynHKb6WST83Jy4KPqhsyeq+DSTXLtj7WP4ns70iABhLxeb7A 6mcyBYdLz5ewUXFsWiEmF8rCe3aFlXGvDAN+ahag8qxToPCAUwCeX1nB3OSazRadcg i0GXhFfGYFBAaAMS8lSOFLoqpYYFZIE3Xx6WM+N7zyForeoHiqqlu6wW2eORgLo3fl FtcjKdk8zm7zQ== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 24/28] rust: static_assert: add `static_assert!` macro Date: Fri, 2 Dec 2022 17:14:55 +0100 Message-Id: <20221202161502.385525-25-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119806630440798?= X-GMAIL-MSGID: =?utf-8?q?1751119806630440798?= From: Miguel Ojeda Add the `static_assert!` macro, which is a compile-time assert, similar to the C11 `_Static_assert` and C++11 `static_assert` declarations [1,2]. Do so in a new module, called `static_assert`. For instance: static_assert!(42 > 24); static_assert!(core::mem::size_of::() == 1); const X: &[u8] = b"bar"; static_assert!(X[1] == b'a'); const fn f(x: i32) -> i32 { x + 2 } static_assert!(f(40) == 42); Link: https://en.cppreference.com/w/c/language/_Static_assert [1] Link: https://en.cppreference.com/w/cpp/language/static_assert [2] Co-developed-by: Alex Gaynor Signed-off-by: Alex Gaynor Signed-off-by: Miguel Ojeda --- rust/kernel/lib.rs | 1 + rust/kernel/prelude.rs | 2 ++ rust/kernel/static_assert.rs | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 rust/kernel/static_assert.rs diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index d6371c9c8453..9b83ef736298 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -26,6 +26,7 @@ mod allocator; pub mod error; pub mod prelude; pub mod print; +mod static_assert; #[doc(hidden)] pub mod std_vendor; pub mod str; diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 345fc9075d1f..178fe8e6cb6d 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -19,6 +19,8 @@ pub use macros::{module, vtable}; pub use super::{dbg, pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn}; +pub use super::static_assert; + pub use super::error::{code::*, Error, Result}; pub use super::{str::CStr, ThisModule}; diff --git a/rust/kernel/static_assert.rs b/rust/kernel/static_assert.rs new file mode 100644 index 000000000000..3115ee0ba8e9 --- /dev/null +++ b/rust/kernel/static_assert.rs @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Static assert. + +/// Static assert (i.e. compile-time assert). +/// +/// Similar to C11 [`_Static_assert`] and C++11 [`static_assert`]. +/// +/// The feature may be added to Rust in the future: see [RFC 2790]. +/// +/// [`_Static_assert`]: https://en.cppreference.com/w/c/language/_Static_assert +/// [`static_assert`]: https://en.cppreference.com/w/cpp/language/static_assert +/// [RFC 2790]: https://github.com/rust-lang/rfcs/issues/2790 +/// +/// # Examples +/// +/// ``` +/// static_assert!(42 > 24); +/// static_assert!(core::mem::size_of::() == 1); +/// +/// const X: &[u8] = b"bar"; +/// static_assert!(X[1] == b'a'); +/// +/// const fn f(x: i32) -> i32 { +/// x + 2 +/// } +/// static_assert!(f(40) == 42); +/// ``` +#[macro_export] +macro_rules! static_assert { + ($condition:expr) => { + const _: () = core::assert!($condition); + }; +} From patchwork Fri Dec 2 16:14:56 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28980 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948351wrr; Fri, 2 Dec 2022 08:19:39 -0800 (PST) X-Google-Smtp-Source: AA0mqf7a1f0ad/Gs0oMGyiEM5NE43srz8FFQEC32tmlrAMY8sZy/LGUWh1/HGVrgJuCqGJlxNDMI X-Received: by 2002:a63:fc63:0:b0:478:18d6:ad22 with SMTP id r35-20020a63fc63000000b0047818d6ad22mr22815763pgk.492.1669997979157; Fri, 02 Dec 2022 08:19:39 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669997979; cv=none; d=google.com; s=arc-20160816; b=uE9e+HbWTCg5Ig/CXDGfeZbHLAVWv8eVE/MyMQhyRKuzrBqmWyD+1FGCvhUB4zpqJz q9jvFZ8Gke+TXGOYoLDlrxDo5I8GbR9X2qhAs7np6d2aQ4hszmJEAjecIheCOJY3Eajt Tv0S1/5QoYlLDNHZckwz/RFW3RW+LgE0ZcA1vyJmV7sjQl7LJoC8RarnVJN1ErGBeF+a qz2HrsSNzBo6v7O/B5Gnqkwto6Eeyew/HYpAuaRqv364uGM9K4Mxmtw7ett5g+0/4LAa G7iNGfjns19OVJka9K5kUaYJqX6SvWE4e9b2Tj5rRiYXAmogO7brrqD53S0esvCyrlWn 0zBg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=9gVCIz7eka9O0RHemDINMSTcfEmASnOdZ5ovgrSkDzA=; b=LFHse6zpB1StL6HhNShKdxZ48uqvR4xqGoD7pfFzU8dhGJfAmErRMfMWLxcG/45fPP trhNMbIZ5vocXkO3tcHuGMITjXYovw/qoTCzTeKyE+BLRdcKANUETZ2U6qF+3n2BBcLX H/gEwNQmpihcIqJAc7l8E5sHDxhIac2BVB9jdq6xFq7ggvDcSKO/srSte3Ywq3tPt8ud BByISOiemCx30WATsnrU3lVNBVbKJua0aAqGgeBAvF/4n+ixoEIxjv7MxgKimxj5Dl/p BYFZUVZi8wHpZjdEyeLrrKrp0rjJsYHhuB31EmK+KRRdOor3yd+XRxCX4dBvPeDR0h4P +6cw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=l6Vh9ABg; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id u3-20020a634703000000b0045837277570si5257868pga.286.2022.12.02.08.19.25; Fri, 02 Dec 2022 08:19:39 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=l6Vh9ABg; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S234054AbiLBQSP (ORCPT + 99 others); Fri, 2 Dec 2022 11:18:15 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53278 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S234048AbiLBQRF (ORCPT ); Fri, 2 Dec 2022 11:17:05 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id E525BE344D; Fri, 2 Dec 2022 08:16:39 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 51CB76232F; Fri, 2 Dec 2022 16:16:39 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B64B4C433C1; Fri, 2 Dec 2022 16:16:36 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997798; bh=iAULzJjTkMYw0u7l3baHfHlwoqKQV2hasTAeqrSBB1g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=l6Vh9ABga2CKt9uX0GKTfUF22w97cxtLXrqoEojoJF0HuWuURmq2zYECSRtkqG6cV ENSpzyDMAfQ/69vN3Hkp3fnwDIYRxAxf3+ceA/FHBlTyyU725/JKrjBMxTTWtaOlHk WpT/WhwXGhd4JONZ4WfKtGbh+qa1rAQBMpbOqB0ueXpY6CouIGrIzyNIFOpSm33GhG dZJjNv3Mcg1KHQWJEkYUa2a/XY8deFiChmC8IXGLnSDplKfKRQbuwP5Vh42hN8YRUR 2gHb9gWblC5ktyFwRCuZYvJpVY0/q3CT/2EWAgKgh6YOIPEuBnbBDrzXx3VKtyAucW LTnBV7F20xeUg== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 25/28] rust: add `build_error` crate Date: Fri, 2 Dec 2022 17:14:56 +0100 Message-Id: <20221202161502.385525-26-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119801168156466?= X-GMAIL-MSGID: =?utf-8?q?1751119801168156466?= From: Gary Guo The `build_error` crate provides a function `build_error` which will panic at compile-time if executed in const context and, by default, will cause a build error if not executed at compile time and the optimizer does not optimise away the call. The `CONFIG_RUST_BUILD_ASSERT_ALLOW` kernel option allows to relax the default build failure and convert it to a runtime check. If the runtime check fails, `panic!` will be called. Its functionality will be exposed to users as a couple macros in the `kernel` crate in the following patch, thus some documentation here refers to them for simplicity. Signed-off-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Wei Liu --- lib/Kconfig.debug | 16 ++++++++++++++++ rust/Makefile | 22 +++++++++++++++++----- rust/build_error.rs | 31 +++++++++++++++++++++++++++++++ rust/exports.c | 5 +++++ scripts/generate_rust_analyzer.py | 8 +++++++- 5 files changed, 76 insertions(+), 6 deletions(-) create mode 100644 rust/build_error.rs diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug index 29280072dc0e..452c9f06c2bc 100644 --- a/lib/Kconfig.debug +++ b/lib/Kconfig.debug @@ -2801,6 +2801,22 @@ config RUST_OVERFLOW_CHECKS If unsure, say Y. +config RUST_BUILD_ASSERT_ALLOW + bool "Allow unoptimized build-time assertions" + depends on RUST + help + Controls how are `build_error!` and `build_assert!` handled during build. + + If calls to them exist in the binary, it may indicate a violated invariant + or that the optimizer failed to verify the invariant during compilation. + + This should not happen, thus by default the build is aborted. However, + as an escape hatch, you can choose Y here to ignore them during build + and let the check be carried at runtime (with `panic!` being called if + the check fails). + + If unsure, say N. + endmenu # "Rust" source "Documentation/Kconfig" diff --git a/rust/Makefile b/rust/Makefile index 7700d3853404..ff70c4c916f8 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -19,6 +19,12 @@ obj-$(CONFIG_RUST) += alloc.o bindings.o kernel.o always-$(CONFIG_RUST) += exports_alloc_generated.h exports_bindings_generated.h \ exports_kernel_generated.h +ifdef CONFIG_RUST_BUILD_ASSERT_ALLOW +obj-$(CONFIG_RUST) += build_error.o +else +always-$(CONFIG_RUST) += build_error.o +endif + obj-$(CONFIG_RUST) += exports.o # Avoids running `$(RUSTC)` for the sysroot when it may not be available. @@ -108,7 +114,7 @@ rustdoc-alloc: $(src)/alloc/lib.rs rustdoc-core rustdoc-compiler_builtins FORCE $(call if_changed,rustdoc) rustdoc-kernel: private rustc_target_flags = --extern alloc \ - --extern macros=$(objtree)/$(obj)/libmacros.so \ + --extern build_error --extern macros=$(objtree)/$(obj)/libmacros.so \ --extern bindings rustdoc-kernel: $(src)/kernel/lib.rs rustdoc-core rustdoc-macros \ rustdoc-compiler_builtins rustdoc-alloc $(obj)/libmacros.so \ @@ -126,6 +132,9 @@ quiet_cmd_rustc_test_library = RUSTC TL $< -L$(objtree)/$(obj)/test \ --crate-name $(subst rusttest-,,$(subst rusttestlib-,,$@)) $< +rusttestlib-build_error: $(src)/build_error.rs rusttest-prepare FORCE + $(call if_changed,rustc_test_library) + rusttestlib-macros: private rustc_target_flags = --extern proc_macro rusttestlib-macros: private rustc_test_library_proc = yes rusttestlib-macros: $(src)/macros/lib.rs rusttest-prepare FORCE @@ -216,9 +225,9 @@ rusttest-macros: $(src)/macros/lib.rs rusttest-prepare FORCE $(call if_changed,rustdoc_test) rusttest-kernel: private rustc_target_flags = --extern alloc \ - --extern macros --extern bindings + --extern build_error --extern macros --extern bindings rusttest-kernel: $(src)/kernel/lib.rs rusttest-prepare \ - rusttestlib-macros rusttestlib-bindings FORCE + rusttestlib-build_error rusttestlib-macros rusttestlib-bindings FORCE $(call if_changed,rustc_test) $(call if_changed,rustc_test_library) @@ -366,6 +375,9 @@ $(obj)/alloc.o: private rustc_target_flags = $(alloc-cfgs) $(obj)/alloc.o: $(src)/alloc/lib.rs $(obj)/compiler_builtins.o FORCE $(call if_changed_dep,rustc_library) +$(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FORCE + $(call if_changed_dep,rustc_library) + $(obj)/bindings.o: $(src)/bindings/lib.rs \ $(obj)/compiler_builtins.o \ $(obj)/bindings/bindings_generated.rs \ @@ -373,8 +385,8 @@ $(obj)/bindings.o: $(src)/bindings/lib.rs \ $(call if_changed_dep,rustc_library) $(obj)/kernel.o: private rustc_target_flags = --extern alloc \ - --extern macros --extern bindings -$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/alloc.o \ + --extern build_error --extern macros --extern bindings +$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/alloc.o $(obj)/build_error.o \ $(obj)/libmacros.so $(obj)/bindings.o FORCE $(call if_changed_dep,rustc_library) diff --git a/rust/build_error.rs b/rust/build_error.rs new file mode 100644 index 000000000000..fa24eeef9929 --- /dev/null +++ b/rust/build_error.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Build-time error. +//! +//! This crate provides a [const function][const-functions] `build_error`, which will panic in +//! compile-time if executed in [const context][const-context], and will cause a build error +//! if not executed at compile time and the optimizer does not optimise away the call. +//! +//! It is used by `build_assert!` in the kernel crate, allowing checking of +//! conditions that could be checked statically, but could not be enforced in +//! Rust yet (e.g. perform some checks in [const functions][const-functions], but those +//! functions could still be called in the runtime). +//! +//! For details on constant evaluation in Rust, please see the [Reference][const-eval]. +//! +//! [const-eval]: https://doc.rust-lang.org/reference/const_eval.html +//! [const-functions]: https://doc.rust-lang.org/reference/const_eval.html#const-functions +//! [const-context]: https://doc.rust-lang.org/reference/const_eval.html#const-context + +#![no_std] + +/// Panics if executed in [const context][const-context], or triggers a build error if not. +/// +/// [const-context]: https://doc.rust-lang.org/reference/const_eval.html#const-context +#[inline(never)] +#[cold] +#[export_name = "rust_build_error"] +#[track_caller] +pub const fn build_error(msg: &'static str) -> ! { + panic!("{}", msg); +} diff --git a/rust/exports.c b/rust/exports.c index bb7cc64cecd0..83e2a7070cae 100644 --- a/rust/exports.c +++ b/rust/exports.c @@ -19,3 +19,8 @@ #include "exports_alloc_generated.h" #include "exports_bindings_generated.h" #include "exports_kernel_generated.h" + +// For modules using `rust/build_error.rs`. +#ifdef CONFIG_RUST_BUILD_ASSERT_ALLOW +EXPORT_SYMBOL_RUST_GPL(rust_build_error); +#endif diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_analyzer.py index 75bb611bd751..ecc7ea9a4dcf 100755 --- a/scripts/generate_rust_analyzer.py +++ b/scripts/generate_rust_analyzer.py @@ -67,6 +67,12 @@ def generate_crates(srctree, objtree, sysroot_src): ) crates[-1]["proc_macro_dylib_path"] = "rust/libmacros.so" + append_crate( + "build_error", + srctree / "rust" / "build_error.rs", + ["core", "compiler_builtins"], + ) + append_crate( "bindings", srctree / "rust"/ "bindings" / "lib.rs", @@ -78,7 +84,7 @@ def generate_crates(srctree, objtree, sysroot_src): append_crate( "kernel", srctree / "rust" / "kernel" / "lib.rs", - ["core", "alloc", "macros", "bindings"], + ["core", "alloc", "macros", "build_error", "bindings"], cfg=cfg, ) crates[-1]["source"] = { From patchwork Fri Dec 2 16:14:57 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28984 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp948642wrr; Fri, 2 Dec 2022 08:20:11 -0800 (PST) X-Google-Smtp-Source: AA0mqf59HoN2THjivGOO3LMup3lwVtFuTajNpxfCJ4wmrNo97oVFukeRMVP/ibMmhDHTWK4H0n4b X-Received: by 2002:a17:906:1f56:b0:7ad:f6ef:e6c8 with SMTP id d22-20020a1709061f5600b007adf6efe6c8mr45263701ejk.541.1669998011389; Fri, 02 Dec 2022 08:20:11 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669998011; cv=none; d=google.com; s=arc-20160816; b=DJkP39tXsXsCPBaUzpeXHarDIti1VTcS1HMRkJLVwpqhNFLelpyYXh7cHZD57hs0+P z288mosct4ONn6TqcmvNZZUHXo5kyCAt7LGHciwYnWE/oV9IXRIRHvh8ryZ0ll3y/XLy W+Avl0VbU+ztfMGCJP3hbQedyW98UPfZpfHlkj8A9Zqwh3sQ9wy1zbi2CUx5ICUtSJHI 3wAlzlhHWGUx2OdGbHt7u6rZylWK6ZqNq7tXEnyPobprf827lDYDOeEmItjew5rHTXbf puYb37u7dutruzYdVngHXgGaU+mf4CGxTC/FgQkOmO4oPk0MhbPxXBreb1N0CPr7RDKp Vh7w== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=ED+gUV3tYJ0qkuZw8mwTENY+M3JbW5VyR4VjDB4YNMc=; b=OYRc4GDZwSDGV8PvJm6BSp4cOvEKkEp/9H5il6MUR0qXW4UjWt+yIery3ldInl0qtG sL5T0s2enWBuUHcSpXDaYxHnAYR22ybEH9vBs0su3lpqAc4N9VgSueEeRylbNz//ylH1 MIydLTQP/YU4x0FOV0Mg28aAiHWGCLqpC3HvzbLK4YVvmRgN5aNMLwp+/ggNePeoaZtx 7V5+efukPZ1p0CaopkRpCTCDBVmyEY0wxVAdTTuvOBuBTGAAAMJeLff7XBoPTT6k9QbS EfomE8hr4Bjtu3JUqDf4jNIrm3FDlQ8cFABV2GM1GJvzzmNVyhi9XOU0Ze5jLMlwsM2j A7ag== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=WjzCHS3A; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id hz4-20020a1709072ce400b007c0c0cb9f25si2187677ejc.3.2022.12.02.08.19.46; Fri, 02 Dec 2022 08:20:11 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=WjzCHS3A; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233728AbiLBQSb (ORCPT + 99 others); Fri, 2 Dec 2022 11:18:31 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53804 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S233944AbiLBQR0 (ORCPT ); Fri, 2 Dec 2022 11:17:26 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [IPv6:2604:1380:4641:c500::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id E52ABE346E; Fri, 2 Dec 2022 08:16:42 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 062AF62325; Fri, 2 Dec 2022 16:16:42 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6A5FEC433D6; Fri, 2 Dec 2022 16:16:39 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997801; bh=qf1L1f1lloAHjax2Q2sSNkOySbNmdgvi1HaQZKetkYY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=WjzCHS3ANJYDqZrQ1IviFl1Ud5lXAOhenxU8ghqXN/mYT6AI55VhO4q9g1G9mrL1F ZQ4jDtc6AffEVqiRMiy5kJLphb/244aEflV/t9SWPY2+aTKo7//vojphYskIh3VU8i VYxhqMWJbNHgYGbWVFWDVq/him1fQMyTfd6ifXX0nwh6hnFJ7YqPZK8x7Tq4JmaM4M +cEPAQdrv5m1FC8xIASmAiiDdrILsj4e9kPRm29RW33nxwlYwCnFPb11XIAl/31qp2 LTjUJ9iYrUJOs+Yq6LKCdtNiRMdk8IXxZoVjSJfH3EHbXJwreyUxQFj0X9NVr3BKe9 uTBASa7Q6VrdA== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 26/28] rust: build_assert: add `build_{error,assert}!` macros Date: Fri, 2 Dec 2022 17:14:57 +0100 Message-Id: <20221202161502.385525-27-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119834778564982?= X-GMAIL-MSGID: =?utf-8?q?1751119834778564982?= From: Gary Guo Add the `build_error!` and `build_assert!` macros which leverage the previously introduced `build_error` crate. Do so in a new module, called `build_assert`. The former fails the build if the code path calling it can possibly be executed. The latter asserts that a boolean expression is `true` at compile time. In particular, `build_assert!` can be used in some contexts where `static_assert!` cannot: fn f1() { static_assert!(N > 1);` // Error. build_assert!(N > 1); // Build-time check. assert!(N > 1); // Run-time check. } #[inline] fn f2(n: usize) { static_assert!(n > 1); // Error. build_assert!(n > 1); // Build-time check. assert!(n > 1); // Run-time check. } Signed-off-by: Gary Guo [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Wei Liu --- rust/kernel/build_assert.rs | 82 +++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 4 ++ rust/kernel/prelude.rs | 2 + 3 files changed, 88 insertions(+) create mode 100644 rust/kernel/build_assert.rs diff --git a/rust/kernel/build_assert.rs b/rust/kernel/build_assert.rs new file mode 100644 index 000000000000..659542393c09 --- /dev/null +++ b/rust/kernel/build_assert.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Build-time assert. + +/// Fails the build if the code path calling `build_error!` can possibly be executed. +/// +/// If the macro is executed in const context, `build_error!` will panic. +/// If the compiler or optimizer cannot guarantee that `build_error!` can never +/// be called, a build error will be triggered. +/// +/// # Examples +/// +/// ``` +/// # use kernel::build_error; +/// #[inline] +/// fn foo(a: usize) -> usize { +/// a.checked_add(1).unwrap_or_else(|| build_error!("overflow")) +/// } +/// +/// assert_eq!(foo(usize::MAX - 1), usize::MAX); // OK. +/// // foo(usize::MAX); // Fails to compile. +/// ``` +#[macro_export] +macro_rules! build_error { + () => {{ + $crate::build_error("") + }}; + ($msg:expr) => {{ + $crate::build_error($msg) + }}; +} + +/// Asserts that a boolean expression is `true` at compile time. +/// +/// If the condition is evaluated to `false` in const context, `build_assert!` +/// will panic. If the compiler or optimizer cannot guarantee the condition will +/// be evaluated to `true`, a build error will be triggered. +/// +/// [`static_assert!`] should be preferred to `build_assert!` whenever possible. +/// +/// # Examples +/// +/// These examples show that different types of [`assert!`] will trigger errors +/// at different stage of compilation. It is preferred to err as early as +/// possible, so [`static_assert!`] should be used whenever possible. +/// ```ignore +/// fn foo() { +/// static_assert!(1 > 1); // Compile-time error +/// build_assert!(1 > 1); // Build-time error +/// assert!(1 > 1); // Run-time error +/// } +/// ``` +/// +/// When the condition refers to generic parameters or parameters of an inline function, +/// [`static_assert!`] cannot be used. Use `build_assert!` in this scenario. +/// ``` +/// fn foo() { +/// // `static_assert!(N > 1);` is not allowed +/// build_assert!(N > 1); // Build-time check +/// assert!(N > 1); // Run-time check +/// } +/// +/// #[inline] +/// fn bar(n: usize) { +/// // `static_assert!(n > 1);` is not allowed +/// build_assert!(n > 1); // Build-time check +/// assert!(n > 1); // Run-time check +/// } +/// ``` +#[macro_export] +macro_rules! build_assert { + ($cond:expr $(,)?) => {{ + if !$cond { + $crate::build_error(concat!("assertion failed: ", stringify!($cond))); + } + }}; + ($cond:expr, $msg:expr) => {{ + if !$cond { + $crate::build_error($msg); + } + }}; +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 9b83ef736298..a3abc110ff97 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -23,6 +23,7 @@ compile_error!("Missing kernel configuration for conditional compilation"); #[cfg(not(test))] #[cfg(not(testlib))] mod allocator; +mod build_assert; pub mod error; pub mod prelude; pub mod print; @@ -35,6 +36,9 @@ pub mod str; pub use bindings; pub use macros; +#[doc(hidden)] +pub use build_error::build_error; + /// Prefix to appear before log messages printed from within the `kernel` crate. const __LOG_PREFIX: &[u8] = b"rust_kernel\0"; diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 178fe8e6cb6d..7a90249ee9b9 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -17,6 +17,8 @@ pub use alloc::{boxed::Box, vec::Vec}; pub use macros::{module, vtable}; +pub use super::build_assert; + pub use super::{dbg, pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn}; pub use super::static_assert; From patchwork Fri Dec 2 16:14:58 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28987 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp949128wrr; Fri, 2 Dec 2022 08:21:08 -0800 (PST) X-Google-Smtp-Source: AA0mqf6SoNqSejFImVUgSqd+LNLfNPo+/aq1aOrAXlg5swC/ZKU8SuQgWl/D7IPGV/YITzKsS2P2 X-Received: by 2002:a17:903:3011:b0:189:ac81:54d3 with SMTP id o17-20020a170903301100b00189ac8154d3mr12806738pla.130.1669998067789; Fri, 02 Dec 2022 08:21:07 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669998067; cv=none; d=google.com; s=arc-20160816; b=mBeq3a8ZiuVhuRA144VB/JgNFWTv24vrGqe2n+syCmvUDR7ugHK+mMYkorR7OwnuIA xyQm5FXiF+eH2VsquAJpb93oy1v6T570K7DV5xHjne/DoqgZieNSIjYsxlsRReRtNiYa +P5eRuU42sx0Pco1XWB1W2/x/fTxHPZ6YqiU+/imfeiyd6AdESoNMUdSiyRINy7PQ/gl /TCkJbmT2uBKe1DMiR7U+tDZJYs2TSWooFZgJX/nhOPRDkEozV2PAoBRgYPoNB7PQWQ9 GiuEZIJyKCLLLfUGPqyaAsh/w7+7Q2gFYTOjgG0eXflu9l9+qAMVqjy1tkKaCxCqUa8P rrNg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=H+qIDzozhgpQC8XQ4TzwJGrLT45xetRrm2RvjeIc7OA=; b=x10okwMcrXSdCUQB6QZKI0THpbLVvP8C2iX13H9wpN2bAzAkghQUUYsT081oyAUrJD 8nUFRfm7pW8/I2skUIuSTO6WDBHDRVmGGcz2pjPLxDLAWib/J+sBgKabbXOv5Mwa+QQg Kj6sRdbM4mBrc85cDKdy0lQXb1Z5Fbw43znd0WsFjpBpHudguDAX9UQWOzcfotew0X9y b2MVjxlA8oFxLfx825Mo+63F0knR7uGzkEP0DGkRqJWNeeALRh0kJPDpKr/3yyKt+vIk qa/Q7B8jhj8Wy24Awa8eos63oDeU6YGZ7kerY8OoWLeNuBkoV36Xrzaae8MVh49TJhMy o2dg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=KYWxTLoM; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id g11-20020a65580b000000b00477cd4f65fasi7539868pgr.197.2022.12.02.08.20.53; Fri, 02 Dec 2022 08:21:07 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=KYWxTLoM; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S233901AbiLBQSx (ORCPT + 99 others); Fri, 2 Dec 2022 11:18:53 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53668 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S234034AbiLBQSL (ORCPT ); Fri, 2 Dec 2022 11:18:11 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 03636DA216; Fri, 2 Dec 2022 08:16:47 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ams.source.kernel.org (Postfix) with ESMTPS id 9DC07B821EF; Fri, 2 Dec 2022 16:16:45 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1A092C433C1; Fri, 2 Dec 2022 16:16:41 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997804; bh=g8YHlGQGI5+kOudmGxtQLpBJJ0VXh/b1x75GjPjycds=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KYWxTLoMH80ob3tE9WkideVGBL6HUpVaeZ5ha7q+gWJ8kjI8kW66x0wMfXqBvNl+s PJQd5K5KQZRPbx0Sf1colbtpMw5EMb5frdHCbG7WXSId49CmBIqnhXOgw/SvWlMLZW /pZ+eLV9PZFDyxqIlZn7RE/zRC50mbZ565dHUtozufFIjPr8JhTyW/GjdODiw5zipj PX+JcqHJ1LzyhAC0rPUsYW4UiIwEtvsY0IeeGfNCYu7LMAw735b5jv3CF0bl//grQn tO5nU021aoxzEyOal7ng3ohpzMfzsMpB4YvPYEu74tLUPOY8AjYGByia8fsEgC3mBx 4QsQIkCbNju3g== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Wei Liu Subject: [PATCH v2 27/28] rust: types: add `Either` type Date: Fri, 2 Dec 2022 17:14:58 +0100 Message-Id: <20221202161502.385525-28-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119893879012071?= X-GMAIL-MSGID: =?utf-8?q?1751119893879012071?= From: Wedson Almeida Filho Introduce the new `types` module of the `kernel` crate with `Either` as its first type. `Either` is a sum type that always holds either a value of type `L` (`Left` variant) or `R` (`Right` variant). For instance: struct Executor { queue: Either, } Signed-off-by: Wedson Almeida Filho Reviewed-by: Wei Liu [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/lib.rs | 1 + rust/kernel/types.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+) create mode 100644 rust/kernel/types.rs diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index a3abc110ff97..53040fa9e897 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -31,6 +31,7 @@ mod static_assert; #[doc(hidden)] pub mod std_vendor; pub mod str; +pub mod types; #[doc(hidden)] pub use bindings; diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs new file mode 100644 index 000000000000..3b0c44769708 --- /dev/null +++ b/rust/kernel/types.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Kernel types. + +/// A sum type that always holds either a value of type `L` or `R`. +pub enum Either { + /// Constructs an instance of [`Either`] containing a value of type `L`. + Left(L), + + /// Constructs an instance of [`Either`] containing a value of type `R`. + Right(R), +} From patchwork Fri Dec 2 16:14:59 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 28988 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:adf:f944:0:0:0:0:0 with SMTP id q4csp949243wrr; Fri, 2 Dec 2022 08:21:22 -0800 (PST) X-Google-Smtp-Source: AA0mqf5apj1sk2JXaZbiKHRlsauCzwn2100T7Iurgt+JDsB5rdiR1SgYWDJNwBILNTlUfQeAIfhf X-Received: by 2002:a17:902:b782:b0:189:a208:d13c with SMTP id e2-20020a170902b78200b00189a208d13cmr17221480pls.145.1669998082032; Fri, 02 Dec 2022 08:21:22 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1669998082; cv=none; d=google.com; s=arc-20160816; b=tCm7Ixopn3Z5ryPBRWiumDvLM+/aCC6di6mbFuNMUnbmOTFwTzm+9i5dUFcAsbG0wL /12Q3ug2bIAz8k8wba69p9xcoMTBCDeM+fhfmPFl5XjIOxn6f7a9PNeRPVoelfS3QMiK v6rVcAdru2rY7AVCI3wKvLEJAlCk5HVIzWctYwI4PPehBAK0dDafStXzGRtHUvi6+8SY EtvfRFDkp4m8Al7tTqx33vXICMt+BAqvEIQxllcSP8axf3LmpIpmWoqG6N2WmiDG4p/R iPjVTHcBSi+hUfc6yqq8BixnvCfbEbFmJCdMAkz7kHKOLRuhc1c+Y/5k5VKn5qn449X3 ZvNA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :references:in-reply-to:message-id:date:subject:cc:to:from :dkim-signature; bh=sxoDggStGU9gyibisVBvy0AaoTqSPzu+cnxgW3+2CgQ=; b=n71IOh93/hm3Imx0kjGh1r7SSpAPj46DLZW+TI5DivOWqkKbQ+NULg1r6kbE7AUBUQ T9tJ6fCsB9wQIDK30bp3pfzUI4i2fRUzTluhAx+cO57yOihUewUeTxFTHUWFIRRlZIrr mvu+H/2LYFgoeHzRzsjVuiGLY/TqrZmx/1fkb5OqUQmZGSbzOauJDviwseMrAkH4E4zT xaGhvBHvLexk7GX+ogpJMzO/nQKuJw6PUo4UuFh5eI2NAfQrZL1z2TvtrVvoUBt4DH2c jonm/6nPac7sxf7Ya7hSVEPjXMksTHDYqPVKLn8BXiCz4cpB9ej0uxT6zDB7KPNZ6u8e CZIw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=iUVfcvaG; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id k35-20020a634b63000000b004705b0ca9f1si7411486pgl.545.2022.12.02.08.21.08; Fri, 02 Dec 2022 08:21:22 -0800 (PST) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=iUVfcvaG; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=kernel.org Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S234030AbiLBQS4 (ORCPT + 99 others); Fri, 2 Dec 2022 11:18:56 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:53114 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S234070AbiLBQSL (ORCPT ); Fri, 2 Dec 2022 11:18:11 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id DEB81DFB59; Fri, 2 Dec 2022 08:16:47 -0800 (PST) Received: from smtp.kernel.org (relay.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by dfw.source.kernel.org (Postfix) with ESMTPS id 7B1A362322; Fri, 2 Dec 2022 16:16:47 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D6F3EC43470; Fri, 2 Dec 2022 16:16:44 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1669997806; bh=YyjXthwblgrT88DPLFu+XIPGLqjTiZLg+Xpj0PN4MaE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=iUVfcvaGJdF/n2QAZNTbyYm5gbDZ+FvzXb1+V8Q7HwFKlarV3seVo1NnOevDs7f9A uxcx1Ce9O/9sI14ZMd98O5sFBiUUgCcucTb4+KI/zXlega/CNBZpzsuRiXAlpPUEux oPtm3kxnmuw1fAt/iUFshg9JMuKQZavSA/KJpFUAd8Rl2yUN8Hbu+6kOtRGKw3hyBp I3ZSh6nvGSQ6ddBxn2yHDHPvwNJKZDL8JoiLX3U6mkmv8zs1eWyZhXSzHNioAell2D 8+znw2S00T/44bGNXLEEUmiMlyC/YIDBT6y9MFZowF6EDXr+RVIhfRd0/qFm5ZqEUb wCkPYCWBYfpTA== From: ojeda@kernel.org To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev Subject: [PATCH v2 28/28] rust: types: add `Opaque` type Date: Fri, 2 Dec 2022 17:14:59 +0100 Message-Id: <20221202161502.385525-29-ojeda@kernel.org> In-Reply-To: <20221202161502.385525-1-ojeda@kernel.org> References: <20221202161502.385525-1-ojeda@kernel.org> MIME-Version: 1.0 X-Spam-Status: No, score=-7.1 required=5.0 tests=BAYES_00,DKIMWL_WL_HIGH, DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_DNSWL_HI, SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1751119908643034477?= X-GMAIL-MSGID: =?utf-8?q?1751119908643034477?= From: Wedson Almeida Filho Add the `Opaque` type, which is meant to be used with FFI objects that are never interpreted by Rust code, e.g.: struct Waiter { completion: Opaque, next: *mut Waiter, } It has the advantage that the objects don't have to be zero-initialised before calling their init functions, making the code performance closer to C. Signed-off-by: Wedson Almeida Filho [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda --- rust/kernel/types.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 3b0c44769708..e84e51ec9716 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -2,6 +2,31 @@ //! Kernel types. +use core::{cell::UnsafeCell, mem::MaybeUninit}; + +/// Stores an opaque value. +/// +/// This is meant to be used with FFI objects that are never interpreted by Rust code. +#[repr(transparent)] +pub struct Opaque(MaybeUninit>); + +impl Opaque { + /// Creates a new opaque value. + pub const fn new(value: T) -> Self { + Self(MaybeUninit::new(UnsafeCell::new(value))) + } + + /// Creates an uninitialised value. + pub const fn uninit() -> Self { + Self(MaybeUninit::uninit()) + } + + /// Returns a raw pointer to the opaque data. + pub fn get(&self) -> *mut T { + UnsafeCell::raw_get(self.0.as_ptr()) + } +} + /// A sum type that always holds either a value of type `L` or `R`. pub enum Either { /// Constructs an instance of [`Either`] containing a value of type `L`.