From patchwork Thu Nov 10 16:41:13 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18202 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251004wru; Thu, 10 Nov 2022 08:42:58 -0800 (PST) X-Google-Smtp-Source: AMsMyM5y2TJFq5WXaXEzO1uWEkhVdKmcSbAIx+vgss23O1BhWRhH3/SuhBRjWn5k1XvT56hbqtAr X-Received: by 2002:a17:902:cad5:b0:176:a6c5:20c9 with SMTP id y21-20020a170902cad500b00176a6c520c9mr1511741pld.57.1668098577607; Thu, 10 Nov 2022 08:42:57 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098577; cv=none; d=google.com; s=arc-20160816; b=rnfX95ernInDZAVbz2GujFr0zhxkVKy+Rm1ti/dGvpFilyv98ydtdACPIOR/OQyABj dOnwZSbOZNP8QgqFdt5qlood+YHDrYgL4YVbN4W6yHxZb/WMXW77L0VZbASolpcrmMne lK6GmBPRAAAM+61q77pOd6kTNQPrY6h4sK63S/yXgv3ZnN7XROuA6UJN8t/IpPKhgaP0 q3Z8cbmRU5QLvIFVaf6oRpANtOACAFt43QA8UpQ0tpeNZJwd/IMEYMmFdg0Uyq4JJuG7 +5O0xSN+m0+JaBHIWu6+lIJkkRooKdQIuRWOT97yY3uIBkkZOVYaGxFuF1sREjHkVD16 aJbQ== 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=Ky3irMIHw9BjxKXhrRB62YwEqHJh7CNWybyxssaMrq0=; b=KTbf6VfOEpmauWs19CtdeFKqmfphhU7qw6GpJ79E09iYLByq65u8H7GoRFAnzF1vrf lKXjuEYmuX4nO/VxpQjLHJhF4si/63TG+bVLc3wNro832IW/X4P5nIjD6I42fJb3PTi4 Q/Dgp+/sKn21yYLIVb41JorSSXhcO8Zjd9dKcrEh6pXPK3XXkC6mpI16c2FjLiNDmj9A Z5uF+CvgmWi93qdAGeUQJYm0No+mLxhEOKMRw1BomKGNc2fsG4qFLteBvAX5Vni2Rm5l nArkb7LQNbU2bUjaoNMliBa+pojbHD49v4PM2tMu/BR9krWsuElNwW1W4FvRGP1rQ9i+ YZWA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=du9DSV2f; 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 m12-20020a170902bb8c00b00174ea015ee8si18407663pls.592.2022.11.10.08.42.39; Thu, 10 Nov 2022 08:42:57 -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=du9DSV2f; 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 S232000AbiKJQm1 (ORCPT + 99 others); Thu, 10 Nov 2022 11:42:27 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:39712 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231911AbiKJQm0 (ORCPT ); Thu, 10 Nov 2022 11:42: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 7550C4198A; Thu, 10 Nov 2022 08:42:21 -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 13A6861BCD; Thu, 10 Nov 2022 16:42:21 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9240CC433D7; Thu, 10 Nov 2022 16:42:18 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098540; bh=TpYB3dU1gfW4+Y/Ug35QXprZPPfBIkjSDAYCOHoY5AU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=du9DSV2ffNd/eTmXOXKDHseXWj0fdF5SabVHYv4yY9lYA8lKRuij1VOdGWFShHAtc bTqhBNIk0vwv6JuixnIUus4RHxpN17Um5v670GoXdzJUMBbt4AEdAeyp1ce1rL/Ym0 ocKKNzwuvsDkQF7Jf9ItZpObvEkQieohQpc6p5OTDauzvNQAfDtvXQY4lCNRTlutou Udgxan5RLaUO9JzkdMw5qsGb71ODMcQ1iazpFdW+c3vGIE5l7xFvYbPWVMEZm1FRlh yWBHn/c1S2XbCnuiib9TIxBZT5oG9diR0dH2BPSkQWKwCIdyL61bwYaWasi8EfMcRO 7Z8o0uDMfNoVQ== From: Miguel Ojeda 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 v1 01/28] rust: prelude: split re-exports into groups Date: Thu, 10 Nov 2022 17:41:13 +0100 Message-Id: <20221110164152.26136-2-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128134079924683?= X-GMAIL-MSGID: =?utf-8?q?1749128134079924683?= 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). Signed-off-by: Miguel Ojeda Reviewed-by: Boqun Feng Reviewed-by: Wei Liu --- 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 Thu Nov 10 16:41:14 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18203 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251225wru; Thu, 10 Nov 2022 08:43:26 -0800 (PST) X-Google-Smtp-Source: AMsMyM6AJaCgrGuD942U1NbRi8Qe6R6ZO0i4jXtVTDV6iJqXA/AgpMSKk9Zqt0baNiThMNVxGzXs X-Received: by 2002:a17:906:c40b:b0:7aa:40ea:faae with SMTP id u11-20020a170906c40b00b007aa40eafaaemr3121645ejz.551.1668098606041; Thu, 10 Nov 2022 08:43:26 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098606; cv=none; d=google.com; s=arc-20160816; b=aqhazOrE+Dy6zRqNZkENuGN0ucFGm5qOYSPAlKmMxo3deFsTVPpWagbdEB7JTnkbJC huYJFno50L0xPyRqXToawDNHXuiaM/HZlgVo1aYOS09hC1RQY2S5YRPYSkr+kTO9lhhL AvT6/nXPktC77CqU/Pq6mRFspmuX8cJZp8udJf6rjjqtEBafsSN4VXUP2p9vhuh0b/Sw EsWok6hy/+VWV1ib/VyDBEZIlfdYqnTkggvzmaeNfKwBUvKOrkfbP0mjKbPm9Ih81ctv Gba9om7GR94vEdCHzi2ihCYxztwivHLi6SFjnrraKipEsaVKH8DWSD56udPZiysViHWw 3zuw== 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=T8vUE+rfvjsgeeaSCxP8XDbKqPw79TWIqOYFgdciEhE=; b=zcroY7eImN5mSOWw476WZQSK9/4wJHpbhbwV7z2qn0MyVPdBhhrjxBf/36X6S63nw0 eDzgtNMEnDhZ3bA2TGdT76Qxv3GxotknrYapwwKHWUc+BeJA8ksJe50WtBjFC1GIGUsk cTQitX3NPRv0hqnEkOmJ1z37e3BJVV5nefNojhohJ1nBlYxin42vkld2/cjLeSAowYIu wVRYs9IaaCYQiTZWSumzJACqsQFwtQXjtJd2RAWm+0nGt4mPVkRiAIRjpAmZUzmh1R4d 3rOsWoH57zpaP9SaueM4YyNAyiaat5Ndu7MHo0FHMtHoNLPVlotUIOXn7oLExA8PdV3h invQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=qSN7hMNk; 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 sb8-20020a1709076d8800b0078a4aad3141si19692621ejc.211.2022.11.10.08.43.00; Thu, 10 Nov 2022 08:43:26 -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=qSN7hMNk; 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 S232032AbiKJQmc (ORCPT + 99 others); Thu, 10 Nov 2022 11:42:32 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:39726 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231989AbiKJQm1 (ORCPT ); Thu, 10 Nov 2022 11:42:27 -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 5363B4198A; Thu, 10 Nov 2022 08:42:26 -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 F31D9B8224F; Thu, 10 Nov 2022 16:42:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6A029C433C1; Thu, 10 Nov 2022 16:42:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098543; bh=tXzOn+7cijuWIp52Zl+aCsVkYnNXzw4FG3zobVkUUqQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qSN7hMNk8q9hSnBx+GzZ7cd5NT3BZyBy1PRfMQ7WDV2U56OxMaBtdCJtI0o6qpdc1 HYo9izT4mpQlBG+mhWk0jGFd3QloBdRD1SmZScdb+dCqC/lskvyFaEvCvKFtbbvboh 3ugwX1amyZsGDwvOh8wcy1PtQtLz6zq8akqMJ1wOW0T+xMYWJXGsfyF49D8y7Cl9XV Cdog5uDSrbtLaV5qwPsJr4o8rC48T3IbyYoLI5zZK2UGb2MXuV74kNlE+Waet9CbG4 fTy5UMfDhKtpjbLeQrj5J/ZABTBQqgDoK7Ooo1+uGJ/G7dyeCSc9O1DSq3Q/wFbMau Zr7qp+bg0KBTQ== From: Miguel Ojeda 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 v1 02/28] rust: print: add more `pr_*!` levels Date: Thu, 10 Nov 2022 17:41:14 +0100 Message-Id: <20221110164152.26136-3-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128163521407422?= X-GMAIL-MSGID: =?utf-8?q?1749128163521407422?= 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 Signed-off-by: Miguel Ojeda Reviewed-by: Boqun Feng Reviewed-by: Wei Liu Reviewed-by: Sergio Gonzalez Collado --- 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 Thu Nov 10 16:41:15 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18207 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251443wru; Thu, 10 Nov 2022 08:43:57 -0800 (PST) X-Google-Smtp-Source: AMsMyM7fDCo5AyV8NLkL2AD6rqgp4Yib7dmUKzMaRysOLF8Mlien54r59U+tvvVGxvjMp/+fSjbf X-Received: by 2002:a50:870d:0:b0:460:5340:d522 with SMTP id i13-20020a50870d000000b004605340d522mr2587485edb.87.1668098636929; Thu, 10 Nov 2022 08:43:56 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098636; cv=none; d=google.com; s=arc-20160816; b=dJWQAya4nA/0YDu+sRRabShNI+dHTF1GbDHexUe8oFQgq9j2rV91eFKx82vubifSnQ IXhUs3vSuSLbA7WnYhHLGOhfyv624om4l6mkXpFKzfoapjAw3sFWBtNGfUSodwE4Oi0p aRLUM/a6KpDE4Z/jURbVO8wv6cZqHYpCNfnL2CRYmoXN4tz0gU58haln5NHeoLBeHHcO oZg/6Q8X4QBtAHPNEF5LJNITXx2ThyCCi2NnLc0CGj3jmpZzMYrfBA0gYyuyzMb/OKvV sBZUt01HJMj+AY0iMXHQBf71MGbTDmdDK6hdm77HLsnJyqmuNzQCg0M6ye8kynKd3GLO RyAQ== 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=ldaEe9KApNhefpDFD1HSGI3dhp7+25X2gsB4zM/xv2A=; b=aEOgZGV1HwpcE5tr1XMGTaH0TTFoKc70OkTS7aWcOR4fXZODrumxjFTusE8JNSthiF FHr+g9wLG75eadTp+2/pyPl1k1f7hfN1sH+J1Hiy15Bpf4c3UMPNqWK6XSHViYmelVDf 7/UiQlsAj1V6ANlMZ0xGAj7ldD+2AkcqbXEo27bAM0kyvyUhbvTg4skEeh+Jt3ONvWpz sNJlZovPObRQ0PkZzTecLQPInE900DtyG/cglHgInFuqklQK8MEgUvPhn1MTeCaIquVk zfInuiovkqNYBq1sJ1HuYgMBKaVe79GrPfXL1ByxfopF2/X63F+mavua3bkFdkKi+SC9 TbJQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b="B/hIsu7e"; 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 21-20020a508e15000000b00461f44d7bfcsi19254edw.573.2022.11.10.08.43.32; Thu, 10 Nov 2022 08:43: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="B/hIsu7e"; 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 S232083AbiKJQmi (ORCPT + 99 others); Thu, 10 Nov 2022 11:42:38 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:39770 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232016AbiKJQma (ORCPT ); Thu, 10 Nov 2022 11:42:30 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 56AEF42F77; Thu, 10 Nov 2022 08:42:29 -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 1016EB82248; Thu, 10 Nov 2022 16:42:28 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7C5ECC433D7; Thu, 10 Nov 2022 16:42:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098546; bh=cjfwm/dXZDtpPVV3XayAZky4PejRTuNQmN9tC2oXScc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=B/hIsu7eDFQZTGjIfhDw5l3TF9VIwHNr2Q6T1YCb0aacp6+nyTgNDM5KKbqHkb1ub Y0bjGjL+6TmWY9djH4F8AQ0EXw28chJgkIo27ooUIf1NA9P8mxht0f6yZmTj9RwX7N QfFx8RAcFzip9FEN4jmiuqaJM9DdfcG2jZVCIDmOGAyiBFfXB8mAQrIU+hSHC5WzQd fruKavWcmD2TRAr3Zw4RZId5zaC3MiLPVW9pxxNKNdhf426JNE/lTPBMsyXHRJkTPK ktLOW+3/N4UiDnnSigIj5l20WHq3z8Li2GTWl63hT05c9rhFLB7tEUHB/u7EYOcguE mvle2s5YdcMYg== From: Miguel Ojeda 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 v1 03/28] rust: print: add `pr_cont!` macro Date: Thu, 10 Nov 2022 17:41:15 +0100 Message-Id: <20221110164152.26136-4-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128196473530412?= X-GMAIL-MSGID: =?utf-8?q?1749128196473530412?= 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 Signed-off-by: Miguel Ojeda Reviewed-by: Wei Liu Reviewed-by: Sergio González Collado --- 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 Thu Nov 10 16:41:16 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18204 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251317wru; Thu, 10 Nov 2022 08:43:39 -0800 (PST) X-Google-Smtp-Source: AMsMyM6bV/782i4R/2hTMGiVS+ZhHM6GjTJvIra4AErCg1NOqFkKMDFex9EpZKxU8rp4TW0qKfJY X-Received: by 2002:a17:906:26ce:b0:7ae:3f79:4d0a with SMTP id u14-20020a17090626ce00b007ae3f794d0amr2836976ejc.120.1668098619676; Thu, 10 Nov 2022 08:43:39 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098619; cv=none; d=google.com; s=arc-20160816; b=s/04cKlzD7m3b6qvTz/Ut5mGyAvIpM4x8no8Vwl4XlW2pPnUP/NeKDLm56FYJrgL5r +iV/4upHyqPFmCHTKMnbnBHFfZ3BrvXjlLXf3wJXqM/7a1SrQxbCsowNEmtWK+KHfuni wmY1jHRqCWuN0lKo7I7NaO0htXOiFJd779YlK5Yw2N9tV8GobJWkrsKyrRVW5Tojw8aM 5hbcIsZjC0GrrOXO4o0YYBk88BtnzJgkA3apwOTWB1LZSd3Y/8PIerh32kCv6yGnTn3t IjNhOoBtJHLcezppshoNUcLcoYnBvHi19MIJWplY4qAeBitGDNxrm1bRmdiVL5aMmyph JhBw== 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=DL8biA4l58Uib7Zi0kvMfO+1q1DrZjakq6c9suKK+gg=; b=NrbNcYF1O6wa+B9ZGxxmVU22jVy2OCkRK4E3xc4wqYLy+X3VXtDgpfLCnZY81B41f1 Rem1ChCYOsvHgpPig4M0Adzx6IvteqtfcHhH3kS0tfgbvHMrkeWEHDVdeiygrwtD8lM9 3/gE43lKQGw0L+9zZePd9ORfogTBT+71GgvkHpMS3EWZC+b19dEDS+uC8wxpSl3B57Uv xe0han4xEKlpq83AUTpf3NYqosNybJT/8iKekhoIt0vP/1tLHWqQhrxY5QKOFGEID1dA L1Dee6x1EXYpTClmLu4PB/UO8lVjPoYjrUup7o36Ppnx2V24SJ0Ubl92Hrw7uHc9izW+ PT4A== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=kFHRJ3LL; 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 kq2-20020a170906abc200b0078ddc074afdsi13759996ejb.577.2022.11.10.08.43.12; Thu, 10 Nov 2022 08:43: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=kFHRJ3LL; 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 S232069AbiKJQmm (ORCPT + 99 others); Thu, 10 Nov 2022 11:42:42 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:39810 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232035AbiKJQmd (ORCPT ); Thu, 10 Nov 2022 11:42:33 -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 923BD419BA; Thu, 10 Nov 2022 08:42:32 -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 4E06EB82248; Thu, 10 Nov 2022 16:42:31 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id E61E9C433D6; Thu, 10 Nov 2022 16:42:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098550; bh=QKUPnCuSt4qJQagjKlcEHWgf/R6XA/d08OIKtNrfC4A=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=kFHRJ3LLht4uHqTvA2yMYuD/T2ka6ewc6LmTvqWp/68elWBdnjquvKyqAxmYBXycR JyriAUY2Fen5o1iJDBbRbKP3Gh/RwSX5mD/geMGKy5yU936R9Jfif7tnxrHPIwXXZi /Nrvl41iIzXpoTwzDxD7UpP6SpynDlu2ttxQzbpJ8r9tMGEO2zIQGAysutNJ5qpalX HiURkpjwPpoALI/3J8kEr8nggzmSlt8QAOW7jc4BKbV5MuMVqAqj2W44PU2eBH7jFn TGii7XSktwWnUtD+PnjNYXPrxGMzDYfrZv+KXdjsKOGnr3N5N8XBdhBbh/C5JXm1Pp GoZG9rfnKihnA== From: Miguel Ojeda 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 v1 04/28] rust: samples: add `rust_print` example Date: Thu, 10 Nov 2022 17:41:16 +0100 Message-Id: <20221110164152.26136-5-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128178067926160?= X-GMAIL-MSGID: =?utf-8?q?1749128178067926160?= Add example to exercise the printing macros (`pr_*!`) introduced in the previous patches. Signed-off-by: Miguel Ojeda Reviewed-by: Finn Behrens Reviewed-by: Wei Liu Tested-by: Sergio González Collado --- 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 Thu Nov 10 16:41:17 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18205 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251328wru; Thu, 10 Nov 2022 08:43:41 -0800 (PST) X-Google-Smtp-Source: AMsMyM4eu/7EqW8SYsMtPxatIQnCKwJOb53ULiStlD52HHzt+xW2jGq0FfYh81FgsEHd8/ZLBYwp X-Received: by 2002:a50:fa96:0:b0:463:56ff:4d3a with SMTP id w22-20020a50fa96000000b0046356ff4d3amr55952485edr.345.1668098620931; Thu, 10 Nov 2022 08:43:40 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098620; cv=none; d=google.com; s=arc-20160816; b=ilQ/v/P+1jtLbs9U7zC9++vTr+UkM103LUr8drlzJX5Oi/uXInEGJCbOdnk29TIZNk Y7FnZj55JqtfQbJcLlLHxdjY6aGaipTg9f2QFKaaFo5qFLs+mVtS5hEmR0T5W0IIgO3j ow6WofnBf2/8sYU49lJsocF7LrQ3+twen4j8otkqxX7+XhFkBl7heqOjL8qBgRy9dN23 jI6+o2Xb5b+0LbcSxS3VsbQOkZ+0S73lbGWr/IgVrguMP3I9F3BW8dX/VSGsvOU9H4kW 5GPc+OozGGDa5amMYGhFbApEwDhYlsagNi5fgx4a/hHjStVPzAaTX45PG3StuLKcUxBm Hj6w== 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=ZNPuuMc10L4dUu70U9sOvLzAYihy0C6hKT8Vm+e30y0=; b=YcF+5IbtuTTNMbIZauNTqKaDY5lYv9LS9B6RLoEJ+rtFBexGtL1VbL1dvHxor5RLwD +dGV6iks/CB3MQx8Z58zx9o2TsQKmkPPTqJcK7a8lVN72qwn1V1UEcUxWBSQm/WMV8KO XCos5A9+4GY/N6mmQVBbAf1NMVrogfhRagfLSRUJtUxsXAzya/Q8sHzdrhzBZhsWo64A 3HuYL238rE2F8qW8WFy6e+UFMPbpCPpJ178+nSQfvjw7D8S6GPWaiiSKTD7IArC8o5L+ BgUCbeLXAZYCw3jVk5BDzHyiOJUDqp1bPTF4eKPceiCdBw9q6c4y+MJudGGcJgMJnaSB oLaQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=BSw+HTvT; 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 s17-20020a056402521100b004593671898esi19063edd.611.2022.11.10.08.43.16; Thu, 10 Nov 2022 08:43:40 -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=BSw+HTvT; 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 S232127AbiKJQmp (ORCPT + 99 others); Thu, 10 Nov 2022 11:42:45 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:39970 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232067AbiKJQmh (ORCPT ); Thu, 10 Nov 2022 11:42:37 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 1F1B743873; Thu, 10 Nov 2022 08:42: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 AF77D61BCB; Thu, 10 Nov 2022 16:42:33 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0E308C433C1; Thu, 10 Nov 2022 16:42:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098553; bh=AMkgQPuKRPM8nukZjM2ZwIbmA4VXBv+Y/FxTSShnnN4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=BSw+HTvTR1YTwG2L2/IDN14ICE8/eRnpXQ+wUaxgoRuAo4ky79Uzh1d9UoUkMGawo hCR1elrv3JDcen+1T/eG56Yx3t5rjjMaVFoZILt42d7jiU1umM5Nkqs540U2+FdcMp sIuRSVi2M5ahdmCmEX2qfXJhbrixMri2seWgjThtQyu+nZuMq6LfOotGIlJ6jvQzxQ O64fBYUlUrGO/35w9YvADIUoIc3Nz4S5UnH7UuphAzbcLq+AgqtLzcgSE9e3mWflyE mRf7b/MTzNouujFnULKfb2jG7VKPCv071P0Q4BgHT7DluNjmJYuRWp139XP8JGKdi6 o6O3MXqnfEmCw== From: Miguel Ojeda 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 v1 05/28] rust: macros: add `concat_idents!` proc macro Date: Thu, 10 Nov 2022 17:41:17 +0100 Message-Id: <20221110164152.26136-6-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128179042619607?= X-GMAIL-MSGID: =?utf-8?q?1749128179042619607?= 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 [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Finn Behrens --- 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..3b5a9dd70e8a --- /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(&(a.to_string() + &b.to_string()), 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 Thu Nov 10 16:41:18 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18206 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251421wru; Thu, 10 Nov 2022 08:43:52 -0800 (PST) X-Google-Smtp-Source: AMsMyM4PWHox4H0J8Ex47wkHheiK26/DBHRgrEd3pzUhdG6LYcSfD0yXz2cVK6f9sdqIR4T1ekPW X-Received: by 2002:aa7:ca54:0:b0:461:ec03:3c04 with SMTP id j20-20020aa7ca54000000b00461ec033c04mr2650072edt.24.1668098632318; Thu, 10 Nov 2022 08:43:52 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098632; cv=none; d=google.com; s=arc-20160816; b=uWSPHN/f46jVlUvjdwhjGHriQW7bplSv5C0awDZmJPr1684eSz1QOTr+2EtaPlVTSz uF1Trq2CF43ESTt+rP3oq9JkWRx6rHhV0hobS4/nQZFDVkO91OF0QqxU2oNclg3BhaWi kjcxK7DN1/xTTHxby962EzhEzcQGH9fhpXc+AbosuuNYDBxDtI/39wcOLy/G8oX46aLS vVPN+m9IlMamMWf4a+euAWpaDAvMef6PX32/6xgItouVb9lRYAe0Eg4GNMqElO7ZTfja HTMfCeRFacKBe+on7PLLI1rm43p6Yg6QKX5aQ0uiKTeDNjTbcPO4FfJEcyhcMJHw6D9W lGJQ== 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=v7eV+S8ivYWXkYq9+haQ1gOFr3R0P0LwRqUoYegbXzs=; b=DZ2IZUFjSecizaXFnjOPc7jQxVzCYRFGhcLJd8szW4c0ZMgfpLICWNkNWjHwb3UXLF rm1w2QO9ME7DZNoLyckwPAgb0KS9QzLfmWShyRlsYXAr9AZ3VbJ/Dg3gQmE9JGr/aSFo 2wdIeZsn+CkyN0HPIi9c6tg+fyndjVXHUULsXm04ItnswNP5ejkSYbMSE1WsfM5Mliwh iLCz7ZDJBlteCmpObImvKDu0vb4+gvh4LejTu16aD5iO40vRcRS4FxR2IFitEKfUXsZO OGYbg6xBAKrfx6yFONt1E9WAzt5odPyXPNBZbaFWEDwNeKDgGovrW3aZZna02YB2jqqS gn6g== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=j0ZcbNCS; 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 dt3-20020a170907728300b0078db371355esi18422385ejc.987.2022.11.10.08.43.28; Thu, 10 Nov 2022 08:43:52 -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=j0ZcbNCS; 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 S232176AbiKJQnA (ORCPT + 99 others); Thu, 10 Nov 2022 11:43:00 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40058 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232099AbiKJQmj (ORCPT ); Thu, 10 Nov 2022 11:42:39 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 526B543AF2; Thu, 10 Nov 2022 08:42:37 -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 E2A1761BCB; Thu, 10 Nov 2022 16:42:36 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 439A1C4347C; Thu, 10 Nov 2022 16:42:34 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098556; bh=j8Vv0JsY401mmuX1GnDq9A3c9gx2HGMWyl7yi4WgHN4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=j0ZcbNCStzx5mABTaSVrD/sXylGjxiWKUyEOG+4ul+Y0x7EzTVYg88N4cypw4uFVu JL8qfoUkpdr812dgFNyPWBSgst072b39TTPrbXhL4zbPjyWeJ2wVUQvWX81dyLlE2I w71o14k2k/Amh1+5mdp5WkJXSinvwhU45ZIvNBA3gopq5UrzRVmQrR8EADO/x/4Ysn rzEQoSqNGGGecSnrI7GKvoRzFRFeoC3Q3Js45UD5w4R1uedOZAERSW1FO1yOTJaytF RrV/Z6jD0vX6+9hUcw/gjm8vEd/GZrrrecTPwd9bioiowa9dlfRLiHtdrVY2XWiB4C 1zQjN1L8zlHXg== From: Miguel Ojeda 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 v1 06/28] rust: macros: add `#[vtable]` proc macro Date: Thu, 10 Nov 2022 17:41:18 +0100 Message-Id: <20221110164152.26136-7-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128191763978281?= X-GMAIL-MSGID: =?utf-8?q?1749128191763978281?= 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 [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Sergio González Collado --- 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 Thu Nov 10 16:41:19 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18209 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251652wru; Thu, 10 Nov 2022 08:44:22 -0800 (PST) X-Google-Smtp-Source: AMsMyM7sLyJ/YdrNDnmz3Kku6PmEjSg0G730ClqPFTT4O1rBEpyndqimn+JODAF8bpaVYpjL0Cye X-Received: by 2002:a17:906:4fcb:b0:791:9a26:376f with SMTP id i11-20020a1709064fcb00b007919a26376fmr59195844ejw.431.1668098662233; Thu, 10 Nov 2022 08:44:22 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098662; cv=none; d=google.com; s=arc-20160816; b=ueNhe14dK+aKkVWYgs0k3dKMa6BADifsa7SSpH2g6MbZHZL0H7m1iw7yEtP0LkpOnk aUzHMWqAD9a92SRo5KNk3wCUZLvDThD5LQQcyM0U4pqm9hR+D+CZ5huON9d/oSlGeKY4 59EDCp0GJp52f+D2mElZfgXStL2PEX2lagxrfy4xvpizlAP6lGPsomVvKG+4EDGfcknj GcLy+VtC90fIvmu80sa2NY41XlMviWTxSBSaW8cJAnj8q1c0eK3zZWBHi8LJrKlPS7l2 9VlLGcuFZSby/TeNRgTemdIF8ApTc5q4tq2/3ZheiuPRtNNS7tQj+BjBtRG4+UHJDHrc Mhvg== 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=pCUPsyOlXwgapw7WsmIsOpUk3MlN7wjeIpz88jMw0PVFqL86ywP0mW0ODBzKDpPt9i gAroRMGUVP0aWcEGveGmbCjLRXenUW2P3meS7YznfOaFzI2HZm0rk2XqFiw6b+8dupHV avUSgXgy0URfto0WV72Al6vr8XB8Z7XUEg9xfyT4mdfpmE5c3/FnWyvMq9bBfyMmDdpV eSPlqWpOnxXVtTPQA6OlxXZHaA28dBUzdQxEhcKX8xfvBoz57qCsPgKff4LynJA8BnYo G0DRtXJF1AVVWOT2NG4QQkkWvM0F/+Xv/LAprUy2mj12M94Can+upMeSNnb9905ma90U UWVQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=HEC7BC06; 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 h25-20020aa7de19000000b004616acd9cbcsi42454edv.360.2022.11.10.08.43.58; Thu, 10 Nov 2022 08:44: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=HEC7BC06; 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 S232076AbiKJQnS (ORCPT + 99 others); Thu, 10 Nov 2022 11:43:18 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40584 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232140AbiKJQm6 (ORCPT ); Thu, 10 Nov 2022 11:42:58 -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 5428A45095; Thu, 10 Nov 2022 08:42: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 ams.source.kernel.org (Postfix) with ESMTPS id 095B2B82252; Thu, 10 Nov 2022 16:42:41 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9D6DBC433D6; Thu, 10 Nov 2022 16:42:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098559; bh=sgzLAxpoWYOhhz1qABiMpx4C/FWitRtqVHgbxRNmqTw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HEC7BC06OAR9pVeEukkGaqBFYivIWanC36Ml5l8z2qN9azjXT9hhFIMHhquUvPRSV kpSkIwgiFbSCECSgzsmTbREoKNwte4NUsinJSlOItbwU60n36YC1fBy6jdfoQIATCf mePvqXfMaUXcE3hlW6P5HqBo8gFP8mESSdBM+UyRbN6LHN37PiFDEax44R/oEoqt0V OMLT/JLBBzwlfc4lY4gFqHNCoT6lErjpydHLxOLxtLV2r830Vn7bdIB/B9MOBIAGXf CmuhbPf2nHX6WKcqv8kmf7aRGE6TtR5DaXNEvX9OiAzw8m7jWaU7og7EjJMHkl5/iO 3Qa8pm35Xs05g== From: Miguel Ojeda 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 v1 07/28] rust: macros: take string literals in `module!` Date: Thu, 10 Nov 2022 17:41:19 +0100 Message-Id: <20221110164152.26136-8-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128222755555025?= X-GMAIL-MSGID: =?utf-8?q?1749128222755555025?= 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 Thu Nov 10 16:41:20 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18208 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251534wru; Thu, 10 Nov 2022 08:44:06 -0800 (PST) X-Google-Smtp-Source: AMsMyM4BxtU0avBUjSPWUVFQSEdhi+gQNAuEbdFFtoFgPX8Xmaiudi8tphUmk0PKZ5ydkUy1AHpY X-Received: by 2002:a05:6402:c87:b0:459:9dd3:2217 with SMTP id cm7-20020a0564020c8700b004599dd32217mr2589667edb.163.1668098646706; Thu, 10 Nov 2022 08:44:06 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098646; cv=none; d=google.com; s=arc-20160816; b=XVmxTaUVCxwSlW/HKfqDfnak1PW0yswxpGIMHuqy6EqmEscyGjhHfqUNWxzGtXXAv9 Zz5hea+vrpQ4kB8zCdbZB4HAGhQmZKlMQrS/EA8rOUmY8DENgS6U1TtoYPC5YFdhgzqL Rj7VJsbzBu2Gi5FPFicbvJxThwkyBEWCflba3V58eKcFRnHm1cK/xNwQK/AdyA4iFbqT Bb3yvGEb1xVm06R9DTwTSSRSYUIGmdjUeivkL5h39F6wHodAJIOI7zrmvGd2iBDi59fI B+65ZBNaB/Teo8JkX1C65KCIeFbBZzKiPo7p6tyxI0iejRFEMb27HEY8mJTco45eI6N4 fAsQ== 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=g5cVh0xSq3jaNRDqfhMMQW4dkxnGleN2X+5zgROr4jI=; b=TXKQ7SfZGsAhEHVAwl9rJlhsX+STn3XraFNMBRBkgedUhbfpa6Zcx6UeU7UJYSd6HV l67ZocYQBOFflI8GWJ+5wSvf0LGlHGXo+lwRxaVyuaNKI82GpRV0sh762SOF9CBSpfTy uVthyYm3FkXM6zOfyPyWSypf/giSmfwXw5NQ2aNC0MWsc8O7qULy9axhO6vACxaVALpo DDk0WkSX1oNKRdWi/HWxAw95tqbWj36jBFjT3HieQ3BLgUHjDS4f27Oa/xFJqb3Z7GWX 7Lp4ZNLMMpvYknlVbDR36M2U2yDOYT7YN0ZaP4sKRSMmFX3om2yeAYvpjfKHl5mccMTz C+xw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=G1+TkYS8; 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 hr14-20020a1709073f8e00b0078d878d8fb7si19213852ejc.920.2022.11.10.08.43.42; Thu, 10 Nov 2022 08:44:06 -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=G1+TkYS8; 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 S232115AbiKJQnO (ORCPT + 99 others); Thu, 10 Nov 2022 11:43:14 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40056 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232145AbiKJQm6 (ORCPT ); Thu, 10 Nov 2022 11:42:58 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 97387450A0; Thu, 10 Nov 2022 08:42:43 -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 2FE5161BCD; Thu, 10 Nov 2022 16:42:43 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7DC79C433D7; Thu, 10 Nov 2022 16:42:40 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098562; bh=6C+J3CqClsIGimlHszB691qkxwmrQJQgf22GuHYX/4g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=G1+TkYS81fI6KSg3uG+BjrvTTqwlFukFJRj2LwmIc/PY+4bu15wKIHNVRoMKmd2w3 fOILmAK9tfxfkhrj1mZCLHN67XlwCgHTuFOTQtgog4E1l1DZijE51REMWOHUKX+AgU Cf6Cl+PmHmrNUfwGYynRW6v35tV6JQ8m47tEE1noO0kLk3P4GpQDeLriy/uMxv8jCZ 8EH6wHcR5p2rdvqVYomwjKh4SreNFMlss2KEl0EdqsrU1t90p8SuY3Kuet8yilSJ6s /Amoxx4CaUbgEQ5q6nVtIIkC6vyTWt/zaw3fEq7ZGmCqORj1UXaSXE+1FYnYfbnWw5 lXJ435A+AMdog== From: Miguel Ojeda 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 v1 08/28] rust: error: declare errors using macro Date: Thu, 10 Nov 2022 17:41:20 +0100 Message-Id: <20221110164152.26136-9-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128206695513604?= X-GMAIL-MSGID: =?utf-8?q?1749128206695513604?= 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 [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Gary Guo --- 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 Thu Nov 10 16:41:21 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18210 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251670wru; Thu, 10 Nov 2022 08:44:25 -0800 (PST) X-Google-Smtp-Source: AMsMyM5It0VWJkZ70IIgKiwUGbigSJYTrTjwQnWZGj8Oj3UFIz9sb8vSDspYlkpLEwTF7snrY7si X-Received: by 2002:a17:907:c19:b0:7ad:e10b:c415 with SMTP id ga25-20020a1709070c1900b007ade10bc415mr46499663ejc.537.1668098665065; Thu, 10 Nov 2022 08:44:25 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098665; cv=none; d=google.com; s=arc-20160816; b=toLvwHXhpKGGFDyeFhaG88DWcdk0F4WMQpSvgessQIzjkGwdsg/zwDRC97JS1Jk7+1 Jzq2KRnPSTMNLoRv7qkZslwREu4N9bLNi+GJCMfD2uTx9vDNh2EcbhGY8m1vhL0zI9Vh 8bd16ebZ1V4DmnNKpjXKBPCucNhrBDa63PWXFWNdD89SEf1EyiRZUdGSVPYs50MlGuT8 0F6q0Eh0WAENx+FkEBKOuoIYoiMMgOWFCz6ukZ+vlToCq7oOTIl1msC5s7jLv+M+7EyV mmgbL3O7yQdNsQTGX+J0sjAeMX7RH4VQHYcfG3kM3cPPK9S9+wHN4zJ9+Zay2YdzpuUu C8sQ== 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=mgLnLC9ChpCvIxT4ohlVSrmKxcmu75XokevUDFzZeAw=; b=UlSMYGUYMtLDo/dFNrJIddxaLWEPGn/hvTBhyIAXBKTKXE28KEi3gGlDFWbomEFWhc YesI7rDYmNS5XAyWS7nci4Qckxf7Xg+SFRz/w6moFWOMagKs6O2JOyMazI7+JlpQuawd BxqXYZ7AmUaaBgbEdCu+jj64kwCX1lj87cpE4A1bwOJa3YpStEcLPkr/eUEBnMDS8Gch XVLjzQ03Lcy+VIaxWYaDnk1A9tNhzxQRi/0mRLIZevx0xUW92f26u4id7xyizcZEe5+x fHBuLEEuWwk91qjl8b0j/Ku1YN0o6/v+PuRmeTerFl7G78Huf9287bH6t/kWDwWKCtI9 AjVg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=defv2G9C; 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 cf24-20020a170906b2d800b00781e17d3699si14168688ejb.203.2022.11.10.08.44.01; Thu, 10 Nov 2022 08:44: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=defv2G9C; 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 S232122AbiKJQn1 (ORCPT + 99 others); Thu, 10 Nov 2022 11:43:27 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:39930 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232195AbiKJQnC (ORCPT ); Thu, 10 Nov 2022 11:43:02 -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 4DAB545A02; Thu, 10 Nov 2022 08:42:48 -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 ECA7CB8225D; Thu, 10 Nov 2022 16:42:46 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6557BC433D6; Thu, 10 Nov 2022 16:42:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098565; bh=zrkavDKsBthT94ju0QKne8tZOVOAyQVpPnOep6nNbD4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=defv2G9CQv4RktVFNQNYIolUchVkLP9Wq9ByfDiqNu63DeSvdvWA0Ax4wY/j5/Sd1 tRNOsoPy3x6hDXT9L2L30RD+6Cgv27U2nN1UaLW2p2TO+f8Bx1FerAC5tJM8Q5luE7 5KGB+tgEub5+QyLrVQAhnAr/adNRgT7mi9c0U880z1OslWQY9D8+jCSGjYprxnCpPG 4NgMnIkawCVT2rS9XKBnQwo6+VNsLqaiGNTSzs1+OjXhtZwRSKsS8rnWmL4Lw1//7P JF680DAc4dhz7Ozt17PuKli23dQr/kaHvXY5dvv4rGBlm6nnKrdyLamMhtImSZ5/wF kQ+e8ErUC2YSQ== From: Miguel Ojeda 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 v1 09/28] rust: error: add codes from `errno-base.h` Date: Thu, 10 Nov 2022 17:41:21 +0100 Message-Id: <20221110164152.26136-10-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128225759217626?= X-GMAIL-MSGID: =?utf-8?q?1749128225759217626?= 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 [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Gary Guo --- 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 Thu Nov 10 16:41:22 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18211 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251686wru; Thu, 10 Nov 2022 08:44:28 -0800 (PST) X-Google-Smtp-Source: AMsMyM4nXD5OMylyDH65Oam5rp99eImtRM1MsV8bk4fwSPkJOK9sEYYyVFKFzgK6aDuBQBSActoE X-Received: by 2002:a17:906:6155:b0:79f:e0b3:3b9b with SMTP id p21-20020a170906615500b0079fe0b33b9bmr3085710ejl.378.1668098668615; Thu, 10 Nov 2022 08:44:28 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098668; cv=none; d=google.com; s=arc-20160816; b=GnNo30hlMF8hrDM1Vw6iKyNq/XqU9s1TW0VIUbTx3LKqxu+QE38pzBOTld9Irn6MFh 4NiY2mreHg2fSY3U04+KBStnrBc9Mg86KnWNfsjdWOyo98sJXOXg1GO9kuIUBjeoCU6L lmgRKZKBvCz/hHo8r0l5knasWugsPpDzErNBH5kLP0wgi0SGYLs79R+qMUDDa1sjMADo KOn1IZy7MENhM5johu1vZ40C5R8cObzC5vw3/yX2AxcYSMayUFz+i/eJXRBYF+Vnkg4d M0lPkwZlV9cIUJEwnuwdt6HiLcOlwQwZxmPzufiHOhNKAPbvdfBmrracxxGmGv5M6qII RQTQ== 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=GEALJcaN68Zb4QzXM43BVOkHunzRyZjiJ4KxVcRED/k=; b=dTsiVKIP02Uro3vjHVAiznB/nOXdPtp42WHe5dYPvIRFiiVvgPAqw9+n0/R4hVe8j9 xdMCQSu/SgUb1RdpDKM4cPtKDULUojgYQTzZXLyDfqHugQPhEruUDDmim+O14PKfWwQn K9z7g4RCWgoYRipxTz2dl6lnlnYBfIP+CA7cW5K3DANwws3SbS7j9k5UT0dQXdcWR0az Fzh7jyuuuXSqptNpgRZoF76QDAu4h90lrer1nhFlJyL9kVlm5PrfM2C6TVwqG6gQfdEa +bnRNw1bqaA8dKPHu5bULF1FwaUFPNRJjwV6KW/VxGpCiG7O1Ld0NF9W6Sv32k0lAprW PQmg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=WSG25kTp; 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 ed15-20020a056402294f00b0045cfb63a033si21495edb.551.2022.11.10.08.44.04; Thu, 10 Nov 2022 08:44:28 -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=WSG25kTp; 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 S232234AbiKJQnd (ORCPT + 99 others); Thu, 10 Nov 2022 11:43:33 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40568 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232087AbiKJQnI (ORCPT ); Thu, 10 Nov 2022 11:43:08 -0500 Received: from sin.source.kernel.org (sin.source.kernel.org [IPv6:2604:1380:40e1:4800::1]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 8213845A2C; Thu, 10 Nov 2022 08:42:52 -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 sin.source.kernel.org (Postfix) with ESMTPS id CE2D2CE2328; Thu, 10 Nov 2022 16:42:50 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 90A23C433C1; Thu, 10 Nov 2022 16:42:46 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098569; bh=7/BYuBysk0ovFW2IxRe1BxcDiN48GCNf/QdZo7baLig=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=WSG25kTpYBQoKiCLhSZTPhkydYrJwchGquJUJx4Y9FJC1OEa+uK/gflPhWRa+hZua YV48APql0DDQMaQxHYWDX/4ofRlj0tp5tLr1bsx//+9I3IIEjEDtjhm0GTyYX+J2Nr tFb7l87VZ6VbX3o3GPdwD8OfVtkUP266mzSoO4SvHIyYMh+hAMTkareFordH0ZLG4N 5/SBBKVarR5GCjlePpwbDvXzM4mdInmRTUziiDg82udpkJ11F5eaz2O5OK212qSgHv UWuQ7CJ6cj+mfTyBjJU9j4qogTmhl5ffPd1eG4OI3e5l2L331qh9ul7AGPYr/Blnrp Zpu64hINj4AWA== From: Miguel Ojeda 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?= Subject: [PATCH v1 10/28] rust: error: add `From` implementations for `Error` Date: Thu, 10 Nov 2022 17:41:22 +0100 Message-Id: <20221110164152.26136-11-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128229591799823?= X-GMAIL-MSGID: =?utf-8?q?1749128229591799823?= 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 [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Finn Behrens --- 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 Thu Nov 10 16:41:23 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18212 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251707wru; Thu, 10 Nov 2022 08:44:33 -0800 (PST) X-Google-Smtp-Source: AMsMyM579WSp0rajVZnYsV7CnUSIEMArWdXDjlw17L02zL2S36QEqXwdE8314F3IXg/OpOUTQQuH X-Received: by 2002:aa7:dcd5:0:b0:461:5fad:4215 with SMTP id w21-20020aa7dcd5000000b004615fad4215mr65947611edu.332.1668098672985; Thu, 10 Nov 2022 08:44:32 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098672; cv=none; d=google.com; s=arc-20160816; b=phqLfo4N8yN0hI8uSDdnDmFWkOOMjYmpUvmS2+RasxuTzFvCNFlUMVDqiLkGqMyxPT CA4KgEsNg1sKlV8e+6JAbYNHx9gJLyUoCmFmJGgWMuZDaEdQxLvLeBhrodbB+KGaS8MN XTlV8unU7XIIJhLW6Ef6m9aaGIFkgAuWDWalEG6yUyWiqA+h2OI+w/M/VK8iFFf1PDC6 f/+o96XQ0t8LroDM0rT+pF/TisYF0sNy3yCFik+nYAHGukFwjzGQpOilUEuHot2JbHRK VfOd18SWGwSiyty8Pg3bVN56PGkF0YnOtJmw4zqjkt2y28fkTcnt0WQD0GOzwRA5Wm8Z VzMQ== 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=kjyB0L3v/WSt6i3VJ0y38bLFmB3YWf7Yg6UXFfhxsTw=; b=GXMF8sJ70EF8ALPQ07ThQ3M7jr+ataQGln5uKKVDaLhmK7Gw9WffP/roS8yAAaczBq BzUUTRJcMpo/Ucq3lqyOjZSeFE848T8Vqam3aNUTGJ3QCGFKmiP7Ztmv5lCdAfWHL1iz EWt8Fyk+fim4AStzYxbp8zpTUEO2/TStoCJY8tmQvH1D/C0306xQYpLcJWhNtHxzj4tU 8KHcuM1EHIipaOb5pvMX1AS+Pd+XNkjxYll5BKxo+iw9Iuf+o+GSHvm6tvFscOghBZmx YzpuSTwAYYB4Inm7J31dDu6AHUgxoL1aOXPeKPgBkYbfVdSjasCu3oYGs4VllT8Km9BD 8idg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=uSw9Fyis; 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 gn15-20020a1709070d0f00b0078239e3f846si20827528ejc.1.2022.11.10.08.44.08; Thu, 10 Nov 2022 08:44:32 -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=uSw9Fyis; 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 S232282AbiKJQnj (ORCPT + 99 others); Thu, 10 Nov 2022 11:43:39 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40916 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232269AbiKJQnJ (ORCPT ); Thu, 10 Nov 2022 11:43:09 -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 4D9FE45A3E; Thu, 10 Nov 2022 08:42:54 -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 0DA30B82248; Thu, 10 Nov 2022 16:42:53 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id CC6DFC43150; Thu, 10 Nov 2022 16:42:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098571; bh=J+cwd2iu48BeHn73Bu4PeBxaaHkYRYafz2YHSK3Yjjg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=uSw9FyisDjfN09jEGFqMNicm0MJQe4gjqoQHUcw0zW8s3zbT71HkF7coKOTFDAIEF KeUAeyvy+trgzIGFr7nvNIJdho1rG3qLM/6MeFCQJqonH9iAMxHZEaf7CaQDsl5rHi pxtgrv2vNzqPZqfvKpIhhVcLd816IsfyaBZLV9ifPgsgwe3XSmr3EDC7dRb1HiPUqj 87PKmFi2DHO5LxTg+sErRFR9xN0Oe2rM1unhtzfDoibHtxRMWvP08FALvX7eyqz+WA 7pp60pskFP9ppg3E1HOuKdgPqGDGrpXKlpe9CFOfIvdIVxUZQwwF8eI9GK1CgQVA1w MUqryAoSBk9HQ== From: Miguel Ojeda 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 v1 11/28] rust: prelude: add `error::code::*` constant items Date: Thu, 10 Nov 2022 17:41:23 +0100 Message-Id: <20221110164152.26136-12-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128233980016970?= X-GMAIL-MSGID: =?utf-8?q?1749128233980016970?= 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 [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Gary Guo --- 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 Thu Nov 10 16:41:24 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18213 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251770wru; Thu, 10 Nov 2022 08:44:42 -0800 (PST) X-Google-Smtp-Source: AMsMyM7N7zkIDPmAwbH5dV0poFlATFWRXu/GQOPUpceZ1dU8iSRK5sHDhhmEJiuDFOs2Ov0j0aO5 X-Received: by 2002:a05:6402:b6c:b0:461:c563:defa with SMTP id cb12-20020a0564020b6c00b00461c563defamr2597033edb.72.1668098681853; Thu, 10 Nov 2022 08:44:41 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098681; cv=none; d=google.com; s=arc-20160816; b=YVUb2HEeBRa6kVcH3GuN8SRGmRXlFWVDU6ce6c3DtF5W1M8+MGX464yc8DB72ydm0c Ni/MGcQwjPFsZPCKaVKArw/aKTp2m19g8oYjt0WpT5WlihlW5aqZDiL3g/E8NRqNbCHf IYrSP8k/lu+lbeghuHKvZcKIq3tjO9qHzOBwcB50ODxBymE+BfuSs7amAKkrIfJEp/hB 4JQoVr2jUAtZZREzDVCH/8xnqG9KqEwC+cf5t4hHQDgN0SyNiYgPxKhde/5nCbhbv7j4 BHs4P19l4QKV73Xwpbwu5JNUNUWdttE3Xg66XPs4A29CsCDlVKgNOEHw6lP6Fw4m+SFY jirw== 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=eVD7pQO0toRvJ+1A1FlIpZOJCQUXU8SyPHlX2aiuCQU=; b=KKqQiUx+oqs2a/cbas7KzpEkCy+QRspEBByHzRIo0yc+vmRtSE5YsNewoVPJ6K84D1 GzYoOiHdMVwp4gLBVSQOgTgx8qLczSeTuAZlrs5OHwT8oqgOzYOok1XClU+LtpZi9Xyr e8CpxpHcJ38CK4nCv+7zJqWmnjvP178VftRB947cThQQ5XpB9CHq/sSmVEHfR4Eb1JKR MGXveM3jPnp0q/Q2xpvMA1351DZ1fyYsd3+lDX9K3eNKZTtxsQ8AT4giQ6qqm0lsLxO9 z2CvYkJUmb1HnEwlpICYb1Snfv8X9lLMac8/hA1Uy1lzi2yG+fibW/yOLOJbasF1u5VZ F6Kg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b="P4Bx/5fM"; 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 f12-20020a17090660cc00b007ad855bc09csi15101096ejk.595.2022.11.10.08.44.17; Thu, 10 Nov 2022 08:44:41 -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="P4Bx/5fM"; 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 S232287AbiKJQno (ORCPT + 99 others); Thu, 10 Nov 2022 11:43:44 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40594 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232274AbiKJQnL (ORCPT ); Thu, 10 Nov 2022 11:43:11 -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 8E59145ECB; Thu, 10 Nov 2022 08:42: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 2B36D60E75; Thu, 10 Nov 2022 16:42:55 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 852C1C433C1; Thu, 10 Nov 2022 16:42:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098574; bh=oHlabre48JwaQeQ82d/rrnGlLyDZ1CNALanCqEPU3dw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=P4Bx/5fMNOjtIMrYghXNmUtzIdPI4JhjRlrRWBRrhfd5cTaivD5K2wGsqAzYlSn0+ KRyBBHNuGQnBXvI5SV2wbxTs1JHzfzT4LqQUPmwJ1rrvha15ZLz8dREEP4tTirp1bn 9JDVflUqFXxCop7nlp23gmGF6+hB07TaO3xom+/StRWZErd9wLBg/iKR8fNWcrgKb0 tpBoobNEDIQ474EIgzE8d5H6Sja0sMf/FQT0dw+aOilom7LYseVVZ1HgqFI1Szc+wN bJLKrVa59oW6cGhuPBUzneF3vxk9SVfm3rcgm8KMyR1KciDIJOvDTgWRDNdaureF/w mSBDNNB25bnIA== From: Miguel Ojeda 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 v1 12/28] rust: alloc: add `RawVec::try_with_capacity_in()` constructor Date: Thu, 10 Nov 2022 17:41:24 +0100 Message-Id: <20221110164152.26136-13-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128243291210816?= X-GMAIL-MSGID: =?utf-8?q?1749128243291210816?= 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. Signed-off-by: Miguel Ojeda Reviewed-by: Gary Guo --- 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 Thu Nov 10 16:41:25 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18214 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp251899wru; Thu, 10 Nov 2022 08:44:54 -0800 (PST) X-Google-Smtp-Source: AMsMyM4Y8fjPFcCcFNWTTi2O/eE+1FVnJhR6eb+k6/knSCBAu0IpVx8s2BpoDt6zNFBGIdQDO0hB X-Received: by 2002:a17:907:3e88:b0:78d:b3f0:b5c0 with SMTP id hs8-20020a1709073e8800b0078db3f0b5c0mr3253814ejc.141.1668098694154; Thu, 10 Nov 2022 08:44:54 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098694; cv=none; d=google.com; s=arc-20160816; b=qG770LrwxAGjZ9Iy99lipzZn4xnX4ZiMwPatSWl0CTfYlvMSGBNcrt8BxS+gOxzm38 4ZnZjft/bx7kwvuZ2ATxWtUI5JLTwbgbPwBc3TobJv0O7mxKle4ghc73EaquHN5r0zi3 VbbzcoNKfPtuaWjiMbsVAQ/8wTlEKD/DYdP84llEYvLsbvUfCeaGFpMpxMGsICj4Yd9S xLKnKWVETbel9vh5Kyt8z+VA5i28vdL2qK8z4t5LY/wVMvBIsc4HWnV0vGr646npJNe3 Si+tEzGxvFCa6QPC3DlLKy4gWEDcUmDMox2AKm0f5M/1/81Oxi7N65cbYH93r0yUZW1h 4SuA== 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=fWoofikj69iRbd4Mfwg7Z519A3E0rOj80lwqfIbn7js=; b=JaKH9LTrmbT10DmvYaHKtAClODYq6T4cTdgDNpKGhW6zbViDukegw217AEGDcEz8Vq dJeBz9VHymQhz5QAw+FD9OIGB4DypbLj2Gr9tdpLARmH0+IwHyed2rILvs0iWuTtqlhX ULXMEjTNNQCexENlpeJQuib+I9hDsiDN1CbjwWM8lzpDY9oqjawh2Xu/NJ9yMdmNvNA2 XRXtXz2K3pkWxuo8aGxB4pZ9p9GxLOpzSP+tDwqFw8C3l2m48Mb1UvBG4QmJPCh8FQfa Gsf0yAWympKTCZjzps0bw3JfbEU+bCa8j4548INL7Z1vWf44cU/ZphrnC89Y0658Oein +4Wg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=s791YN2U; 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 nd18-20020a170907629200b007ae417013desi21609407ejc.324.2022.11.10.08.44.30; Thu, 10 Nov 2022 08:44:54 -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=s791YN2U; 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 S232363AbiKJQoB (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:01 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:39928 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232099AbiKJQn0 (ORCPT ); Thu, 10 Nov 2022 11:43:26 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 3A4294385A; Thu, 10 Nov 2022 08:43: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 DA077B82251; Thu, 10 Nov 2022 16:42:58 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 88272C433B5; Thu, 10 Nov 2022 16:42:55 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098577; bh=BvwkwmrbZC14+/ZpCX1HQjoc2T2Qpowc2X8TOjeQukE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=s791YN2UzC8dhtmjVNGRnI0TlhTl/C5cNWs9GU+8N/CMDuw3sUQPrw+9/ee8KnDtq mMSuLzJmPNMiWBRTYbSSUnXLCQtLRoUuEzrO37LiXy6Z+M49S03NLaWfgpqAJ7dGgh dz2Acl6UXWkPAqNeWejXTcFL7NAtRPti3g/PN416jMnL3g1Rn9bUr1iNCNtNk75HvL US1JOiBnvbEJyP/Vb3XpgeL+fhv1QMd+DnvrRhSZK2lAZ9k5r+TB8pxuyMoaHQ2Woe Sm2g/YYENLlz4ojLxVqaov38JdbUKh3LWPonkNSR3EhKCJynHtCFy/KZXLarJN7zvE UL4DCRGqp3CFw== From: Miguel Ojeda 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 v1 13/28] rust: alloc: add `Vec::try_with_capacity{,_in}()` constructors Date: Thu, 10 Nov 2022 17:41:25 +0100 Message-Id: <20221110164152.26136-14-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128256266645713?= X-GMAIL-MSGID: =?utf-8?q?1749128256266645713?= 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. Signed-off-by: Miguel Ojeda Reviewed-by: Gary Guo --- 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 Thu Nov 10 16:41:26 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18215 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp252002wru; Thu, 10 Nov 2022 08:45:06 -0800 (PST) X-Google-Smtp-Source: AMsMyM4cOoWuy5I9QI66UB15odUhVcCMTEdWtY7+7rQi/zOu0OqfJSRy05bF0L8nbzCxEVKlyPtW X-Received: by 2002:a17:907:a429:b0:7a6:a48b:5e52 with SMTP id sg41-20020a170907a42900b007a6a48b5e52mr58814222ejc.411.1668098706381; Thu, 10 Nov 2022 08:45:06 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098706; cv=none; d=google.com; s=arc-20160816; b=sKbUsaYcnIBT5M1psuQOAcn4NeFaVqblkEt8uGIsloRwTs67WBL9X1hiuHFaKpFpL2 7OCQujanKkfONg1d4/9fogFtAic7PFSTaBFBCg6owEp87Dzsepm4NcvAYDs1a8QxZcHs Vg5GVC6OELON3UQitf0jWWI2VpzmgEF9HkTfxx71Eoj2Zy2KIXb/mft9rSxGfZLb7ely OBFmDhxoUtVpJ3uyW3HAeAmiV2qFyUkTSc+VErWtJI0qDkBGmfv6PKW5b8scKc9tOKIn 18jgYGtvhBigcrM8oweOrmhdA4wb644MtuQ4MrENnMWjuMwu7+NZBri4obJhimO3vsJc VT+Q== 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=ttvujd7A8/pVe0CnZocPvGoni7Q1Gmk+N0iZy8e/uo0gU6xMom93NPyAdJIPyhxJhN 1aJ90t8G3emg54TIbiZLWMzygBogy2u6CakN6IiGdkhOiuzgFKkWkvwH4j9PgEejbLz6 jZVFbQzQicv+Arilf3ClVzbFsMwkq/MYVn0FLTxBPkQr+LJUMIzR+cuok0KHT4tdI4lR YvQPG7Iqu2Wy9z5JjwHbXFRTHExU/1S+WGE8C1TpwgdI8BqUwqwtGFPTlk7nNqXhUvy1 zS3WemuQ6CiAZyRGSKEBPlDIM/7mZM7op6Yzvfo1g+c6+13cOXe27hRpaIdDGO80g7pw eceQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=V1fkxyBu; 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 cs17-20020a170906dc9100b007ae86742c3bsi6680825ejc.1009.2022.11.10.08.44.41; Thu, 10 Nov 2022 08:45:06 -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=V1fkxyBu; 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 S232471AbiKJQoE (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:04 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40726 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232351AbiKJQn1 (ORCPT ); Thu, 10 Nov 2022 11:43:27 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 4A58E43AE2; Thu, 10 Nov 2022 08:43:01 -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 DAF0C61BCB; Thu, 10 Nov 2022 16:43:00 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 678EEC433D7; Thu, 10 Nov 2022 16:42:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098580; bh=H8GrOu07IRuGrUGFNBmi30U0LGPQsGBzhM2gPsNjUkU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=V1fkxyBuVKLqkXCwarbt2nzk2Gmd07/5IZb172x8K6Iy7ZZK0piYHQxGtjJCvFZ8q Egl+ANyi1jtSNOuoAVyMVUn7rSeKu62QUS8uG1yNeqdQ+kDrAWvp82GYOJx0YHKWck lr/e+VWXG4RC7ejtRrDSGpYfNpXSBwAGrMQg7Bnb5C0xO19VpGmFTymLBid3wrPtx/ ZXk7aIs44xhFG4QWSt7kCoxPk9WwPBVZH9uM2K7i/1GcZ2hLuUh1wMR/+dmHhCwbMo F+z3N+/Vf2dX4jP31xl7zMAda7Tv7tuUDo4lJ4/4IG64eaxObhRxbFOYk8xUTftZA2 9AvF7s5SKzNWQ== From: Miguel Ojeda 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 v1 14/28] rust: str: add `BStr` type Date: Thu, 10 Nov 2022 17:41:26 +0100 Message-Id: <20221110164152.26136-15-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128268995024157?= X-GMAIL-MSGID: =?utf-8?q?1749128268995024157?= 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 Thu Nov 10 16:41:27 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18216 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp252120wru; Thu, 10 Nov 2022 08:45:20 -0800 (PST) X-Google-Smtp-Source: AMsMyM7DHDOwfLBQbmjDFuzeQxF6sdTUDZrGo556s/RKG+v5LazWrC1Ez9yfm+f1ePNTXySlM/fw X-Received: by 2002:a05:6402:11cc:b0:462:76cd:1215 with SMTP id j12-20020a05640211cc00b0046276cd1215mr62641242edw.318.1668098720602; Thu, 10 Nov 2022 08:45:20 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098720; cv=none; d=google.com; s=arc-20160816; b=YPXAL+5lxsb7Vjywn66SGfPEZiJ+vfdgkhBKiUEte5YIFPp4rHdPY0DeSS1HMH72VU dXD64ZLrgCuizdjep3w1BCqQNNatlbNo5WzZBcdK3qFR1G9/0TmC2KJ0rQgFmutdXXSL tKjJnAJPPQslydYftqwvW+c5myCiHV9/yzLrh1w5UkTgpMW4bkH9GujVa7gyNM4uuJZ4 Fg4m7esAPjBEuANPfxle2/IA+IZmR6XLFdwf/0u30k8+OIb5RAq0iUu9loCLEtlWy2fI 9gdPkPCc6PKKmUbc3OE+/+IowUGs6v8xoQU4/7YG9F0xbA+APDT3x7pTD9Ja+npQI1q6 fibA== 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=Y/ZF8bLKWHPYtveaS6Y0cANfG6yph5TFLQX52D7J9R9+Xy+mPEez1eCN9K7ESlxEMk 9zo730ZeFaUWSA2PvG76qlL0CCFVwjUjLcgAyejkgQcuOzr4GvFjiJf44Ej+a7Gcdev+ NlTHP9Ym6F4jQLPhB0mqish1TjQMcQ7JyTjxi0oWjmkpR3SPehGQ5IYzOoC23z7XupyQ wi8dxJvezNoQNqTa19gX0kmlPheOkR9j6k/7LK/yA8DVzFhDz43a9mzjf2dJ89E/ulcH WqDnDvgGIZUs+j5R/vli6BKVoij07YDzfjgr7hfSGCva6DksEjGvrJu6iNRNxtvql02b b0Ig== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=KQn3g9qg; 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 i2-20020a056402054200b0045d03c18e5bsi19086edx.560.2022.11.10.08.44.56; Thu, 10 Nov 2022 08:45:20 -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=KQn3g9qg; 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 S232483AbiKJQoG (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:06 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40052 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232209AbiKJQn3 (ORCPT ); Thu, 10 Nov 2022 11:43:29 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id C184A45EE3; Thu, 10 Nov 2022 08:43:05 -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 6DB33B82251; Thu, 10 Nov 2022 16:43:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1C2AAC433B5; Thu, 10 Nov 2022 16:43:00 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098583; bh=Pqv7nrnSw/i2nkLoHhZe36xor+0aWZ+RAfK3x5lb5qk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KQn3g9qgwmBkJ3Wnm9vxu2L3S8bIXyFNlEQYHy0tMIwN5QBj06PvJhG4rpm0GpuEB GLZQFqXmFCsWDvzpYXSnEZxwbmW+nz0dbZgfnHLjqmA+H2VYUxCELTkC/mq1yAEVIk sY/IcDdQAIBb/RKTHzX5Ii2HbHpIjSBRIARMOPRaC2bm0XUncJ7go5zYE+xD8YA/w8 K5haTcYQCzGir4ppjj/ehtE3OySb7CFv5p5m8QS+W8wpnIs78z1cQnh1grp3YiQqRG eKeTVeJx6ov9zDF/6cRSau+xC4Sbxxl5cO4ULDLG2dzc2WxQVmJCToVNpobyP4ds3v fpLwbnifHBhbA== From: Miguel Ojeda 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 v1 15/28] rust: str: add `b_str!` macro Date: Thu, 10 Nov 2022 17:41:27 +0100 Message-Id: <20221110164152.26136-16-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128283697197136?= X-GMAIL-MSGID: =?utf-8?q?1749128283697197136?= 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 Thu Nov 10 16:41:28 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18218 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp252311wru; Thu, 10 Nov 2022 08:45:40 -0800 (PST) X-Google-Smtp-Source: AMsMyM4rZkVZ8cZ13v5QPsAmdSjO3lDSQaCIznuIMfek8qx6NxC3K/Lggkt4Rk1xCLH9B3S+WZZg X-Received: by 2002:aa7:c14b:0:b0:461:c47d:48cf with SMTP id r11-20020aa7c14b000000b00461c47d48cfmr61397790edp.83.1668098740759; Thu, 10 Nov 2022 08:45:40 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098740; cv=none; d=google.com; s=arc-20160816; b=teTO9p++NC5K+x/SxlyCjLS23xMubBkKOqCEEgpKxhekXFKgB/pOUyy4GRSLZhwcBs CpNDLE9c17m+P9+MFX+1dI+3TI6GydNzz9G/XVCD1n2tAReSobZ8hSv937VWM86qNivj MrqoHtTT2YMiSauLH0WwbqV2jBSRDpq/shchjF2n1jQN1KE1MEILDNyIFlPidin62C52 tJPHPKtj+Ne4LUboXMaMt9WNssHRhWLs5R2XeR4QvqbcxEbBDanlcC1sGofnd/fNkaFN TYCv7Vxw3E6M0jnFG86GrSisrnTtwnOXY8D4NRCxcgR6rIJNkBSuE/tCI0sYuUdTHDZH pwJA== 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=Q6vyPIIuHxB+VRWMFf9D6X0Eg7tKukd4akU0EdSPDAvhdS06nX1qL8uaa1qjvFufGn /73hu5NUeMscRHtlG1yd7z+oskNH2b/9BAP6WdCV5HlRKl3QDAI3+x5OlxQAYR8AqN07 edN0h2aSZ8lvG3sRfE9blvs/S9YypOQu0KKvndk6eSX1JJM8kxpPGBBYfSgiG+AA63+g PVwjWP6nuEunyr3at7zrP8JxHpeWwsixmJEqCpsgsEWn6ZarU/RwYhIfeZziRzyIjPkT 2p7f9+kZgocBeh5yIN7T0nExmgH3sW94ix9vshhNC+VsHZl7vPX526W+ygK080J6arpM dKzg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=l91c9Vzv; 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 sc8-20020a1709078a0800b007ae86742c20si6765930ejc.282.2022.11.10.08.45.12; Thu, 10 Nov 2022 08:45:40 -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=l91c9Vzv; 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 S232277AbiKJQoS (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:18 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40060 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232373AbiKJQnb (ORCPT ); Thu, 10 Nov 2022 11:43:31 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 4BEF045EFF; Thu, 10 Nov 2022 08:43: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 D91E760E75; Thu, 10 Nov 2022 16:43:06 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 14143C433D7; Thu, 10 Nov 2022 16:43:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098586; bh=JUlBWWC3mMeuYO9e7TQWTKj0jrpvH43QY5gJsfCQcio=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=l91c9VzvwUfPRWQ/5oYRmYOEZYEGPOs+6lKTCG0JBFfHlrVMwP0BBia1scemi5Iqf 59GVrJAxhXxeAojfncKkdLn4vHxghsRx5CgqR8mqxfy9a6nC5++CSruYW6j8oWvDAF Xa6glWaXbztW7ONXVZHICeMKiIBIDU5+OyoRXK8enihvl094nEDy0NHP82Uo/DbmL+ CR/9KrhMbUVcIBqjYgSv6KxOHifWOHiCsacri6hj2XsyqDKMVXgqGsEZ/hcRd42eO7 HRBsA1dmO3VX1cmKR45XLa8YMNr6b4SqxF85Uxl933gcBnoqnSUAWvqnbgYCyXAm8h 5L99GCO8s7QfQ== From: Miguel Ojeda 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 v1 16/28] rust: str: add `CStr` type Date: Thu, 10 Nov 2022 17:41:28 +0100 Message-Id: <20221110164152.26136-17-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128305572008048?= X-GMAIL-MSGID: =?utf-8?q?1749128305572008048?= 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 Thu Nov 10 16:41:29 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18217 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp252140wru; Thu, 10 Nov 2022 08:45:23 -0800 (PST) X-Google-Smtp-Source: AMsMyM7S4VYj3yBPdtk2yETNWISJKHcj6jaEh7eUePlagqEWYEppBP6SEgndW/bmA2wHKOVJ8DBs X-Received: by 2002:a17:906:d9ce:b0:78d:dddb:3974 with SMTP id qk14-20020a170906d9ce00b0078ddddb3974mr3090753ejb.411.1668098722940; Thu, 10 Nov 2022 08:45:22 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098722; cv=none; d=google.com; s=arc-20160816; b=ggjFlg0sLEFsHDfyvlhRQC78qhkxB3lzU9ij1JImeu+ux+johhAON7mpLQfacPBq6o DpYr+BnVbOahE/L3x9N+oAnWgl7s7J6MIOwBtI7mTk+oi570lefGl389Amdk9T1o4cyp vUTpDIvY+oXDtz55qekD1FcJvUFDIdWtPWdmi9jlT8h+rRXRIBFkCDdRQCjHMXegIjFC l0ZJjDIWDp90NkrAy9fBdixhnARhvTBFQDHL0LaU+NU3ddxPCRge1rg98C8PhBwyWsmP 8jet6/X/2+eJHPpJDWbTZTwpqIeotcse5EmPE0yR71NjFCYGh446BQU6FxQeNHzPE9Ca 1AeA== 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=En31/ZXU9gfC1Z2+2yeXjcgAcL8kyv1LkvNdpgRL05hg9B9xJGSHbrnoVso+ff6vPY P0Z3vTIGLmoJhrqgRU4MXvcRjrrKgwvkcLOeJhAtcSWGKk2wn6CW8n7577YNhTpH/oYq YE9ti15rQ6uKWAfqioUIA7sXwXKEMNuMSqrtiLCtWFV+yfuDxBLHz5Fau3+Vg3JwxZnp T55KcWXRL/hdjbQjnzV9MA+6tY/7ZeNcfz69Hgo/exiV4XsURL9m7XSWQOhXXjVXpU85 WSPf20mSYOQtgzbJ3W2egE/shwhBfcicmVR9LmvbkWK6fyzmqJP1BMaeh4MUhJxSje+/ DV6A== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=WXfn05iC; 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 cs17-20020a170906dc9100b007ae86742c3bsi6681601ejc.1009.2022.11.10.08.44.58; Thu, 10 Nov 2022 08:45: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=WXfn05iC; 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 S232507AbiKJQoQ (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:16 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40056 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232229AbiKJQnb (ORCPT ); Thu, 10 Nov 2022 11:43:31 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 518064384D; Thu, 10 Nov 2022 08:43:10 -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 E2D8560C3C; Thu, 10 Nov 2022 16:43:09 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 20A19C433C1; Thu, 10 Nov 2022 16:43:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098589; bh=lSrHt+F2Ze+/0shcXyGqT2iYHkhHUzJS18BpgwZFKfQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=WXfn05iCKkaThQThCXeKWEliWM8sYgdfDebypjfYb7zVgGuFoYbQC0a9EXewcfKeM u1FwVCtDj7pABLT8E+A9RmwU1fg1dCOtsxDfD/9PVLaCScNel7NS0s/0/wfJeHXF/1 KMaM7KmBO4fwh0PCgDYgJCLG+qPhmpBACcfnPEQc4ndGdA29MBi4FYx6t3rDHhV9ba utPqEiLMNvDmlJvS2KIyAZwP8FJzQJofuk1yjJYo7u9NL44ikmQQnLSV7ipciu9EwX GrF7h4ljSCT/DwahFTNF1UfB+o4pblBGXx5RLhD27EzfsAnLsiFrmfkX/NkN2bGCgS 3usHAuTFJ3/wg== From: Miguel Ojeda 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 v1 17/28] rust: str: implement several traits for `CStr` Date: Thu, 10 Nov 2022 17:41:29 +0100 Message-Id: <20221110164152.26136-18-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128286885538019?= X-GMAIL-MSGID: =?utf-8?q?1749128286885538019?= 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 Thu Nov 10 16:41:30 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18219 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp252378wru; Thu, 10 Nov 2022 08:45:48 -0800 (PST) X-Google-Smtp-Source: AMsMyM6r8HAjYNbQPsmxwumxmW13k2pGcOtahQ0AQjCTOFiQfJJl1ayxiyJsl6SknJ8RkxFChJ5f X-Received: by 2002:aa7:c047:0:b0:461:5917:bd3a with SMTP id k7-20020aa7c047000000b004615917bd3amr2740984edo.146.1668098748542; Thu, 10 Nov 2022 08:45:48 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098748; cv=none; d=google.com; s=arc-20160816; b=xlGJA7W1d+iFPBFckO9LESeH9H0a7WJ3IPbBRr+M92PBf/2UFXiH+peRLshEtZ+xSj bt/tDsEIKsk16Dae3w+L4jn34w60j2s7o7FhzDV/CCq5H3O4V1t+Mvfl873FY8Bw+Ehq y2qf8AkFK5LveragnX6BN7IM2htX8y8rlPV1jxhVcKEU5EpSzEPfCXlM3pixJv7gfT2v DFT+ahFuUVgZO1yd72FxqwNRtZ4YIdgTt5Izv0rD4SXKC2+VhJ6McsQ/yyEYNKmomGiL KLBvFwtzBRKPZ0runO3sTcJlqR+5cgPunqU382tnkArOslmI61EeTT7nTYEs6RPapsw5 rAcA== 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=mkQD1CMyBB73zTsvHjdpf3B0NeYSC1ZF5/jQiGZEUX1HqJhPlf5zFMUpAXPP/DGqBf PSA9oAYIi09sh2bSqwKSrGoq6JqYF2WxBhHxSq+2eUrI5lgPeGWixFwfJ5VZSKhCNlLM 8E0XkzOGArVHqCVdgyob/vSZPC0dZX5oulWJdL257Ldvi/zm+O2NoKF8rRdl/VKVlbwW TGtm1k7Bf2bp5T87+d2+6tHarU5qYuhD6QhqQIc6hMep+gW/h6khEA/qBpV+CpGfBuKw OpIZxXQE5n6QggJsWSESEjojewC+hhzQArqEXbaVze8mD/A2Mys0OjBaigjmo27T8Mqv 6cwA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=q9PPYY1R; 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 n11-20020aa7c78b000000b0045a0e39062esi98614eds.76.2022.11.10.08.45.20; Thu, 10 Nov 2022 08:45:48 -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=q9PPYY1R; 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 S232527AbiKJQoW (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:22 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40950 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232384AbiKJQni (ORCPT ); Thu, 10 Nov 2022 11:43:38 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 5C91C45090; Thu, 10 Nov 2022 08:43:13 -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 ECA5261BD9; Thu, 10 Nov 2022 16:43:12 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2831AC433B5; Thu, 10 Nov 2022 16:43:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098592; bh=McON9F/ZloZh668lpPUE38B16LOD0pkq/6vZiAe96vI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=q9PPYY1RDgJiOgY/j1c3gLqlW1NCi+Y11qnDMQHXS+tqtbOuG/Ny56LlRF7+NwNnB 9Y/lhcdYdOiv+uiVlkW9HWFhyfxJIlmxwlJmDK+2V8AGbt5TdWRtZXumE1qkOGtsdb tawjy5DCiUrEGcCnVjRUSgyL3zFL7l+yTA8i/wjzG4CAM7H5tJMMi6Mkph182Nyf9w C5zxzTSteoJtEOtbPiPSDC7NCl1TJ/O/ucRBFtii1TWmL0YtDpsXuNeTg5h9InIMyg y//I7SkZSGS9P304qTlJroPkvhPixeHCVtQ5A1JUpZCOX9v5FxNVUsIR0YqHFCtsxI +VfABN/suQgVw== From: Miguel Ojeda 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 v1 18/28] rust: str: add `CStr` unit tests Date: Thu, 10 Nov 2022 17:41:30 +0100 Message-Id: <20221110164152.26136-19-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128313661895468?= X-GMAIL-MSGID: =?utf-8?q?1749128313661895468?= 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 Thu Nov 10 16:41:31 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18220 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp252416wru; Thu, 10 Nov 2022 08:45:53 -0800 (PST) X-Google-Smtp-Source: AA0mqf537ln7+ogxK3U1+/xjm0hP+kTG9oUDLUdHMiVozncMporgrXEMg2dLPd4JKX75Y4Mcuutf X-Received: by 2002:a17:906:c839:b0:7ae:b2e3:ce15 with SMTP id dd25-20020a170906c83900b007aeb2e3ce15mr631298ejb.136.1668098753400; Thu, 10 Nov 2022 08:45:53 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098753; cv=none; d=google.com; s=arc-20160816; b=wcX6a74mO8Qm7/v40kG+sgevl5qCf+llbNNW4AJLfnn0aTIOGqqk3FW6nq7ij3v8zA xyjM4NMPsm/HchyfS+rnM6Nzuy9h2rNiQnm2hpYwbF9PCIBkafkoArSFIGJND1v70PW9 Q15rbBsNgxk/Dk4Pec7PhfmIvrUVS6TU+l8dfTRuB4PYf3e5UDlUV86/1Y9K4UMyae9B ZAmHqNiS/iatJp+1OIsdCeTEqeAEOBd3hyFzjS8oZmhPd59fTh89xJbBlGn2W022iY0C DOF/pnCwq4x8/fqMn7fsrrufxiu/okCHeiBUJhHA8QdrzK9bNeYvkJJIOtcniRMTHheL j1bw== 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=vEXAk2WWdrEr5V41nwmE+vwwllebZCHywQ6twWLMjCE=; b=Y6u0TAgBJQbC67O3LE19vGX+JJtEkq9XTK//wPoK9Af55EvpXsImTkIqf6Z/BjyBHo p8+n98XNuuI+Rg85yX1cf4NdxR/s+YF1jjhxeLnGWH9vO6xq035rbfX82F3h1EE/t+6U fSkiClwJf3qJHdKHtvOP6nGbszicr6HY4cv4JhuYPpNV1yu6t+8An4+C7rhXPbE3qVlo Fhl0vp9tDiIkb3TBq2bbjy/1RCHvzm56C6ggyMcYVwkWAUo8PaXs+YV8nmpXFFEGmYnM +5HeFEsUVKEcdzuE6uAw+LKrSS3kH34gyqW6wMeSBSTMdcY65kqOlAg7Aj/0zmAxNblu kX5g== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=CadoW2qB; 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 x7-20020a05640226c700b004520e27e5b9si18712edd.626.2022.11.10.08.45.29; Thu, 10 Nov 2022 08:45: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=CadoW2qB; 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 S232324AbiKJQo3 (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:29 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:41008 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232308AbiKJQnz (ORCPT ); Thu, 10 Nov 2022 11:43:55 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 2AF8847312; Thu, 10 Nov 2022 08:43:17 -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 8B44DB82251; Thu, 10 Nov 2022 16:43:16 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 362CAC433D6; Thu, 10 Nov 2022 16:43:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098595; bh=bTwV3nkr6jPDZcA7hO2dJXGMLx9sZQV043G74OSH4H0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=CadoW2qBa6bNQMyp1nnAz/fKRxL9PT6Cjyz4lVonGscW0FXbELPIh151r/bpTZLX0 RNBGpEae5EeDzpOjPC/lFxm/X6VPej6rwjFjK/TaJOCaNEXZ0jFlLbaFPm9LxgnORm uK6QlIAdByyC1uohiB+V3QQ/ch52eA5RRBBq4PHpLLDPVcrDgDVBcwBaod1F2V71v8 b7i8y6F1+iKuiSPcH9IjuBo3kRwpV4TJEVJYuWJ/T9fQNrk4BEQPnomVI4rHV7K/k+ sC16wilA/IOLzQ6c7yZUqcRsX5a1u2QcVF/sjIQuDByyUbd8CgZ8SFCbo5L9Hf53wh CYzN6evp+pGOA== From: Miguel Ojeda 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 v1 19/28] rust: str: add `c_str!` macro Date: Thu, 10 Nov 2022 17:41:31 +0100 Message-Id: <20221110164152.26136-20-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128318235681985?= X-GMAIL-MSGID: =?utf-8?q?1749128318235681985?= 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 | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 3ed685cb5a3c..3fb73b888dce 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -128,6 +128,18 @@ impl CStr { Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) }) } + /// Creates a [`CStr`] from a `[u8]`, panic if input is not valid. + /// + /// This function is only meant to be used by `c_str!` macro, so + /// crates using `c_str!` macro don't have to enable `const_panic` feature. + #[doc(hidden)] + pub const fn from_bytes_with_nul_unwrap(bytes: &[u8]) -> &Self { + match Self::from_bytes_with_nul(bytes) { + Ok(v) => v, + Err(_) => panic!("string contains interior NUL"), + } + } + /// Creates a [`CStr`] from a `[u8]` without performing any additional /// checks. /// @@ -321,6 +333,26 @@ 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 = $crate::str::CStr::from_bytes_with_nul_unwrap(S.as_bytes()); + C + }}; +} + #[cfg(test)] mod tests { use super::*; From patchwork Thu Nov 10 16:41: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: 18221 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp252428wru; Thu, 10 Nov 2022 08:45:55 -0800 (PST) X-Google-Smtp-Source: AMsMyM6w85KB8xX6NxMgrHuv9F0BS/lyG8+i3p4b9aVvG7hI7bj0wkU2RTGQQfgtkjS90hEbp5eF X-Received: by 2002:a05:6402:1203:b0:461:a09b:aaf2 with SMTP id c3-20020a056402120300b00461a09baaf2mr2595595edw.328.1668098755635; Thu, 10 Nov 2022 08:45:55 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098755; cv=none; d=google.com; s=arc-20160816; b=ahJpU4eDjwrzsR01AdeF9y50EaAfDGXUhjneITCRNX0zJO0w3cRb8Hv6RwlfZ4Qfxu 0alH0eOpyo2lsnlV9ptZLr2/wuIekc/ZkBNUPU27Jz5/TbukBW1gcN4FgJdUpZWqv1Um RkliGWTZ/hq4BmqquKOsCb75+aVwz+obVX/caQ7k6PvnIf+wtNz2BadC9uCd/tLzmR3n +87GI88wmXk1pM58KVfWni+wfuqFzK3pVr5IOtqztv+v/W3MAsUbUTzEc41YYPIlUsuL rRs2b9UqLSNewWu5xxUBlpD3EPe6nrrpaT3awItapFCuvYiM5bUakQ+eoeNuShpUtM8T 4OwQ== 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=sSYGagKDke4dSn3ed5xnAjLUnlKza3VZtpfsA97909I=; b=S+dwCr47ZTpv1ZaD8wRzmYKoR/NH8CgwnXEiktGQQhLlK8aJvPT4bAED7xFX+yxWcn AU/ucFGPhdbfhfwBfMlgXtWHx4/L+t0sZJWUOjyCjFAeI9iZIwaSNzGDg9alktvu2BLi hcjmGCVQ6Tot+C9dlapiV+rtzx/S4ULbBx/Vme2PDFT+HjWYWqTnaujJ8u9C7dPYw2Mw Zu3vXxZ4LSrPQeb2vr3poerYZcnMfeA/hRXYy6EL1aGUMkk3k23thJXyH9cxvqryYEbd NZiHqDh/JNiglXAjiuGGxcf1tKeQTv+CXjCRnmHREVAFUUEJVnXU5ZP3jL+2XICpWmHC KUtQ== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=JLFepvqh; 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 z14-20020a056402274e00b004667ef1bc6csi114388edd.14.2022.11.10.08.45.31; Thu, 10 Nov 2022 08:45:55 -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=JLFepvqh; 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 S232557AbiKJQoj (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:39 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40200 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232343AbiKJQn5 (ORCPT ); Thu, 10 Nov 2022 11:43:57 -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 E3DFB47321; Thu, 10 Nov 2022 08:43:20 -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 9539FB82258; Thu, 10 Nov 2022 16:43:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0D687C433C1; Thu, 10 Nov 2022 16:43:15 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098598; bh=Z3Poal8/0sehEb7NLOgdH3l5JP1/vq7TUA9vjjBRHIM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=JLFepvqhskfPiO9iSLzm0an7+SN+UMlAWx99yK/eHXyeVW2bZmLa5cfif0sVu9kbw WFqYdTyDbQ85XqNWhZzwuvnRhBUEZWWEefvXDU6kFv3/RChF+U/SikwzuntqV6qJlK e3zLr3B0QjaCQ9YRnHDZMm/0/rr1dhUtM6KG58Y3LD3Cv0knc0j8mKtQMq3Kosb8/5 0vrXxNLcocW5m4rz3TLhiJXIBGneTrap2b2acp+O5K73KzyfRQUZ/tjzWe65CPqWsV 5hztVAqrW3FioMbMiXR26ZeWvUvTcu7k7SstTfGM0j0ltAMEgXqNFRIDgYCKke6Jl0 s/IFAJzVZ/DqQ== From: Miguel Ojeda 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 v1 20/28] rust: str: add `Formatter` type Date: Thu, 10 Nov 2022 17:41:32 +0100 Message-Id: <20221110164152.26136-21-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128320784671721?= X-GMAIL-MSGID: =?utf-8?q?1749128320784671721?= 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 [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Gary Guo --- rust/kernel/str.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 3fb73b888dce..db6473db31c6 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -415,6 +415,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. @@ -448,3 +465,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 Thu Nov 10 16:41: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: 18222 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp252498wru; Thu, 10 Nov 2022 08:46:05 -0800 (PST) X-Google-Smtp-Source: AMsMyM5mNckX8rCvNv/29B5KeA7Xy3OmU2uYxUgpLbtvGQDqyVU1jmXt7PMW4v5jXKLQXOgL23bn X-Received: by 2002:a17:907:2cea:b0:7a3:4ebe:5eb with SMTP id hz10-20020a1709072cea00b007a34ebe05ebmr59455447ejc.228.1668098764968; Thu, 10 Nov 2022 08:46:04 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098764; cv=none; d=google.com; s=arc-20160816; b=QQqWtNB5ykZUh8tbQz6WbbYAh3WAjuW/1nheEoW5wA+9gVCmwsO2ozbU8N+BR/pf+H SH35ZYN2y4OarDyiqo9And6wOk2k3QtTiAUBdlUdk3qg4zCY1/ec5w3zBAiS6h/XTyj9 G1F5kexy5hz9XLLhwzM+/kuk6c+Urs7v0UTAB8yJmg/9JbcbKpiMWMS9wbzzyAqcKFat Bw5LU5fGv6TcLd67OdXSRrRd5B55R8ZH6tjtJhpCk1K2sJ+2Ggi0rmxgVn1aymmGsbJg /Y3GhDMJaZ+932L1pHBlIyvwulYTpSjcflDUWVxmI4jZsh5VHrLa2nqXBEkIf0V/nD0q aApQ== 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=45x0jnFLBTiFN1+7wzfknHGM+Zk+XwnFDi5gOyIlL2k=; b=QwdSZMqxWU5a6CTmErnDXlxSUhXhbIyLsu1f30XblUtPsgunhi+D65HDi034+r9M3E 66aBPNPV4jx/IwxOsYZy/7XAsLV55IeZLy4x9gnDtti6/mC7wIg1TA3/JVIkiB2QNFQp P/icE6IerNPly+veUz+RrQR6BMY7PEVbTnox1YHSoyjN3vxRewa8K2tdIaCsjuWcB8Am ItnaOM3M4h6JPtJHmnOh2MLvf5DNAe7KLG+Kdm5eWgX+hasi8GYIb8/VoWyG9HH9L8nl m9FtH+1Am9RmbffR3jcO5EMtBYBjHj4FzFidVVp5S9QPFZOxpN9zgniJFssAM7tloriT CE1g== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=HurCQzja; 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 cs13-20020a170906dc8d00b007a8a40e6146si18821114ejc.363.2022.11.10.08.45.39; Thu, 10 Nov 2022 08:46: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=HurCQzja; 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 S230195AbiKJQon (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:43 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40568 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232211AbiKJQoL (ORCPT ); Thu, 10 Nov 2022 11:44:11 -0500 Received: from ams.source.kernel.org (ams.source.kernel.org [145.40.68.75]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id DEFAF48742; Thu, 10 Nov 2022 08:43:23 -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 6A92FB8224F; Thu, 10 Nov 2022 16:43:22 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 24135C433D6; Thu, 10 Nov 2022 16:43:18 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098601; bh=VGz/Q7gY5LCscMIH+BUom4dYaRe94hPiAPnwG7cHlrU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HurCQzjaTx4LXSUf0fsQCh5zspRKv/suYkpVIO8l7dXLwUCfRBtmyoxFxLHqBTlEC tI3+A1Oh+VcLnNjO9B0fBuY+h4jiHHFXY0g2L4K3v+vsK3nQ3W92AgnWMTdK5I6IUb OL3jrf2ccL3+PtY/e/P3Pd1/KhImoVq+8SMLBYRSb1mDSm19ZMORxQihNNSfR/cS/i WjKbMwXa91am0kscJ0UQQwrL72rposHYxDuO2ZHtJDqKImrUvO/E9J9KjAOITc47xi wL3wJy0UQc9z2Of54UowHj6Hvx1RigamLh/dK5TL4h6bb7oVlsBUhpTsaPvKJ3pT5/ 4oClzLVvBIENw== From: Miguel Ojeda 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 v1 21/28] rust: str: add `CString` type Date: Thu, 10 Nov 2022 17:41:33 +0100 Message-Id: <20221110164152.26136-22-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128330829969467?= X-GMAIL-MSGID: =?utf-8?q?1749128330829969467?= 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 db6473db31c6..877148b77e71 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}; @@ -393,13 +394,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 @@ -438,6 +448,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 { @@ -478,7 +493,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) }) @@ -505,3 +519,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 Thu Nov 10 16:41:34 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18223 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp252503wru; Thu, 10 Nov 2022 08:46:06 -0800 (PST) X-Google-Smtp-Source: AMsMyM517c9ghDoGKrYf+JdYXACW9Qsa3RQ2LbwzkRgxth1/hMYI6ra9d0qdFYfkrOgxRmP2Fwyc X-Received: by 2002:aa7:d644:0:b0:457:2907:19e with SMTP id v4-20020aa7d644000000b004572907019emr2634347edr.111.1668098766046; Thu, 10 Nov 2022 08:46:06 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098766; cv=none; d=google.com; s=arc-20160816; b=vjtrVBM9VtpQGmLWWFP7YXT8EyCH1XY6L7L64KimW58KYrptnd+hnQ6p3liTtP29JQ U+WWCH8hJGAI3GB8lG4EZDsOtKPJRSqJ5InZ8TO6HHP/8BjhuHt1z5uv3BUWM+wMAWVv lZOoPiK8e7b1Kh29XhWLa6fHjR8lg1H7Sh+tf4kLh25EGhi/E4woxy94iRbbAZOtKSSq Hs+Krn2GYfdf9XA0KtP8YKROgpW/pWlfL5fG0awr32gei+treuedz+6GdyH1NchsDohm nhfYj3bNYJdH1EDWSg30TyShFpycGdUo266q5NDJIzfw5wlHkwNsykj3pkZYzAaTjrv1 c3Iw== 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=cqHcsgnZOKZZBs/V+M5lRsQokgkx4dee3bhdEX/GoLQ=; b=wDSfiBLFUvUyuxQ+8OKcKMNpwMoFlgHwKzekB3wbH2AprA2c0ByB7AWhEMpQ+H4YDW wWmWWvCJeyRav22g1iea2GMyluvOsDRCnMGBDQ9sPd0qCtve55NEZ6tdOFIszxXZK/L1 zI8LPw/jxEqK5L/IIT1wu600OoepY7+VKmLijfTXLnb9GHM4e0U8/lYz5inpfOEeAK1R uPncsqHIvn2sgLxjpibxawUCWBp6tDqCyTy4udG0dbMn60adSennt0r1g6CTKf8QeMl1 bY/ABnWiVJQ2fa1jVSpUfu/P+G2OgJQ/661Ao3L4fVyXXKRtC8vUcq/zwZlbGUbfDGad 6ltg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b="Yp/6XFlz"; 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 g8-20020a056402090800b004615d1d6b1dsi34532edz.502.2022.11.10.08.45.41; Thu, 10 Nov 2022 08:46:06 -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="Yp/6XFlz"; 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 S232509AbiKJQo4 (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:56 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40176 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232516AbiKJQoR (ORCPT ); Thu, 10 Nov 2022 11:44:17 -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 7295C450B4; Thu, 10 Nov 2022 08:43:26 -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 11C77B82251; Thu, 10 Nov 2022 16:43:25 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id DA8D4C433B5; Thu, 10 Nov 2022 16:43:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098603; bh=I3b0Z7RHs3m0QbSSsLLKwiQESMTWz+K564vWJV2JsjA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Yp/6XFlz+k04kCIlhS2B7ArlTF8uHXzFiMTnjRyUTjiwb4202IV8ifYnWqDb0mU+G yfICCMeY46vT+WeRhUyJuToCRSCPgt8qdqSJuizlKRzNeflPzGSyO/ZCEuIfhErpGM 0COeovEJQIyeGhyYcArZACHaQFby9VJdFW80t+7Lcmzb/3G0P4ocVCPY+V3gZ0u6y2 YorzeDzm32SzM8hpLKcB59M8689V8Pmgh2d7CpI6V67oa3UqYcuCAJXiY5/RQU7KM2 Vix8vowoVr8xSF7f1Ui7Ed8/AV7G7x/zteQ5HQSxeAqg5bTmc7Md0hsusR7qwG2E+1 FUW9QoBga1rQw== From: Miguel Ojeda 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 v1 22/28] rust: str: add `fmt!` macro Date: Thu, 10 Nov 2022 17:41:34 +0100 Message-Id: <20221110164152.26136-23-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128331493898326?= X-GMAIL-MSGID: =?utf-8?q?1749128331493898326?= 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 [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Gary Guo --- rust/kernel/str.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 877148b77e71..ffac633423db 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -592,3 +592,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 Thu Nov 10 16:41:35 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18224 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp253135wru; Thu, 10 Nov 2022 08:47:31 -0800 (PST) X-Google-Smtp-Source: AMsMyM5Ee8PTK0acVuYzSHGxoCvRkPUWLZB9yRtqh/q7rASdM8mCBrZWSjdxPzKTtyx20mYDyLJh X-Received: by 2002:a17:907:a608:b0:7ad:a198:3177 with SMTP id vt8-20020a170907a60800b007ada1983177mr3124420ejc.750.1668098851426; Thu, 10 Nov 2022 08:47:31 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098851; cv=none; d=google.com; s=arc-20160816; b=ppSbL4ZYTTpaVLisI/ezjMpye2BiC+I/xyaJe4Uk6KHQjEHVrTR1j5v4OAUN1zPY8f H34wKA/ltC6d4lowkP8Fav7jVdIzBjV1XK6F6zcrxw18hLEcoZJEWCDTdOliYt7zAWsW DiiwU5YnUEpYqhcNX32+jzPtnvo1dI18fqWlObkqs1c6JMjIi6jtXHKSRQYMo8pauIMI r3zZmhdCB5k+zc2O4MSeDMswJ6FqM5aFdP/gPY4Zc3g8qJche6NNc0Q3rYadxh8Vmr5f crVFc4s/Qve2+ew/MXYq0VZaZeeRrddlCpOKvd11PVnbHnNyve4JtpTzxaTIHANVURq8 3eDA== 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=n3NKeWNbg1SBhnqHCpLlUYtmsFGWeB0jN5sgd7OvX0w=; b=q013t8OTVmL081iwm+qAgCUbRnuNM5nRdf8L9c9qYRMXkKZcoLpDqjweOrns+MjQTz AkWsrB74OVefeA2G+MFCT9VmO4EinI8SXSqtiifIjOTexZfzlMH6yn9fc+ABy8SaxIuT kLfA8KzbVTiau6fW+iNF6/8PRBqE04a/YG3NzAgIS9W57FI1snyCa25e/kVzMu8CkGTY nUWly9tnshP8/9FmpZrdXOOXGBh6OjZzQ4D7gZlW583e4PKytSumBJ+md8nz0lxSWurm eHYuaJZmzdzr3noUGBTspRefazi6/XLiLwMXFhdIu73hj92SWwCRAJCZS2DdRY6R/hyg f4hg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=XbqXHj1y; 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 ss28-20020a170907c01c00b00787803711f9si16182534ejc.353.2022.11.10.08.47.01; Thu, 10 Nov 2022 08:47:31 -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=XbqXHj1y; 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 S229831AbiKJQo7 (ORCPT + 99 others); Thu, 10 Nov 2022 11:44:59 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:41038 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231946AbiKJQo1 (ORCPT ); Thu, 10 Nov 2022 11:44:27 -0500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 42D2645A13; Thu, 10 Nov 2022 08:43: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 BE08861BCD; Thu, 10 Nov 2022 16:43:27 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id E82D6C433D6; Thu, 10 Nov 2022 16:43:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098607; bh=HjvUpyGIW4BqiVc1eK1nOFEnywHRBja8WZXcNu1Xsro=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=XbqXHj1y/nG8jTYpN6CQsFzBrMf2VYre1h+DDfUNBWlXn0xh9HwX4enVcuzgSwiJ9 NeAGbnqEyXVxniRTOMBS4mjA1fKpwfAtAjhcnfafgTQ+sd8cdUglLp/DvhlKS0rzqc WmKybZLQBZzLmP9e9Ajnz00QypI2TSAHtEQAmwr1LqhKeBaEJkVfEoCYeAnJGu0HLI 5Ak+5waKF0+7jn89gsYFhfog0joLVY8hjIAL/++jCFkRVGz8l9opv0l7zMQmbcgOaZ z6jr61HANdh3rBZMXd9YT+kC/LmabXebx8M7at6qcgyVL9s/FHqsSxNhzFuk8BQH0y yt50rL5E0CYPA== From: Miguel Ojeda 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 v1 23/28] rust: std_vendor: add `dbg!` macro based on `std`'s one Date: Thu, 10 Nov 2022 17:41:35 +0100 Message-Id: <20221110164152.26136-24-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128421473573250?= X-GMAIL-MSGID: =?utf-8?q?1749128421473573250?= 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, using `pr_info!` instead of `eprintln!`, inside a new module called `std_vendor`. 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 | 160 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 163 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..da57b4e521f4 --- /dev/null +++ b/rust/kernel/std_vendor.rs @@ -0,0 +1,160 @@ +// 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 debugging tool and therefore you +/// should avoid having uses of it in version control for long periods +/// (other than in tests and similar). +/// +/// # 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 Thu Nov 10 16:41:36 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18225 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp253722wru; Thu, 10 Nov 2022 08:48:48 -0800 (PST) X-Google-Smtp-Source: AMsMyM6XgB+cDg547iN+5AC0myQenUXo8AU8dYXVRaHH90yzcgiYD5jjS991mb6CY9RDX3myXbE2 X-Received: by 2002:a05:6a00:23c9:b0:56c:9f62:3369 with SMTP id g9-20020a056a0023c900b0056c9f623369mr63738609pfc.22.1668098928156; Thu, 10 Nov 2022 08:48:48 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098928; cv=none; d=google.com; s=arc-20160816; b=CazaCgkdYIOqU5dBy3Qrt/JP+F2Cao4ZsnH/ha0JfE/7w/y27r6Gks1iCDPoEk7SWD WVd6KOGaR96SZA8Pp68uZP8qyf5xirc/hGOg/sk1P6PWLhQALcw/aQasY+orSV6gX1nl OTLJE1SGk7X30uZhjaVaIsPuNsz4SiHZj9FYpCjlR0uvhhoJq/34ikqCy6CYaVnAMOlu u5+tEuuuE4Web69WZ0quSdt2W8GzVHbmEa46S6juccjl0uETaxu2EZRpbQLzu/BVScHD PxR1tKBquIsn+K4tCS4KtvsnnDTDJ/1ou8n5puxuhhrHNvb/8wvTZWZ5S7sEURBkNbiH CPfg== 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=cpMPROnt17I0XhcytYVQ8mrRPasrp+0HmNjZCbV7+H8=; b=hg4PId90O8nE1iM+bbKfPhc0cWwedOosDsPNpvlA/c1KSXUr/EJ3SON75oH2hVuvRS jchYFauqa6ykANswytU+HZsOx/Ie9mAO/lV+MTdMxGG5Ck1iHVmT5nWFNLDAFYaTBfIf y5HQUC59UrM29dIWtJ4t3Qu3+FN+QMlxirMv3O+jw3ng3an+EWq/fkHrxQp7xH/hQYYW A/I2KZ29rNyTBTv2aEMr3Qa7jkjiJ0GhPpAiEwcQUkrePbee/CHzFDbZm0+S0RaekAU/ 0CRZLBSDwccVtkfm00OfbTSqNmjxVxQQUN8yj5Pt/ivHknyQcDBITRAEJ097TQ/3buyV jwwA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=cMjyLtNa; 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 o14-20020a056a00214e00b0056de69b0c76si17765563pfk.283.2022.11.10.08.48.30; Thu, 10 Nov 2022 08:48:48 -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=cMjyLtNa; 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 S232546AbiKJQpM (ORCPT + 99 others); Thu, 10 Nov 2022 11:45:12 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40208 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232140AbiKJQoh (ORCPT ); Thu, 10 Nov 2022 11:44:37 -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 C9718CFC; Thu, 10 Nov 2022 08:43: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 0004A61BD5; Thu, 10 Nov 2022 16:43:30 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5B550C433B5; Thu, 10 Nov 2022 16:43:28 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098610; bh=uX6/pkir0Xey7grEQ8c5/5PlojfkXX4KXlDb5cWi7gY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cMjyLtNaHUBK7dWmm62B3GEJtoez4W1kGeKCONcxIW4KI1Fr5ul0oNhPPT6QyLkMt /N9DSfUgnyLEUE9TVJhm3z9qxsqOsIV+V0lETiUplg/oOLpOPCNy5cnnOHUcL8PLda Glu2x4PrtYoVx5/I7L/0gZMPnzUA9oxVQngc0MRZYRYj8MaSDc6arELfBB64goFDYn KLFOd38XtLy1qaNTLx7SgwHd2usIS+uq8A/t/3yN/3DF1AKPSAnBdnJ6O5/FU8ez9m dAT++p5ProfJfhhISfzrkrr+B7im6pUHOogZnyxVKX+j8z/I+f2ApU9flmrb2/HPnW A1zfDRLtKAJPg== From: Miguel Ojeda 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 v1 24/28] rust: static_assert: add `static_assert!` macro Date: Thu, 10 Nov 2022 17:41:36 +0100 Message-Id: <20221110164152.26136-25-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128501951367417?= X-GMAIL-MSGID: =?utf-8?q?1749128501951367417?= 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 Thu Nov 10 16:41:37 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Miguel Ojeda X-Patchwork-Id: 18226 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp253780wru; Thu, 10 Nov 2022 08:48:55 -0800 (PST) X-Google-Smtp-Source: AMsMyM5V1U2/e6fgrwQfAjo/CUNdSXVKIQrHg1zat547+9No4vr7YZ4lu+nUjcI/DdFeLg6g2Lxw X-Received: by 2002:aa7:d694:0:b0:461:7638:bde5 with SMTP id d20-20020aa7d694000000b004617638bde5mr64154507edr.105.1668098935438; Thu, 10 Nov 2022 08:48:55 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098935; cv=none; d=google.com; s=arc-20160816; b=q+E83n7aSMgKhvgr2Jrg0R33F+Xv0bWSTGzKQfbaLvTiWNhCf/Hh6xrjzyX+W3rIvs s+KGSXs/YXBUB62V/5B48NLvUSWpVgpo8DzHfYraxCWneDEdR/4L0dzKRwOfAnCckALl ZsE8TOGfDohCEw9IjX+XyRZhaju/QB4GJg220YPHUqYkRrIpnG7Nb5lSPehx8BCladWo BXNEISjLl7jVeekmL4kvkExBhcPz/34YjsGUuAXFDoXsFTDq1NjaTXPukPGRjH9Tdw2f h+mjF0xKbKsUvky6+TzkINTkuT6M9bKCRQ5pXfzzBY08YBXJ4Bx3cQ0uhKnJW6FzE5nX zFdA== 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=ytSzA+9XlyrtdLjEflIVnNpDh9d356pgS3jlG7inOt8=; b=FuKGKbxTvegyJjEhHYUqUcAgskRWZQwtcYfMBhLRhwM/KJ0HsEXKGrE0ozNh6V1kJ2 wFT1jCNbbesVSvmn3I9oEFaFhtlDpCCYmENzaxYU9ANxpv3g6mhaKJh4IFnEQ5kNJ4Io W8/dHcP//FrkrjGlpfBlAjjVgernbWnNt36XY+7ehTMohQgrKNU3D38WTb7yPerrtixj TECCBi5yO4hx+2WDiBqAbcRUZteeivZo3z4du4WHs+8AdtdI0deuxFb+aypmhTbalYgq z8CS1izJrCkFpzPjjP29Ji+CmQMrcvUlMQjTHhBUyEa36bv29Z4DricHYtSYEjXdc/vh q8yA== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=KcZWT59D; 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 j10-20020a05640211ca00b004619453ac91si38831edw.499.2022.11.10.08.48.31; Thu, 10 Nov 2022 08:48:55 -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=KcZWT59D; 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 S231176AbiKJQpU (ORCPT + 99 others); Thu, 10 Nov 2022 11:45:20 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40568 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232209AbiKJQom (ORCPT ); Thu, 10 Nov 2022 11:44:42 -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 E29A0BDC; Thu, 10 Nov 2022 08:43: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 728D861BCD; Thu, 10 Nov 2022 16:43:34 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id CF050C433D6; Thu, 10 Nov 2022 16:43:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098613; bh=q1b+8RZULo3LQ8zfqDuXjlyaAk2LL+pi89RJyIKKyOM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KcZWT59DhU6X0r5e+tq/lKETZqJggaXdtsuQ9zutkzK2+7s+T5StUs+YzFvBnACGg ogTAKl6xIMpebuPXuCitVtNnY8VpWQxom9BtobATzy//M5CJ7ErFztIwV4oGqMPgqh heo2ndpyQmPtJSLGr9aZAT38CVilEe5JPglAcFaL4wZ6Ca6eR8znyC158lz98eDUxk 6qlX1EMZ2qUdsieAYqPfgQk7lsiX0a3OdvRgwjWDh8Yg9J5NaJncHEchEV1+biGbKu 4dTuoyolV77dcXBFGKkXoARnoq3JYG/tvK2O7qhiP0iAtZghZ8UUPsBOrEindsgtIf S7EeVmWJ2t9jg== From: Miguel Ojeda 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 v1 25/28] rust: add `build_error` crate Date: Thu, 10 Nov 2022 17:41:37 +0100 Message-Id: <20221110164152.26136-26-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128509588312758?= X-GMAIL-MSGID: =?utf-8?q?1749128509588312758?= 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 --- lib/Kconfig.debug | 16 ++++++++++++++++ rust/Makefile | 22 +++++++++++++++++----- rust/build_error.rs | 24 ++++++++++++++++++++++++ rust/exports.c | 5 +++++ scripts/generate_rust_analyzer.py | 8 +++++++- 5 files changed, 69 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..0ff6b33059aa --- /dev/null +++ b/rust/build_error.rs @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Build-time error. +//! +//! This crate provides a function `build_error`, which will panic in +//! compile-time if executed in 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, but those +//! functions could still be called in the runtime). + +#![no_std] + +/// Panics if executed in const context, or triggers a build error if not. +#[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 Thu Nov 10 16:41: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: 18227 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp253917wru; Thu, 10 Nov 2022 08:49:11 -0800 (PST) X-Google-Smtp-Source: AMsMyM7rAzKDNl3MWtxY09V9Y1f+IkDxNnrJ4b153oNTwsFUlkgGOs+zN2eYznrsAHkJ8UIJBFBV X-Received: by 2002:a17:906:d799:b0:76c:42b4:dea4 with SMTP id pj25-20020a170906d79900b0076c42b4dea4mr3027313ejb.515.1668098951092; Thu, 10 Nov 2022 08:49:11 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098951; cv=none; d=google.com; s=arc-20160816; b=hnqJFT+l3pTBUK3Uzs7uqHi5ckxY+/QeiIk1CuOBvb0Qi0NBTICW8W7xf1q7L6gcur ZBM69lzTzGV+vx23yNALGbiG///Y4gGSELEI0dGo5IW6K1FHus2DCqnSsZBfHtyXhW5n yk6ATf/0ZcjTmD6b8mvVK5Urp0/jMBpg115pjMVsF3XWhjqET6XuR9O7fOYXer2FrEFk 0MHp/o7v5Ha6fbMfYZGSPEmgwpPTjo2XSAVLn0fDvdxB04ZnZxN8TyraECYU8mb7Nhj2 yC7cmseajHxCIWlpkggA2QCEdCZ5ugNi5YOMNM/RrAQxyiKRPfD6WIEGCTdjAI3N4jv3 Eweg== 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=KPl2fbbm9+/Sx1JZSa6NuUo2cATGgMCwMJupUhsHC4nsO9ud6Vp/52/pE0LVWiSNfN QV26zPF3fQ5QVj5qvjehDz+HrLNeQ0A9OUagkts2lTQm5QdqyC1+aBoAJ26SL7Sx/S5W 2GgwgqcyHFY74RlnDdSAnHSFWY1CJjV4pTPrV+/IvJq3CM+80yJ/b68AOFGo8VdLKmu/ kk0YCO6W5Cqw5G45weQBPmDy7P8FYjQ2/NKmVgwDcuSwYyM7GbQ8LVqbwH+YUU5Yvboy zfuitvbSsqvXy1m82lKomyl2H4ORyC5AGOM8Jwa/y+IWwB3pwEjh+714hWF7YywhEXmk i7jw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=ecJ7IZZ3; 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 y22-20020a170906449600b007ae87dde2c7si3746570ejo.830.2022.11.10.08.48.46; Thu, 10 Nov 2022 08:49: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=ecJ7IZZ3; 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 S231234AbiKJQp3 (ORCPT + 99 others); Thu, 10 Nov 2022 11:45:29 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40960 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232370AbiKJQow (ORCPT ); Thu, 10 Nov 2022 11:44:52 -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 C37C611804; Thu, 10 Nov 2022 08:43: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 6CCC1B82248; Thu, 10 Nov 2022 16:43:38 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 12ADCC433C1; Thu, 10 Nov 2022 16:43:34 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098617; bh=qf1L1f1lloAHjax2Q2sSNkOySbNmdgvi1HaQZKetkYY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ecJ7IZZ3CrxyZ6SylQUbghb7oCf0y3MByU/BnTH3+lBMZugHYgzdnIkj2XVSnU9tz FKd0FTLp6mZ5ZSnV3RWqJJPKUUSGld6FgOKKLKdWvLDnbNXZ+U/VN67IGN8LEAWXTR /0+WBmoDU16OGhkN0v+SbKFHDrSe+8JAw39fTLkCTtrihKDHNa8V8/lxurXDlWaWsG Nn99uEv/W8YwgQ4UZmuXGOlx2WpoO+MX1RsJcVlWZ6px4Hw24REgxHOY8J3PSWOOZm zrn0FbGszPHkmY3Dj8maFV9Id3q62WcX+pP6kV7Rxl1E0aCnFF1SbArcBAwAt0uUTc Cmf+R6kLpFG1w== From: Miguel Ojeda 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 v1 26/28] rust: build_assert: add `build_{error,assert}!` macros Date: Thu, 10 Nov 2022 17:41:38 +0100 Message-Id: <20221110164152.26136-27-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128525700480730?= X-GMAIL-MSGID: =?utf-8?q?1749128525700480730?= 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 --- 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 Thu Nov 10 16:41: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: 18228 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp253969wru; Thu, 10 Nov 2022 08:49:16 -0800 (PST) X-Google-Smtp-Source: AMsMyM6gh2ijRuwYKQpsbRc5GfbNOiN/WRloy8zc+FeTeACgZLNAdoZo/0tYVE3jwYXfvJLRz5tH X-Received: by 2002:a05:6402:4d5:b0:459:2b41:3922 with SMTP id n21-20020a05640204d500b004592b413922mr2557082edw.160.1668098956018; Thu, 10 Nov 2022 08:49:16 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098956; cv=none; d=google.com; s=arc-20160816; b=YNjvnww6sygb0xFQmsTSQgzyG3/zK/DoTPbcPufVnOw3BTONmzDYy0eY51jH0ER0va CQt8tX29elPd+C0lrl7QLU9UwKGISq4MpxJtz2b0fKWYO2N/FYBpWECymushRCH/Dxpi AZLEhFoZp+9VcrYw0cGlt+NkhLG+sfkbLeL8c5CoysAGyDt+6SZS6vsZAyLuhKo2i1oU lz2zut4Cgem77Djgh//2eCmk2sDkVsMjM94MOdzFAJriijbA/CUu5d+SIqWQMKGItmLt gk3T3s4NnJoQVTxaxvtnjLvFbRCtDzbH2q58zqAJIrLmweBNxBNaZ9/RT6hI+/3Xu44b fMxA== 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=c8zlke2bLqJH/ddO2YAQ0YrBo//PbtDCeP+1p0VEKYE=; b=ZrNnqQg9i+Km9vVIK5nxirCsVNSVB7jivo16iNkxDzyodc8ywL8mf4ye0SmHQ/JUQ0 qczyeWl/VBJ8DM0ygL1lU0PZU8gjT+uvU8NIcZjimoDCLU3zbvIUrt7hrTBO6qqGHi7c 771bQD2IXc/g+ot3OWhVApXsla2zplryhnGppQpG/GkuNxiShR1GZcpRQ+s/Teh8M1Al ni50DAPDl6tYicBBvlMfH5C0tDXTE6bAC+Emn59O47QHPImdmennIwhI1QG+ClwEmZpA rU5ksNect1hyyIDK1thNydVgEdAlXucvkkALj4mk2JWySa2H38H/zKer+qqieVUEB79F lqmw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=JzTGAWvq; 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 cw9-20020a170906c78900b0078b96722000si13783032ejb.608.2022.11.10.08.48.49; Thu, 10 Nov 2022 08:49: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=JzTGAWvq; 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 S232330AbiKJQpi (ORCPT + 99 others); Thu, 10 Nov 2022 11:45:38 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40682 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232580AbiKJQo7 (ORCPT ); Thu, 10 Nov 2022 11:44:59 -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 B7BC010FE0; Thu, 10 Nov 2022 08:43: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 ams.source.kernel.org (Postfix) with ESMTPS id 73137B82251; Thu, 10 Nov 2022 16:43:41 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 293CEC433B5; Thu, 10 Nov 2022 16:43:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098620; bh=qGXfF0wUmE6bpAXFogr6UIGDaM64e+dQ9MKJUHRzQqM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=JzTGAWvq1ESHwzE5/pnlpzv+kVN4jQdV0B7HZEKQ/UmLxon1vkKllZAhV1tMEcGBL TjNhYhQ93oWavvSJQCrcp+aUEsO5yFkknl12Ak8++oIXZVVu+I41j9wAThrU43HkHP vXIf/h8URsKzoDgUyMR5OZQ/awbNiuMyca0x9jorm7yZ5X3Pw5NoQyuhw+5P0Rf+4Q KjUXEnopsOuDc92smLFfBJh4l3acvRr0CdfzyRSo14rrxUFbcxkeTULB5Ra47pyOUa u9uTDs58hdBnt5F4SuN1CHWr6iceMyvVijdPgUTVTX5b1sg4iytGoJQ2t5hR/IX7AE wy75gexKLrpoA== From: Miguel Ojeda 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 v1 27/28] rust: types: add `Either` type Date: Thu, 10 Nov 2022 17:41:39 +0100 Message-Id: <20221110164152.26136-28-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128530812759015?= X-GMAIL-MSGID: =?utf-8?q?1749128530812759015?= 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 [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda Reviewed-by: Wei Liu --- 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 Thu Nov 10 16:41: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: 18229 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a5d:6687:0:0:0:0:0 with SMTP id l7csp254110wru; Thu, 10 Nov 2022 08:49:34 -0800 (PST) X-Google-Smtp-Source: AMsMyM5rbKHMMzsT3JvYjkXwplqMJ5ZtQj5bjtGC0H1FcM4sLrfZ9il4WnY7gMyWYBJX6Ba7VTNZ X-Received: by 2002:a05:6a00:e0f:b0:56d:6e51:3060 with SMTP id bq15-20020a056a000e0f00b0056d6e513060mr57603730pfb.55.1668098974280; Thu, 10 Nov 2022 08:49:34 -0800 (PST) ARC-Seal: i=1; a=rsa-sha256; t=1668098974; cv=none; d=google.com; s=arc-20160816; b=Ym6H+Zjj+sgo9Xbmax7VHIq5UBXrnqweOM4rJ5wVHPOtiqVyoseb9+hXQ9cjO0+4A/ Ydn6qIqnlicWb9cCL1ge+/SS6rc80zQYDqMzZTVgLbkfOP7vrzGLYXGoIc9r3UUxaVrX OJtfJ9WxZgW1G/s1UWy+FOP5jOpw7/BVB+Frh0ifgfQvhk8eYL6UqzWDrZm1Z19v3zlv vH8UBEUewjXm5HlDQoy92oEHDMxRS2NMgb7vazl37WX4ob5OyX1+PxWI9z7hfSCwuJnD 1FhntGizflOPfllId008/jMjn5dlD33lAPHkW2Cokn+uhyNfGe1NVLaI/cL/rATweSb7 FQQQ== 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=k3fbSHkAbyD7UT+g36XGG/hCJzyLvr3/riHcVFR3e/cOz0s/7jJH440TSYq0ruknrA PPBOxnh567ISSK1ownZwQqCVctZi2Zk8tdgRqVC7pGVuprLLr4XqHA0hcHM4epljLR45 nYqndU+pAK/tHsi04MY9lKgWNF6QSqk145CJoOhxLyrJvI8x2PQjahISPBKSMJRFlfRo Dczo+THI0accXdAnZ4AQWhXyC4s04xINi1GT+8MP45ZSs3PAu0RhXHbQQFSaYXPpE/dd jA0wPQfhePYORgutKUC5HAz2+3hrWuFO4IK+emwoK4g+hqMfN5isjlTjvzOS+5C0sA0X Mluw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@kernel.org header.s=k20201202 header.b=QFqr9Y8X; 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 d190-20020a6336c7000000b0046b454af0d6si23099913pga.520.2022.11.10.08.49.18; Thu, 10 Nov 2022 08:49:34 -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=QFqr9Y8X; 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 S232029AbiKJQpk (ORCPT + 99 others); Thu, 10 Nov 2022 11:45:40 -0500 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:40552 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S232602AbiKJQpN (ORCPT ); Thu, 10 Nov 2022 11:45:13 -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 ACBA11EEF5; Thu, 10 Nov 2022 08:43:45 -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 58B12B82248; Thu, 10 Nov 2022 16:43:44 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 02B66C433D6; Thu, 10 Nov 2022 16:43:40 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1668098623; bh=YyjXthwblgrT88DPLFu+XIPGLqjTiZLg+Xpj0PN4MaE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QFqr9Y8X7Tigp18oliUFzjQmBK/C7AIWjnahKOX9XFUZZ5k9p85F+b9YrWQFAyT6R kiHrrN4NzdKIK6lQ+4RjaJYDQgUlMiv0QuklOB8XekHJQ6Ysoy0dS4dtNvmrqvQhdv l3dCz2qtsKyKXo7WA6yNgMjlYukM0Q1v076iwo2Jfao8Ae+HwmO5X4Wlx+yAcSb+dv +N81e4BkTfSkXnSlRCTkczSZujt3Pnqb4yGsIwqE8iRK4++IDcFS+IE8QltD74JVUl dDJnqLBcCYfVH1M8riwd/2iDGhBca/3oUv4BOxobeWiW/83LlxoWUiIwmTBA8QSC3p sIndo9vYAzXeQ== From: Miguel Ojeda 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 v1 28/28] rust: types: add `Opaque` type Date: Thu, 10 Nov 2022 17:41:40 +0100 Message-Id: <20221110164152.26136-29-ojeda@kernel.org> In-Reply-To: <20221110164152.26136-1-ojeda@kernel.org> References: <20221110164152.26136-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?1749128550019886772?= X-GMAIL-MSGID: =?utf-8?q?1749128550019886772?= 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`.