{"record":{"id":"06e09030f1214d4c","repo":"rust-embedded/rust-raspberrypi-OS-tutorials","slug":"invalid-kernel-state","errorCode":null,"errorMessage":"Invalid KERNEL_STATE","messagePattern":"Invalid KERNEL_STATE","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"20_timer_callbacks/kernel/src/state.rs","lineNumber":68,"sourceCode":"impl StateManager {\n    const INIT: u8 = 0;\n    const SINGLE_CORE_MAIN: u8 = 1;\n    const MULTI_CORE_MAIN: u8 = 2;\n\n    /// Create a new instance.\n    pub const fn new() -> Self {\n        Self(AtomicU8::new(Self::INIT))\n    }\n\n    /// Return the current state.\n    fn state(&self) -> State {\n        let state = self.0.load(Ordering::Acquire);\n\n        match state {\n            Self::INIT => State::Init,\n            Self::SINGLE_CORE_MAIN => State::SingleCoreMain,\n            Self::MULTI_CORE_MAIN => State::MultiCoreMain,\n            _ => panic!(\"Invalid KERNEL_STATE\"),\n        }\n    }\n\n    /// Return if the kernel is init state.\n    pub fn is_init(&self) -> bool {\n        self.state() == State::Init\n    }\n\n    /// Transition from Init to SingleCoreMain.\n    pub fn transition_to_single_core_main(&self) {\n        if self\n            .0\n            .compare_exchange(\n                Self::INIT,\n                Self::SINGLE_CORE_MAIN,\n                Ordering::Acquire,\n                Ordering::Relaxed,\n            )","sourceCodeStart":50,"sourceCodeEnd":86,"githubUrl":"https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/blob/644474cc09f755249f9c55d99a5d1e07a2562fc7/20_timer_callbacks/kernel/src/state.rs#L50-L86","documentation":"The kernel state machine stores its state in an AtomicU8 with sentinel values (INIT, SINGLE_CORE_MAIN, MULTI_CORE_MAIN). state() loads the atomic and panics if the raw value matches none of the known sentinels, indicating corrupted or uninitialized KERNEL_STATE memory. is_init() calls state(), so any state query on corrupted state panics.","triggerScenarios":"Reading kernel state before the static KERNEL_STATE was initialized with a valid value (memory not zeroed/initialized to INIT); memory corruption overwriting the atomic; a bad transmute/write to the static from elsewhere; calling is_init()/state() on a wrongly constructed StateProvider.","commonSituations":"Early-boot code querying state before state initialization in .bss/.data setup; linker/script changes that clobber the static; concurrent unynchronized writes to the state cell; hand-edited sentinel constants.","solutions":["Ensure KERNEL_STATE is initialized (to INIT) at/before its first use — check static initialization in state.rs.","Find any code writing raw values into the atomic and validate it uses the defined constants only.","Initialize the atomic with Self::INIT as its default value so it can never hold a sentinel-unknown value.","Check linker script / memory layout for overlap with other statics that could corrupt this cell.","Gate early-boot callers so is_init() isn't invoked before state setup."],"exampleFix":"// before\nstatic KERNEL_STATE: AtomicU8 = AtomicU8::new(0xff);\n// after\nstatic KERNEL_STATE: AtomicU8 = AtomicU8::new(KernelState::INIT as u8);","handlingStrategy":"validation","validationCode":"fn state_is_known(raw: u8) -> bool {\n    matches!(raw, s if s == INIT || s == SINGLE_CORE_MAIN || s == MULTI_CORE_MAIN)\n}","typeGuard":"fn valid_kernel_state(raw: u8) -> Option<State> {\n    match raw {\n        x if x == INIT => Some(State::Init),\n        x if x == SINGLE_CORE_MAIN => Some(State::SingleCoreMain),\n        x if x == MULTI_CORE_MAIN => Some(State::MultiCoreMain),\n        _ => None,\n    }\n}","tryCatchPattern":"// Panic aborts in no_std; validate raw value before querying:\nlet raw = KERNEL_STATE.load(Ordering::Acquire);\nif valid_kernel_state(raw).is_none() {\n    log::error!(\"corrupted KERNEL_STATE: {}\", raw);\n    halt();\n}","preventionTips":["Initialize the state atomic with a valid sentinel (INIT) as its default.","Only write the state through the defined transition methods.","Verify linker/memory layout doesn't overlap the static.","Never transmute or hand-write raw values into the state cell."],"tags":["rust","kernel","state-machine","panic"],"backgroundTag":"internal-invariant-violation","analyzedSha":"644474cc09f755249f9c55d99a5d1e07a2562fc7","analyzedAt":"2026-09-06T09:25:56.584Z","contentChangedAt":"2026-09-06T09:25:56.584Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}