morpheus_bootloader/
main.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Morpheus UEFI Bootloader - Hello World
//!
//! First UEFI application that displays "Morpheus" on screen.

#![no_std]
#![no_main]
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
#![allow(unused_mut)]

extern crate alloc;

use core::panic::PanicInfo;

mod boot;
mod installer;
mod tui;
mod uefi;

use tui::boot_sequence::{BootSequence, NetworkBootResult};
use tui::distro_launcher::DistroLauncher;
use tui::input::Keyboard;
use tui::installer_menu::InstallerMenu;
use tui::logo::{LOGO_LINES_RAW, LOGO_WIDTH, TAGLINE, TAGLINE_WIDTH};
use tui::main_menu::{MainMenu, MenuAction};
use tui::rain::MatrixRain;
use tui::renderer::Screen;
use tui::storage_manager::StorageManager;

#[repr(C)]
pub struct SimpleTextInputProtocol {
    reset: extern "efiapi" fn(*mut SimpleTextInputProtocol, bool) -> usize,
    read_key_stroke:
        extern "efiapi" fn(*mut SimpleTextInputProtocol, *mut tui::input::InputKey) -> usize,
}

#[repr(C)]
pub struct SimpleTextOutputMode {
    max_mode: i32,
    mode: i32,
    attribute: i32,
    cursor_column: i32,
    cursor_row: i32,
    cursor_visible: bool,
}

#[repr(C)]
pub struct SimpleTextOutputProtocol {
    reset: extern "efiapi" fn(*mut SimpleTextOutputProtocol, bool) -> usize,
    output_string: extern "efiapi" fn(*mut SimpleTextOutputProtocol, *const u16) -> usize,
    test_string: usize,
    query_mode:
        extern "efiapi" fn(*mut SimpleTextOutputProtocol, usize, *mut usize, *mut usize) -> usize,
    set_mode: usize,
    set_attribute: extern "efiapi" fn(*mut SimpleTextOutputProtocol, usize) -> usize,
    clear_screen: extern "efiapi" fn(*mut SimpleTextOutputProtocol) -> usize,
    set_cursor_position: extern "efiapi" fn(*mut SimpleTextOutputProtocol, usize, usize) -> usize,
    enable_cursor: extern "efiapi" fn(*mut SimpleTextOutputProtocol, bool) -> usize,
    mode: *const SimpleTextOutputMode,
}

#[repr(C)]
struct SystemTable {
    _header: [u8; 24],
    _firmware_vendor: *const u16,
    _firmware_revision: u32,
    _console_in_handle: *const (),
    con_in: *mut SimpleTextInputProtocol,
    _console_out_handle: *const (),
    con_out: *mut SimpleTextOutputProtocol,
    _stderr_handle: *const (),
    _stderr: *const (),
    runtime_services: *const RuntimeServices,
    boot_services: *const BootServices,
    number_of_table_entries: usize,
    configuration_table: *const ConfigurationTable,
}

#[repr(C)]
struct RuntimeServices {
    _header: [u8; 24],
    // Time Services
    _get_time: usize,
    _set_time: usize,
    _get_wakeup_time: usize,
    _set_wakeup_time: usize,
    // Virtual Memory Services
    _set_virtual_address_map: usize,
    _convert_pointer: usize,
    // Variable Services
    _get_variable: usize,
    _get_next_variable_name: usize,
    _set_variable: usize,
    // Miscellaneous Services
    _get_next_high_monotonic_count: usize,
    pub reset_system: extern "efiapi" fn(
        reset_type: u32, // 0=Cold, 1=Warm, 2=Shutdown, 3=PlatformSpecific
        reset_status: usize,
        data_size: usize,
        reset_data: *const (),
    ) -> !,
}

#[repr(C)]
struct ConfigurationTable {
    vendor_guid: [u8; 16],
    vendor_table: *const (),
}

