Skip to main content

console_tests_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 missing safety doc comments for public unsafe extern FFI test helper functions.
7#![allow(clippy::missing_safety_doc)]
8
9#[cfg(not(console_enabled))]
10use {console_rust as _, zx_status as _};
11
12#[cfg(console_enabled)]
13mod test {
14    use console_rust::{CMD_AVAIL_NORMAL, CmdArgs, static_command};
15    use core::ffi::c_int;
16    use zx_status::Status;
17
18    macro_rules! zx_status {
19        ($status:expr) => {
20            $status.into_raw()
21        };
22    }
23
24    // FFI imports.
25    unsafe extern "C" {
26        static __start_commands: console_rust::Cmd;
27        static __stop_commands: console_rust::Cmd;
28        fn strcmp(s1: *const core::ffi::c_char, s2: *const core::ffi::c_char) -> core::ffi::c_int;
29    }
30
31    // Statically registered commands.
32    static_command!(
33        TEST_CMD,
34        c"mock_success".as_ptr(),
35        c"mock_success help".as_ptr(),
36        mock_success_callback,
37        CMD_AVAIL_NORMAL
38    );
39
40    unsafe extern "C" fn mock_success_callback(
41        _argc: c_int,
42        _argv: *const CmdArgs,
43        _flags: u32,
44    ) -> c_int {
45        zx_status!(Status::OK)
46    }
47
48    // FFI exports.
49
50    // Verifies that the test command is registered correctly from the Rust side.
51    #[unsafe(no_mangle)]
52    pub unsafe extern "C" fn command_visibility_from_rust_test() -> bool {
53        unsafe {
54            let start = &__start_commands as *const console_rust::Cmd;
55            let stop = &__stop_commands as *const console_rust::Cmd;
56
57            let mut current = start;
58            let mut found = false;
59
60            while current < stop {
61                let cmd = &*current;
62                if strcmp(cmd.cmd_str, c"mock_success".as_ptr()) == 0 {
63                    found = true;
64                    if strcmp(cmd.help_str, c"mock_success help".as_ptr()) != 0 {
65                        found = false;
66                    }
67                    if cmd.availability_mask != CMD_AVAIL_NORMAL {
68                        found = false;
69                    }
70                    break;
71                }
72                current = current.add(1);
73            }
74
75            found
76        }
77    }
78}