Skip to main content

console_rust/
lib.rs

1// Copyright 2026 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#![no_std]
6#![allow(unsafe_op_in_unsafe_fn)]
7
8use core::ffi::{c_char, c_int, c_void};
9
10pub const CMD_AVAIL_NORMAL: u8 = 1 << 0;
11pub const CMD_AVAIL_PANIC: u8 = 1 << 1;
12pub const CMD_AVAIL_ALWAYS: u8 = CMD_AVAIL_NORMAL | CMD_AVAIL_PANIC;
13
14// Command is happening at crash time.
15pub const CMD_FLAG_PANIC: u32 = 1 << 0;
16
17#[repr(C)]
18#[derive(Clone, Copy)]
19pub struct CmdArgs {
20    pub str: *const c_char,
21    pub u: core::ffi::c_ulong,
22    pub p: *mut c_void,
23    pub i: core::ffi::c_long,
24    pub b: bool,
25}
26
27pub type CmdCallback = unsafe extern "C" fn(argc: c_int, argv: *const CmdArgs, flags: u32) -> c_int;
28
29#[repr(C)]
30pub struct Cmd {
31    pub cmd_str: *const c_char,
32    pub help_str: *const c_char,
33    pub cmd_callback: CmdCallback,
34    pub availability_mask: u8,
35}
36
37// Safety: Cmd structures placed in the commands section are read-only
38// after boot and safe to share between threads.
39unsafe impl Sync for Cmd {}
40
41// Verify size and alignment compatibility with C++ structs.
42zr::static_assert!(core::mem::size_of::<CmdArgs>() == 40);
43zr::static_assert!(core::mem::align_of::<CmdArgs>() == 8);
44zr::static_assert!(core::mem::size_of::<Cmd>() == 32);
45zr::static_assert!(core::mem::align_of::<Cmd>() == 8);
46
47#[cfg(console_enabled)]
48#[macro_export]
49macro_rules! commands_section {
50    () => {
51        ".data.rel.ro.commands"
52    };
53}
54
55#[macro_export]
56macro_rules! static_command {
57    ($var_name:ident, $cmd:expr, $help:expr, $func:expr, $mask:expr) => {
58        #[cfg(console_enabled)]
59        #[used]
60        #[unsafe(link_section = $crate::commands_section!())]
61        pub static $var_name: $crate::Cmd = $crate::Cmd {
62            cmd_str: $cmd,
63            help_str: $help,
64            cmd_callback: $func,
65            availability_mask: $mask,
66        };
67    };
68}