#[repr(C)]
pub struct BootServices {
    _header: [u8; 24],
    // Task Priority Services
    _raise_tpl: usize,
    _restore_tpl: usize,
    // Memory Services (correct order per UEFI spec)
    pub allocate_pages: extern "efiapi" fn(
        allocate_type: usize,
        memory_type: usize,
        pages: usize,
        memory: *mut u64,
    ) -> usize,
    pub free_pages: extern "efiapi" fn(memory: u64, pages: usize) -> usize,
    pub get_memory_map: extern "efiapi" fn(
        memory_map_size: *mut usize,
        memory_map: *mut u8,
        map_key: *mut usize,
        descriptor_size: *mut usize,
        descriptor_version: *mut u32,
    ) -> usize,
    allocate_pool: extern "efiapi" fn(pool_type: usize, size: usize, buffer: *mut *mut u8) -> usize,
    free_pool: extern "efiapi" fn(buffer: *mut u8) -> usize,
    // Event & Timer Services
    _create_event: usize,
    _set_timer: usize,
    _wait_for_event: usize,
    _signal_event: usize,
    _close_event: usize,
    _check_event: usize,
    // Protocol Handler Services
    install_protocol_interface: extern "efiapi" fn(
        handle: *mut *mut (),
        protocol: *const [u8; 16],
        interface_type: usize,
        interface: *mut core::ffi::c_void,
    ) -> usize,
    _reinstall_protocol_interface: extern "efiapi" fn(
        handle: *mut (),
        protocol: *const [u8; 16],
        interface_type: usize,
        old_interface: *mut core::ffi::c_void,
        new_interface: *mut core::ffi::c_void,
    ) -> usize,
    uninstall_protocol_interface: extern "efiapi" fn(
        handle: *mut (),
        protocol: *const [u8; 16],
        interface: *mut core::ffi::c_void,
    ) -> usize,
    handle_protocol: extern "efiapi" fn(
        handle: *mut (),
        protocol: *const [u8; 16],
        interface: *mut *mut (),
    ) -> usize,
    _reserved: usize,
    _register_protocol_notify: usize,
    locate_handle: extern "efiapi" fn(
        search_type: usize,
        protocol: *const [u8; 16],
        search_key: *const (),
        buffer_size: *mut usize,
        buffer: *mut *mut (),
    ) -> usize,
    locate_device_path: extern "efiapi" fn(
        protocol: *const [u8; 16],
        device_path: *mut *mut (),
        handle: *mut *mut (),
    ) -> usize,
    install_configuration_table:
        extern "efiapi" fn(guid: *const [u8; 16], table: *const core::ffi::c_void) -> usize,
    // Image Services
    pub load_image: extern "efiapi" fn(
        boot_policy: bool,
        parent_image_handle: *mut (),
        file_path: *const (),
        source_buffer: *const core::ffi::c_void,
        source_size: usize,
        image_handle: *mut *mut (),
    ) -> usize,
    pub start_image: extern "efiapi" fn(
        image_handle: *mut (),
        exit_data_size: *mut usize,
        exit_data: *mut *mut u16,
    ) -> usize,
    _exit: extern "efiapi" fn(*mut (), usize, *const u16) -> usize,
    pub unload_image: extern "efiapi" fn(image_handle: *mut ()) -> usize,
    pub exit_boot_services: extern "efiapi" fn(image_handle: *mut (), map_key: usize) -> usize,
    // Miscellaneous Services
    _get_next_monotonic_count: usize,
    /// Stall for microseconds
    pub stall: extern "efiapi" fn(microseconds: usize) -> usize,
    _set_watchdog_timer: usize,
}

