Working in a Workspace

Typically, an operating system may consist of multiple crates, and these crates may be organized in a workspace. The OSDK also supports managing projects in a workspace. Below is an example that demonstrates how to create, build, run, and test projects in a workspace.

Creating a new workspace

Create a new workspace by executing the following commands:

mkdir myworkspace && cd myworkspace
touch Cargo.toml

Then, add the following content to Cargo.toml:

[workspace]
members = []
resolver = "2"

Creating a kernel project and a library project

The two projects can be created using the following commands:

cargo osdk new --kernel myos
cargo osdk new mylib

The generated directory structure will be as follows:

myworkspace/
  ├── Cargo.toml
  ├── OSDK.toml
  ├── rust-toolchain.toml
  ├── myos/
  │   ├── Cargo.toml
  │   └── src/
  │       └── lib.rs
  └── mylib/
      ├── Cargo.toml
      └── src/
          └── lib.rs

At present, the OSDK mandates that there must be only one kernel project within a workspace.

In addition to the two projects, the OSDK will also generate OSDK.toml and rust-toolchain.toml at the root of the workspace.

Next, add the following function to mylib/src/lib.rs. This function will calculate the available memory after booting:

// SPDX-License-Identifier: MPL-2.0

pub fn available_memory() -> usize {
    let regions = ostd::boot::memory_regions();
    regions.iter().map(|region| region.len()).sum()
}

Then, add a dependency on mylib to myos/Cargo.toml:

[dependencies]
mylib = { path = "../mylib" }

In myos/src/lib.rs, modify the file content as follows. This main function will call the function from mylib:

// SPDX-License-Identifier: MPL-2.0

#![no_std]
#![deny(unsafe_code)]

use ostd::prelude::*;

#[ostd::main]
fn kernel_main() {
    let avail_mem_as_mb = mylib::available_memory() / 1_000_000;
    println!("The available memory is {} MB", avail_mem_as_mb);
}

Building and Running the kernel

Build and run the project using the following commands:

cargo osdk build
cargo osdk run

If everything goes well, you will see the output from the guest kernel.

Running unit test

You can run test cases from all crates by using the following command in the workspace folder:

cargo osdk test

If you want to run test cases from a specific crate, navigate to the crate's folder and run cargo osdk test. For example, if you want to test mylib, use the following command:

cd mylib && cargo osdk test