#[no_mangle]
pub extern "efiapi" fn efi_main(image_handle: *mut (), system_table: *const ()) -> usize {
    unsafe {
        let system_table = &*(system_table as *const SystemTable);

        // Initialize heap allocator FIRST - before any allocations
        // Uses static buffer, works during UEFI and post-EBS
        morpheus_network::alloc_heap::init_heap();

        // Set global boot services pointer (for other UEFI operations)
        BOOT_SERVICES_PTR = system_table.boot_services;

        let mut screen = Screen::new(system_table.con_out);
        let mut keyboard = Keyboard::new(system_table.con_in);

        screen.clear();

        // Calculate centered positions
        let screen_width = screen.width();
        let screen_height = screen.height();

        // Center logo vertically - put in upper third
        let logo_y = 2;

        // Draw logo centered horizontally
        let logo_x = screen.center_x(LOGO_WIDTH);

        for (i, line) in LOGO_LINES_RAW.iter().enumerate() {
            let y = logo_y + i;
            if y < screen_height {
                screen.put_str_at(
                    logo_x,
                    y,
                    line,
                    tui::renderer::EFI_GREEN,
                    tui::renderer::EFI_BLACK,
                );
            }
        }

        // Draw tagline centered
        let tagline_y = logo_y + LOGO_LINES_RAW.len() + 1;
        let tagline_x = screen.center_x(TAGLINE_WIDTH);
        if tagline_y < screen_height {
            screen.put_str_at(
                tagline_x,
                tagline_y,
                TAGLINE,
                tui::renderer::EFI_GREEN,
                tui::renderer::EFI_BLACK,
            );
        }

        // Boot sequence - log real initialization steps
        let boot_y = tagline_y + 3;
        let boot_x = 5;
        let mut boot_seq = BootSequence::new();

        // Initialize matrix rain
        let mut rain = MatrixRain::new(screen_width, screen_height);

        // Perform actual initialization and log each step
        morpheus_core::logger::log("MorpheusX initialized");
        boot_seq.render(&mut screen, boot_x, boot_y);

        morpheus_core::logger::log("UEFI system table acquired");
        boot_seq.render(&mut screen, boot_x, boot_y);

        morpheus_core::logger::log("Console output protocol ready");
        boot_seq.render(&mut screen, boot_x, boot_y);

        morpheus_core::logger::log("Keyboard input protocol ready");
        boot_seq.render(&mut screen, boot_x, boot_y);

        // Enumerate storage devices
        let bs = &*system_table.boot_services;
        let mut temp_disk_manager = morpheus_core::disk::manager::DiskManager::new();
        match crate::uefi::disk::enumerate_disks(bs, &mut temp_disk_manager) {
            Ok(()) => {
                let disk_count = temp_disk_manager.disk_count();
                if disk_count > 0 {
                    morpheus_core::logger::log("Block I/O protocol initialized");
                    boot_seq.render(&mut screen, boot_x, boot_y);

                    morpheus_core::logger::log("Storage devices enumerated");
                    boot_seq.render(&mut screen, boot_x, boot_y);
                } else {
                    morpheus_core::logger::log("No storage devices detected");
                    boot_seq.render(&mut screen, boot_x, boot_y);
                }
            }
            Err(_) => {
                morpheus_core::logger::log("Warning: Storage enumeration failed");
                boot_seq.render(&mut screen, boot_x, boot_y);
            }
        }

        morpheus_core::logger::log("TUI renderer initialized");
        boot_seq.render(&mut screen, boot_x, boot_y);

        morpheus_core::logger::log("Matrix rain effect loaded");
        boot_seq.render(&mut screen, boot_x, boot_y);

        morpheus_core::logger::log("Main menu system ready");
        boot_seq.render(&mut screen, boot_x, boot_y);

        // NOTE: Network is NOT initialized during bootstrap anymore.
        // Network initialization happens post-ExitBootServices when user
        // actually starts a download. This avoids conflicts between
        // smoltcp (bare-metal TCP/IP) and UEFI's active timer interrupts.
        //
        // The download flow is:
        // 1. User selects ISO in TUI (catalog is static, no network needed)
        // 2. User confirms download → ExitBootServices called
        // 3. Bare-metal network stack initializes (VirtIO + smoltcp)
        // 4. Download completes, system reboots

        boot_seq.mark_complete();
        boot_seq.render(&mut screen, boot_x, boot_y);

        // Emit boot token for CI/CD E2E test validation
        // This token is detected by qemu-e2e.sh via serial output
        #[cfg(target_arch = "x86_64")]
        morpheus_network::serial_str("MORPHEUSX_BOOT_OK\n");

        // Render rain one final time for visual effect before waiting
        rain.render_frame(&mut screen);

        // Wait for keypress
        keyboard.wait_for_key();

        // Main application loop
        loop {
            // Launch main menu
            let mut main_menu = MainMenu::new(&screen);
            let action = main_menu.run(&mut screen, &mut keyboard);

            // Handle menu action
            match action {
                MenuAction::DistroLauncher => {
                    let bs = &*system_table.boot_services;
                    let st_ptr = system_table as *const SystemTable as *mut ();
                    let mut launcher = DistroLauncher::new(bs, image_handle);
                    launcher.run(&mut screen, &mut keyboard, bs, st_ptr, image_handle);
                }
                MenuAction::DistroDownloader => {
                    let bs = &*system_table.boot_services;
                    // Get disk info for ISO storage
                    // ESP typically starts after GPT headers, disk size from first disk
                    let (esp_lba, disk_lba) = {
                        let mut dm = morpheus_core::disk::manager::DiskManager::new();
                        if crate::uefi::disk::enumerate_disks(bs, &mut dm).is_ok()
                            && dm.disk_count() > 0
                        {
                            if let Some(disk) = dm.get_disk(0) {
                                // ESP usually at LBA 2048, use full disk size (last_block + 1)
                                (2048, disk.last_block + 1)
                            } else {
                                (2048, 100_000_000) // ~50GB default
                            }
                        } else {
                            (2048, 100_000_000)
                        }
                    };
                    let mut downloader = tui::distro_downloader::DistroDownloader::new(
                        bs,
                        image_handle,
                        esp_lba,
                        disk_lba,
                    );
                    // Downloader manages ISOs (download/delete), boot happens via DistroLauncher
                    downloader.run(&mut screen, &mut keyboard);
                }
                MenuAction::StorageManager => {
                    let bs = &*system_table.boot_services;
                    let mut storage_mgr = StorageManager::new(&screen);
                    storage_mgr.run(&mut screen, &mut keyboard, bs);
                    // Returns when user presses ESC, loop continues to main menu
                }
                MenuAction::SystemSettings => {
                    let bs = &*system_table.boot_services;
                    let mut installer_menu = InstallerMenu::new(image_handle);
                    installer_menu.run(&mut screen, &mut keyboard, bs);
                    // Returns when user presses ESC, loop continues to main menu
                }
                MenuAction::AdminFunctions => {
                    screen.clear();
                    screen.put_str_at(
                        5,
                        10,
                        "Admin Functions - Coming soon...",
                        tui::renderer::EFI_LIGHTGREEN,
                        tui::renderer::EFI_BLACK,
                    );
                    keyboard.wait_for_key();
                }
                MenuAction::ExitToFirmware => {
                    screen.clear();
                    screen.put_str_at(
                        5,
                        10,
                        "Exiting to firmware...",
                        tui::renderer::EFI_LIGHTGREEN,
                        tui::renderer::EFI_BLACK,
                    );

                    // Actually exit to firmware using UEFI ResetSystem
                    unsafe {
                        let runtime_services = &*system_table.runtime_services;
                        // ResetType: 0 = EfiResetCold, 1 = EfiResetWarm, 2 = EfiResetShutdown
                        // Use EfiResetWarm (1) to return to firmware setup
                        (runtime_services.reset_system)(1, 0, 0, core::ptr::null());
                    }
                }
                _ => {}
            }
        }
    }
}

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    // Try to display panic information on screen
    // This is best-effort since we may be in a bad state
    unsafe {
        if !BOOT_SERVICES_PTR.is_null() {
            // Try to get console output and display panic
            // We can't use the Screen abstraction here since we might be in a bad state
            // Just spin - at minimum don't silently hang
        }
    }

    // Log the panic message if possible
    if let Some(location) = info.location() {
        // We can't allocate in panic handler, so just use static message
        morpheus_core::logger::log("PANIC occurred!");
    } else {
        morpheus_core::logger::log("PANIC occurred (no location)!");
    }

    // Infinite loop - system is in bad state
    // TODO: Could trigger UEFI reset after timeout
    loop {
        // Prevent optimization from removing the loop
        core::hint::spin_loop();
    }
}

// Boot services pointer for UEFI operations (not allocator)
static mut BOOT_SERVICES_PTR: *const BootServices = core::ptr::null();