diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3d7f07b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,67 @@ +name: CI + +on: + pull_request: + push: + branches: + - main + +jobs: + build: + runs-on: windows-2022 + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.x" + + - name: Install NASM + shell: pwsh + run: | + choco install nasm --yes --no-progress + if ($LASTEXITCODE -ne 0) { throw "NASM installation failed" } + + $nasm = Get-Command nasm.exe -ErrorAction SilentlyContinue + if ($nasm) { + $nasmPath = $nasm.Source + } else { + $candidates = @( + (Join-Path $env:ProgramFiles "NASM\nasm.exe"), + (Join-Path $env:ChocolateyInstall "bin\nasm.exe") + ) + $nasmPath = $candidates | + Where-Object { Test-Path -LiteralPath $_ } | + Select-Object -First 1 + } + if (-not $nasmPath) { throw "nasm.exe was not found after installation" } + + & $nasmPath -v + if ($LASTEXITCODE -ne 0) { throw "NASM is not available on PATH" } + Add-Content -Path $env:GITHUB_PATH -Value (Split-Path -Parent $nasmPath) + + - name: Install i686-elf toolchain + shell: pwsh + run: | + $version = "15.2.0" + $archive = Join-Path $env:RUNNER_TEMP "i686-elf-tools-windows.zip" + $destination = Join-Path $env:RUNNER_TEMP "i686-elf-tools" + Invoke-WebRequest ` + -Uri "https://github.com/lordmilko/i686-elf-tools/releases/download/$version/i686-elf-tools-windows.zip" ` + -OutFile $archive + Expand-Archive -Path $archive -DestinationPath $destination + + $gcc = Get-ChildItem -Path $destination -Filter "i686-elf-gcc.exe" -Recurse | + Select-Object -First 1 + if (-not $gcc) { throw "i686-elf-gcc.exe was not found in the toolchain archive" } + Add-Content -Path $env:GITHUB_PATH -Value $gcc.DirectoryName + + - name: Run installer tests + run: python -m unittest discover -s tools -p "test_*.py" -v + + - name: Build VIGIL + shell: pwsh + run: | + cmd /c scripts\build.bat + if ($LASTEXITCODE -ne 0) { throw "VIGIL build failed" } diff --git a/.gitignore b/.gitignore index 56a1c63..981e3e9 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,11 @@ Thumbs.db .env *.env +# python +__pycache__/ +*.py[cod] +*.pyc + # builds build/ dist/ diff --git a/README.md b/README.md index b3c708c..d994b3b 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ VIGIL boots from its own two stage bootloader into a 32-bit graphical desktop wi ### Terminal -Command line shell with an 8 entry command history (cycle using up & down arrows). +The Terminal is a Command line shell built into the kernel with an 8 entry command history (cycle using up & down arrows). | Command | What it does | | ------------------------- | ------------------------------------------------------------------------- | @@ -34,6 +34,7 @@ Command line shell with an 8 entry command history (cycle using up & down arrows | `folder ` | Create a folder at `` | | `rename ` | Rename a file at `` to `` | | `files [folder]` | Lists saved files in specified folder. If left blank defaults to root dir | +| `loadapp ` | Loads an app file from disk | ### Notepad @@ -41,21 +42,30 @@ A text editor with a blinking cursor, arrow keys, Home, End, Delete, Backspace a ### Files -A simple file viewing app, where you can navigate the file tree. Clicking on a file will open it in notepad, clicking a folder will change the view to the contents of that folder. Files / Folders can be managed from the app, for example, right clicking a file will bring up options such as renaming, deleting, or seeing more information about it. +A simple file browser for navigating the file tree. Click a file to open it in Notepad, and click a folder to view its contents. Right click a file for options such as renaming, deleting, or viewing more information about it. ### Calculator -A simple calculator app with simple operations such as (`-`, `+`, `*`, `/`, & `%`). Each command is linked to a keypress. +A simple calculator supporting `-`, `+`, `*`, `/`, and `%`, operated with the keyboard. + +### Hello + +A small example app demonstrating that apps can be loaded from the storage disk rather than being built into the kernel. ### Using apps -Click an app on the home screen to launch it. The `-` button (or the `Esc` key) minimizes an app and keeps it running in the taskbar whereas the `X` button closes it completely. +Click an app on the home screen to launch it. The `-` button (or the `Esc` key) minimizes an app and keeps it running in the taskbar, while the `X` button closes it completely. + +### Builtin vs Loaded Apps + +The Terminal is built into the kernel, while Calculator, Files, Hello, and Notepad are compiled separately and installed in the `apps` folder on the persistent storage disk and loaded by the launcher at startup. Loaded apps use the kernel's VIGIL API to access services such as graphics and the filesystem, they are not isolated from the kernel. ## How it works -1. **Stage 1:** the 512 byte boot sector the BIOS loads first, then it reads stage 2 from disk. -2. **Stage 2:** enables the A20 line (access to memory above 1mb), asks the BIOS for a 1024x768 graphics mode, sets up the GDT, and switches the CPU to protected mode -3. **The kernel:** (C) installs interrupt handlers, remaps the interrupt controller, starts the timer, keyboard and mouse, then hands control to the launcher, which runs forever +1. **Stage 1:** The BIOS loads the 512-byte boot sector, which then reads stage 2 from disk +2. **Stage 2:** Enables the A20 line (access to memory above 1mb), asks the BIOS for a 1024x768 graphics mode, sets up the GDT, and switches the CPU to protected mode +3. **The kernel:** Installs interrupt handlers, remaps the interrupt controller, starts the timer, keyboard, and mouse, then hands control to the launcher +4. **Loadable apps:** The launcher loads app files from the `apps` folder on the separate storage disk into memory and registers them for the home screen | Part | Details | | ------------- | --------------------------------------------------------------------- | @@ -65,18 +75,18 @@ Click an app on the home screen to launch it. The `-` button (or the `Esc` key) | Input | PS/2 keyboard (Shift, Caps Lock, Ctrl, arrows) and PS/2 mouse | | Memory | First-fit heap allocator over a 1 MB pool | | Storage | ATA PIO disk driver on a separate 10 MB virtual disk | -| Filesystem | Up to 16 files, 16 char long names, with nested folder structure | +| Filesystem | Up to 32 files and folders, 15-character names, with nested folders | ## Running it -I work on VIGIL on windows (unfortunately). I have some helper batch scripts for executing simple actions for me, which need [NASM][nasm], the [i686-elf cross-compiler tools][elf-tools], and [QEMU][qemu]. +VIGILs helper batch scripts are for Windows and require [NASM][nasm], the [i686-elf cross-compiler tools][elf-tools], [Python 3][python], and [QEMU][qemu]. ```bash :: compile everything into dist/vigil.img vigil build -:: boot it in QEMU (use --sdl) -vigil run +:: boot it in QEMU with an SDL window (--no-sdl boots it normally) +vigil run [--no-sdl] :: build, then run vigil dev @@ -85,7 +95,7 @@ vigil dev vigil clean ``` -Side note - I would PROBABLY recommend running the run command with `--sdl` as an arguement (but this isnt available for dev, so I kind of stopped using it... I should probably add that functionality for dev......) +`vigil build` creates the boot image and installs the loadable apps onto `dist/storage.img`. The storage disk persists between builds, so close QEMU before building and reinstalling apps. ## License @@ -96,5 +106,6 @@ Repo is under an [MIT license][license]. [nasm]: https://www.nasm.us/ [elf-tools]: https://github.com/lordmilko/i686-elf-tools [qemu]: https://www.qemu.org/ +[python]: https://www.python.org/downloads/ [license]: LICENSE diff --git a/apps/calculator/calculator.c b/apps/calculator/calculator.c index 756250b..6998870 100644 --- a/apps/calculator/calculator.c +++ b/apps/calculator/calculator.c @@ -1,16 +1,17 @@ // apps/calculator/calculator.c -#include "calculator.h" +#include "app.h" +#include "api.h" #include "calc.h" -#include "button.h" -#include "graphics.h" -#include "font.h" -#include "kstring.h" #include "keyboard.h" -#include "mouse.h" +#include "font.h" #include "title_bar.h" #include "taskbar.h" +// --- API pointer --- + +static const vigil_api_t* api = 0; + // --- layout (pixels) --- #define KEY_W 96 @@ -105,16 +106,16 @@ static gfx_color_t color_for(key_kind_t kind) { static uint32_t band_height(void) { uint32_t used = TITLE_BAR_HEIGHT + TASKBAR_HEIGHT; - if (gfx_screen_height() > used) { - return gfx_screen_height() - used; + if (api->gfx_screen_height() > used) { + return api->gfx_screen_height() - used; } return 0; } static void compute_layout(void) { origin_x = 0; - if (gfx_screen_width() > CALC_WIDTH) { - origin_x = (gfx_screen_width() - CALC_WIDTH) / 2; + if (api->gfx_screen_width() > CALC_WIDTH) { + origin_x = (api->gfx_screen_width() - CALC_WIDTH) / 2; } origin_y = TITLE_BAR_HEIGHT; @@ -140,8 +141,8 @@ static void compute_layout(void) { // --- drawing --- static void draw_display(void) { - gfx_fill_rect(origin_x, origin_y, CALC_WIDTH, DISPLAY_H, DISPLAY_BG); - gfx_draw_rect_outline(origin_x, origin_y, CALC_WIDTH, DISPLAY_H, GFX_WHITE); + api->gfx_fill_rect(origin_x, origin_y, CALC_WIDTH, DISPLAY_H, DISPLAY_BG); + api->gfx_draw_rect_outline(origin_x, origin_y, CALC_WIDTH, DISPLAY_H, GFX_WHITE); const char* text; char number[12]; @@ -155,28 +156,28 @@ static void draw_display(void) { text = "Error: number too big"; color = GFX_RED; } else { - kitoa(calc_display_value(), number); + api->kitoa(calc_display_value(), number); text = number; } - uint32_t text_width = kstrlen(text) * FONT_WIDTH; + uint32_t text_width = api->kstrlen(text) * FONT_WIDTH; uint32_t text_x = origin_x + CALC_WIDTH - DISPLAY_PAD - text_width; uint32_t text_y = origin_y + (DISPLAY_H - FONT_HEIGHT) / 2; - gfx_draw_string(text_x, text_y, text, color); + api->gfx_draw_string(text_x, text_y, text, color); char symbol = calc_op_symbol(calc_pending_op()); if (symbol != 0 && error == CALC_OK) { - gfx_draw_char(origin_x + DISPLAY_PAD, origin_y + DISPLAY_PAD, symbol, GFX_GREEN); + api->gfx_draw_char(origin_x + DISPLAY_PAD, origin_y + DISPLAY_PAD, symbol, GFX_GREEN); } } static void paint(void) { - gfx_fill_rect(0, TITLE_BAR_HEIGHT, gfx_screen_width(), band_height(), GFX_BLACK); + api->gfx_fill_rect(0, TITLE_BAR_HEIGHT, api->gfx_screen_width(), band_height(), GFX_BLACK); draw_display(); for (int i = 0; i < CALC_KEY_COUNT; i++) { - button_draw(&buttons[i]); + api->button_draw(&buttons[i]); } } @@ -195,19 +196,19 @@ static void press_key(const key_def_t* key) { // --- app_t slots --- -void calculator_start(void) { +static void calculator_start(void) { calc_clear(); compute_layout(); paint(); } -void calculator_redraw(void) { +static void calculator_redraw(void) { compute_layout(); paint(); } -void calculator_handle_char(char c) { - mouse_hide_cursor(); +static void calculator_handle_char(char c) { + api->mouse_hide_cursor(); calc_op_t op = calc_op_from_char(c); @@ -230,8 +231,8 @@ void calculator_handle_char(char c) { draw_display(); } -void calculator_handle_click(int32_t x, int32_t y) { - int index = button_find_at(buttons, CALC_KEY_COUNT, x, y); +static void calculator_handle_click(int32_t x, int32_t y) { + int index = api->button_find_at(buttons, CALC_KEY_COUNT, x, y); if (index < 0) { return; } @@ -239,3 +240,19 @@ void calculator_handle_click(int32_t x, int32_t y) { press_key(&keys[index]); draw_display(); } + +// --- the entry point the loader calls --- + +int app_entry(const vigil_api_t* kernel_api, app_t* out_app) { + if (kernel_api->version != VIGIL_API_VERSION || kernel_api->struct_size < sizeof(vigil_api_t)) { + return 1; + } + api = kernel_api; + + out_app->name = "Calculator"; + out_app->start = calculator_start; + out_app->redraw = calculator_redraw; + out_app->on_key = calculator_handle_char; + out_app->on_click = calculator_handle_click; + return 0; +} diff --git a/apps/files/files.c b/apps/files/files.c index aa31085..e9758b8 100644 --- a/apps/files/files.c +++ b/apps/files/files.c @@ -1,15 +1,14 @@ // apps/files/files.c -#include "files.h" -#include "fs.h" -#include "graphics.h" +#include "app.h" +#include "api.h" #include "font.h" -#include "kstring.h" -#include "menu.h" #include "title_bar.h" #include "taskbar.h" -#include "launcher.h" -#include "prompt.h" + +// --- api pointer --- + +static const vigil_api_t* api = 0; // --- layout (pixels) --- @@ -115,8 +114,8 @@ static void clear_message(void) { // --- paths --- static int child_path(const char* name, char* out) { - uint32_t base = kstrlen(current_path); - uint32_t needed = base + (base > 0 ? 1 : 0) + kstrlen(name); + uint32_t base = api->kstrlen(current_path); + uint32_t needed = base + (base > 0 ? 1 : 0) + api->kstrlen(name); if (needed >= FS_MAX_PATH) { return 0; } @@ -161,7 +160,7 @@ static uint32_t list_top(void) { } static uint32_t footer_y(void) { - return gfx_screen_height() - FILES_BOTTOM - FOOTER_HEIGHT; + return api->gfx_screen_height() - FILES_BOTTOM - FOOTER_HEIGHT; } static uint32_t row_y(int row) { @@ -170,10 +169,10 @@ static uint32_t row_y(int row) { static int rows_that_fit(void) { uint32_t used = FILES_TOP + FILES_BOTTOM + HEADER_HEIGHT + FOOTER_HEIGHT; - if (gfx_screen_height() <= used) { + if (api->gfx_screen_height() <= used) { return 0; } - return (int) ((gfx_screen_height() - used) / ROW_HEIGHT); + return (int) ((api->gfx_screen_height() - used) / ROW_HEIGHT); } static int visible_rows(void) { @@ -208,7 +207,7 @@ static int entry_for_row(int row) { // --- drawing --- static void draw_header(void) { - gfx_fill_rect(0, FILES_TOP, gfx_screen_width(), HEADER_HEIGHT, BAR_COLOR); + api->gfx_fill_rect(0, FILES_TOP, api->gfx_screen_width(), HEADER_HEIGHT, BAR_COLOR); char line[FS_MAX_PATH + 16]; int pos = 0; @@ -217,18 +216,18 @@ static void draw_header(void) { append(line, &pos, (int) sizeof(line), current_path); uint32_t text_y = FILES_TOP + (HEADER_HEIGHT - FONT_HEIGHT) / 2; - gfx_draw_string(TEXT_X, text_y, line, GFX_WHITE); + api->gfx_draw_string(TEXT_X, text_y, line, GFX_WHITE); } static void draw_footer(void) { uint32_t y = footer_y(); - gfx_fill_rect(0, y, gfx_screen_width(), FOOTER_HEIGHT, BAR_COLOR); + api->gfx_fill_rect(0, y, api->gfx_screen_width(), FOOTER_HEIGHT, BAR_COLOR); uint32_t text_y = y + (FOOTER_HEIGHT - FONT_HEIGHT) / 2; if (message[0] != '\0') { - gfx_draw_string(TEXT_X, text_y, message, MESSAGE_COLOR); + api->gfx_draw_string(TEXT_X, text_y, message, MESSAGE_COLOR); } else { - gfx_draw_string(TEXT_X, text_y, HINT_TEXT, GFX_WHITE); + api->gfx_draw_string(TEXT_X, text_y, HINT_TEXT, GFX_WHITE); } } @@ -237,7 +236,7 @@ static void draw_row(int row) { int entry = entry_for_row(row); if (entry == PARENT_ENTRY) { - gfx_draw_string(TEXT_X, text_y, "..", FOLDER_COLOR); + api->gfx_draw_string(TEXT_X, text_y, "..", FOLDER_COLOR); return; } @@ -250,29 +249,29 @@ static void draw_row(int row) { if (info->is_dir) { append(label, &pos, (int) sizeof(label), "/"); } - gfx_draw_string(TEXT_X, text_y, label, info->is_dir ? FOLDER_COLOR : FILE_COLOR); + api->gfx_draw_string(TEXT_X, text_y, label, info->is_dir ? FOLDER_COLOR : FILE_COLOR); if (info->is_dir) { - gfx_draw_string(SIZE_COLUMN_X, text_y, "folder", FOLDER_COLOR); + api->gfx_draw_string(SIZE_COLUMN_X, text_y, "folder", FOLDER_COLOR); } else { char number[12]; char size_text[24]; int size_pos = 0; size_text[0] = '\0'; - kuitoa(info->size_bytes, number); + api->kuitoa(info->size_bytes, number); append(size_text, &size_pos, (int) sizeof(size_text), number); append(size_text, &size_pos, (int) sizeof(size_text), " bytes"); - gfx_draw_string(SIZE_COLUMN_X, text_y, size_text, FILE_COLOR); + api->gfx_draw_string(SIZE_COLUMN_X, text_y, size_text, FILE_COLOR); } } static void paint(void) { uint32_t band_height = 0; - if (gfx_screen_height() > (uint32_t) (FILES_TOP + FILES_BOTTOM)) { - band_height = gfx_screen_height() - FILES_TOP - FILES_BOTTOM; + if (api->gfx_screen_height() > (uint32_t) (FILES_TOP + FILES_BOTTOM)) { + band_height = api->gfx_screen_height() - FILES_TOP - FILES_BOTTOM; } - gfx_fill_rect(0, FILES_TOP, gfx_screen_width(), band_height, LIST_COLOR); + api->gfx_fill_rect(0, FILES_TOP, api->gfx_screen_width(), band_height, LIST_COLOR); draw_header(); @@ -282,7 +281,7 @@ static void paint(void) { } if (row_count() == 0) { - gfx_draw_string(TEXT_X, list_top() + 6, "(this folder is empty - right-click here to add something)", GFX_WHITE); + api->gfx_draw_string(TEXT_X, list_top() + 6, "(this folder is empty - right-click here to add something)", GFX_WHITE); } draw_footer(); @@ -291,11 +290,11 @@ static void paint(void) { // --- the folder contents --- static void refresh_list(void) { - entry_count = fs_list_dir(current_path, entries); + entry_count = api->fs_list_dir(current_path, entries); if (entry_count < 0) { current_path[0] = '\0'; - entry_count = fs_list_dir(current_path, entries); + entry_count = api->fs_list_dir(current_path, entries); set_message("that folder no longer exists - back at the top"); } if (entry_count < 0) { @@ -327,12 +326,12 @@ static void open_path(const char* path, int is_dir) { if (is_dir) { show_folder(path); } else { - launcher_open_file(path); + api->launcher_open_file(path); } } static void forget_target(void) { - int result = fs_delete_file(target_path); + int result = api->fs_delete_file(target_path); if (result == FS_OK) { set_message("forgotten"); @@ -350,7 +349,7 @@ static void start_new_item(prompt_purpose_t purpose) { prompt_purpose = purpose; const char* title = (purpose == PURPOSE_NEW_FOLDER) ? "New folder name:" : "New file name:"; - prompt_open(title, "", FS_MAX_NAME_LEN - 1, "/"); + api->prompt_open(title, "", FS_MAX_NAME_LEN - 1, "/"); } static void finish_new_item(const char* name, int is_folder) { @@ -362,13 +361,13 @@ static void finish_new_item(const char* name, int is_folder) { int result; if (is_folder) { - result = fs_make_folder(path); + result = api->fs_make_folder(path); } else { fs_info_t existing; - if (fs_stat(path, &existing) == FS_OK) { + if (api->fs_stat(path, &existing) == FS_OK) { result = FS_ERR_EXISTS; } else { - result = fs_write_file(path, (const uint8_t*) "", 0); + result = api->fs_write_file(path, (const uint8_t*) "", 0); } } @@ -399,14 +398,14 @@ static void start_rename(void) { prompt_purpose = PURPOSE_RENAME; - prompt_open(title, target_name, FS_MAX_NAME_LEN - 1, "/"); + api->prompt_open(title, target_name, FS_MAX_NAME_LEN - 1, "/"); } static void finish_rename(const char* new_name) { - if (kstrcmp(new_name, target_name) == 0) { + if (api->kstrcmp(new_name, target_name) == 0) { set_message("name unchanged"); } else { - int result = fs_rename(target_path, new_name); + int result = api->fs_rename(target_path, new_name); if (result == FS_OK) { set_message("renamed"); @@ -434,19 +433,19 @@ static void show_properties(void) { if (target_is_dir) { fs_info_t inside[FS_MAX_FILES]; - int count = fs_list_dir(target_path, inside); + int count = api->fs_list_dir(target_path, inside); if (count < 0) { count = 0; } - kuitoa((uint32_t) count, number); + api->kuitoa((uint32_t) count, number); append(message, &pos, MESSAGE_MAX, ": folder, "); append(message, &pos, MESSAGE_MAX, number); append(message, &pos, MESSAGE_MAX, (count == 1) ? " item" : " items"); } else { fs_info_t info; - if (fs_stat(target_path, &info) == FS_OK) { - kuitoa(info.size_bytes, number); + if (api->fs_stat(target_path, &info) == FS_OK) { + api->kuitoa(info.size_bytes, number); append(message, &pos, MESSAGE_MAX, ": file, "); append(message, &pos, MESSAGE_MAX, number); append(message, &pos, MESSAGE_MAX, " bytes"); @@ -460,20 +459,20 @@ static void show_properties(void) { // --- the app_t slots --- -void files_start(void) { +static void files_start(void) { current_path[0] = '\0'; clear_message(); refresh_list(); paint(); } -void files_redraw(void) { +static void files_redraw(void) { clear_message(); refresh_list(); paint(); } -void files_handle_char(char c) { +static void files_handle_char(char c) { if (c == '\b') { if (has_parent_row()) { go_up(); @@ -481,7 +480,7 @@ void files_handle_char(char c) { } } -void files_handle_click(int32_t x, int32_t y) { +static void files_handle_click(int32_t x, int32_t y) { (void) x; int row = row_at(y); @@ -505,12 +504,12 @@ void files_handle_click(int32_t x, int32_t y) { open_path(path, entries[entry].is_dir); } -void files_handle_right_click(int32_t x, int32_t y) { +static void files_handle_right_click(int32_t x, int32_t y) { int row = row_at(y); if (row < 0) { if (y >= (int32_t) list_top() && y < (int32_t) footer_y()) { active_menu = MENU_KIND_BACKGROUND; - menu_open(x, y, new_menu_labels, NEW_ACTION_COUNT); + api->menu_open(x, y, new_menu_labels, NEW_ACTION_COUNT); } return; } @@ -532,10 +531,10 @@ void files_handle_right_click(int32_t x, int32_t y) { append(target_name, &name_pos, FS_MAX_NAME_LEN, entries[entry].name); active_menu = MENU_KIND_ITEM; - menu_open(x, y, menu_labels, ACTION_COUNT); + api->menu_open(x, y, menu_labels, ACTION_COUNT); } -void files_handle_menu_pick(int index) { +static void files_handle_menu_pick(int index) { if (active_menu == MENU_KIND_BACKGROUND) { if (index == NEW_FOLDER) { start_new_item(PURPOSE_NEW_FOLDER); @@ -556,7 +555,7 @@ void files_handle_menu_pick(int index) { } } -void files_handle_prompt_done(const char* text) { +static void files_handle_prompt_done(const char* text) { if (prompt_purpose == PURPOSE_RENAME) { finish_rename(text); } else if (prompt_purpose == PURPOSE_NEW_FOLDER) { @@ -567,3 +566,22 @@ void files_handle_prompt_done(const char* text) { prompt_purpose = PURPOSE_NONE; } + +// --- loader entry point --- + +int app_entry(const vigil_api_t* kernel_api, app_t* out_app) { + if (kernel_api->version != VIGIL_API_VERSION || kernel_api->struct_size < sizeof(vigil_api_t)) { + return 1; + } + api = kernel_api; + + out_app->name = "Files"; + out_app->start = files_start; + out_app->redraw = files_redraw; + out_app->on_key = files_handle_char; + out_app->on_click = files_handle_click; + out_app->on_right_click = files_handle_right_click; + out_app->on_menu_pick = files_handle_menu_pick; + out_app->on_prompt_done = files_handle_prompt_done; + return 0; +} diff --git a/apps/files/files.h b/apps/files/files.h deleted file mode 100644 index adca905..0000000 --- a/apps/files/files.h +++ /dev/null @@ -1,19 +0,0 @@ -// apps/files/files.h - -#ifndef FILES_H -#define FILES_H -#include - -void files_start(void); -void files_redraw(void); - -void files_handle_char(char c); - -void files_handle_click(int32_t x, int32_t y); -void files_handle_right_click(int32_t x, int32_t y); - -void files_handle_menu_pick(int index); - -void files_handle_prompt_done(const char* text); - -#endif \ No newline at end of file diff --git a/apps/hello/hello.c b/apps/hello/hello.c new file mode 100644 index 0000000..332435b --- /dev/null +++ b/apps/hello/hello.c @@ -0,0 +1,76 @@ +// apps/hello/hello.c + +#include "app.h" +#include "api.h" +#include "font.h" +#include "title_bar.h" +#include "taskbar.h" + +#define TEXT_X 40 + +static const vigil_api_t* api = 0; + +static int clicks = 0; +static button_t click_button; + +static void paint(void) { + uint32_t band = api->gfx_screen_height() - TITLE_BAR_HEIGHT - TASKBAR_HEIGHT; + api->gfx_fill_rect(0, TITLE_BAR_HEIGHT, api->gfx_screen_width(), band, GFX_BLACK); + + api->gfx_draw_string(TEXT_X, TITLE_BAR_HEIGHT + 40, "Hello from a loaded app!", GFX_GREEN); + api->gfx_draw_string(TEXT_X, TITLE_BAR_HEIGHT + 64, "I live in a file on the disk, not in the kernel.", GFX_WHITE); + + char number[12]; + api->kuitoa((uint32_t) clicks, number); + api->gfx_draw_string(TEXT_X, TITLE_BAR_HEIGHT + 104, "Clicks: ", GFX_WHITE); + api->gfx_draw_string(TEXT_X + 8 * FONT_WIDTH, TITLE_BAR_HEIGHT + 104, number, GFX_WHITE); + + api->button_draw(&click_button); +} + +static void hello_start(void) { + clicks = 0; + + click_button.x = TEXT_X; + click_button.y = TITLE_BAR_HEIGHT + 144; + click_button.width = 200; + click_button.height = 48; + click_button.label = "Click me"; + click_button.color = ((gfx_color_t){0x30, 0x70, 0x30}); + click_button.on_click = 0; + + paint(); +} + +static void hello_redraw(void) { + paint(); +} + +static void hello_on_key(char c) { + if (c == 'r') { + api->mouse_hide_cursor(); + clicks = 0; + paint(); + } +} + +static void hello_on_click(int32_t x, int32_t y) { + if (api->button_find_at(&click_button, 1, x, y) >= 0) { + clicks++; + paint(); + } +} + +int app_entry(const vigil_api_t* kernel_api, app_t* out_app) { + if (kernel_api->version != VIGIL_API_VERSION || kernel_api->struct_size < sizeof(vigil_api_t)) { + return 1; + } + api = kernel_api; + + out_app->name = "Hello"; + out_app->start = hello_start; + out_app->redraw = hello_redraw; + out_app->on_key = hello_on_key; + out_app->on_click = hello_on_click; + return 0; +} diff --git a/apps/launcher/app.h b/apps/launcher/app.h index 7d51441..9efd828 100644 --- a/apps/launcher/app.h +++ b/apps/launcher/app.h @@ -18,6 +18,8 @@ typedef struct { void (*on_menu_pick)(int index); void (*on_prompt_done)(const char* text); + + void (*on_open_file)(const char* path); } app_t; #endif diff --git a/apps/launcher/launcher.c b/apps/launcher/launcher.c index 6f7b73b..a0b935a 100644 --- a/apps/launcher/launcher.c +++ b/apps/launcher/launcher.c @@ -14,11 +14,8 @@ #include "menu.h" #include "fs.h" #include "prompt.h" - +#include "loader.h" #include "shell.h" -#include "notepad.h" -#include "files.h" -#include "calculator.h" // --- home screen layout (px) --- @@ -45,16 +42,19 @@ static void start_terminal(void) { shell_init(); } -static const app_t apps[] = { - { "Terminal", start_terminal, terminal_redraw, shell_handle_char, terminal_update_cursor, 0, 0, 0, 0 }, - { "Notepad", notepad_start, notepad_redraw, notepad_handle_char, notepad_update_cursor, notepad_handle_click, 0, 0, 0 }, - { "Files", files_start, files_redraw, files_handle_char, 0, files_handle_click, files_handle_right_click, files_handle_menu_pick, files_handle_prompt_done }, - { "Calculator", calculator_start, calculator_redraw, calculator_handle_char, 0, calculator_handle_click, 0, 0, 0 }, +static const app_t builtin_apps[] = { + { "Terminal", start_terminal, terminal_redraw, shell_handle_char, terminal_update_cursor }, }; -#define APP_COUNT ((int) (sizeof(apps) / sizeof(apps[0]))) +#define BUILTIN_COUNT ((int) (sizeof(builtin_apps) / sizeof(builtin_apps[0]))) +#define MAX_APPS TASKBAR_MAX_ITEMS + +typedef char builtin_apps_must_fit[(BUILTIN_COUNT <= MAX_APPS) ? 1 : -1]; -static button_t home_buttons[APP_COUNT]; +static app_t apps[MAX_APPS]; +static int app_count = 0; + +static button_t home_buttons[MAX_APPS]; // --- state --- @@ -64,13 +64,13 @@ typedef enum { APP_STATE_MINIMIZED, } app_state_t; -static app_state_t app_state[APP_COUNT]; +static app_state_t app_state[MAX_APPS]; static const app_t* volatile running_app = 0; -static char home_labels[APP_COUNT][HOME_LABEL_MAX]; +static char home_labels[MAX_APPS][HOME_LABEL_MAX]; -static int taskbar_slot_app[APP_COUNT]; +static int taskbar_slot_app[MAX_APPS]; // --- helpers --- @@ -98,6 +98,49 @@ static void build_home_label(int index) { out[pos] = '\0'; } +static void copy_app(app_t* dest, const app_t* src) { + dest->name = src->name; + dest->start = src->start; + dest->redraw = src->redraw; + dest->on_key = src->on_key; + dest->on_tick = src->on_tick; + dest->on_click = src->on_click; + dest->on_right_click = src->on_right_click; + dest->on_menu_pick = src->on_menu_pick; + dest->on_prompt_done = src->on_prompt_done; + dest->on_open_file = src->on_open_file; +} + +static void place_home_button(int index) { + uint32_t button_x = 0; + if (gfx_screen_width() > HOME_BUTTON_WIDTH) { + button_x = (gfx_screen_width() - HOME_BUTTON_WIDTH) / 2; + } + + home_buttons[index].x = button_x; + home_buttons[index].y = HOME_FIRST_BUTTON_Y + (uint32_t) index * (HOME_BUTTON_HEIGHT + HOME_BUTTON_GAP); + home_buttons[index].width = HOME_BUTTON_WIDTH; + home_buttons[index].height = HOME_BUTTON_HEIGHT; + home_buttons[index].label = home_labels[index]; + home_buttons[index].color = HOME_BUTTON_COLOR; + home_buttons[index].on_click = 0; +} + +int launcher_register_app(const app_t* app) { + if (app == 0 || app_count >= MAX_APPS) { + return -1; + } + + int index = app_count; + + copy_app(&apps[index], app); + app_state[index] = APP_STATE_STOPPED; + place_home_button(index); + + app_count++; + return index; +} + // --- drawing --- static void draw_centered_string(uint32_t y, const char* text, gfx_color_t color) { @@ -110,10 +153,10 @@ static void draw_centered_string(uint32_t y, const char* text, gfx_color_t color } static void draw_taskbar(void) { - taskbar_item_t items[APP_COUNT]; + taskbar_item_t items[MAX_APPS]; int count = 0; - for (int i = 0; i < APP_COUNT; i++) { + for (int i = 0; i < app_count; i++) { if (app_state[i] == APP_STATE_STOPPED) { continue; } @@ -133,7 +176,7 @@ static void draw_home_screen(void) { draw_centered_string(HOME_TITLE_Y, HOME_TITLE, GFX_GREEN); draw_taskbar(); - for (int i = 0; i < APP_COUNT; i++) { + for (int i = 0; i < app_count; i++) { build_home_label(i); button_draw(&home_buttons[i]); } @@ -212,7 +255,7 @@ static char pending_open_path[FS_MAX_PATH]; static int open_pending = 0; static int find_app_index(const char* name) { - for (int i = 0; i < APP_COUNT; i++) { + for (int i = 0; i < app_count; i++) { if (kstrcmp(apps[i].name, name) == 0) { return i; } @@ -242,12 +285,12 @@ static void process_pending_open(void) { open_pending = 0; int index = find_app_index("Notepad"); - if (index < 0) { + if (index < 0 || apps[index].on_open_file == 0) { return; } bring_to_front(index); - notepad_open(pending_open_path); + apps[index].on_open_file(pending_open_path); } void launcher_open_file(const char* path) { @@ -353,18 +396,13 @@ static int click_is_in_app_band(int32_t py) { } void launcher_init(void) { - uint32_t button_x = (gfx_screen_width() - HOME_BUTTON_WIDTH) / 2; + app_count = 0; - for (int i = 0; i < APP_COUNT; i++) { - home_buttons[i].x = button_x; - home_buttons[i].y = HOME_FIRST_BUTTON_Y + (uint32_t) i * (HOME_BUTTON_HEIGHT + HOME_BUTTON_GAP); - home_buttons[i].width = HOME_BUTTON_WIDTH; - home_buttons[i].height = HOME_BUTTON_HEIGHT; - home_buttons[i].label = home_labels[i]; - home_buttons[i].color = HOME_BUTTON_COLOR; - home_buttons[i].on_click = 0; + for (int i = 0; i < BUILTIN_COUNT; i++) { + launcher_register_app(&builtin_apps[i]); } + loader_load_folder(LOADER_APP_FOLDER); show_home_screen(); } @@ -432,7 +470,7 @@ void launcher_update(void) { } if (clicked) { - int index = button_find_at(home_buttons, APP_COUNT, mouse_x, mouse_y); + int index = button_find_at(home_buttons, app_count, mouse_x, mouse_y); if (index >= 0) { launch_app(index); } diff --git a/apps/launcher/launcher.h b/apps/launcher/launcher.h index 240ef19..0bee343 100644 --- a/apps/launcher/launcher.h +++ b/apps/launcher/launcher.h @@ -3,10 +3,14 @@ #ifndef LAUNCHER_H #define LAUNCHER_H +#include "app.h" + void launcher_init(void); void launcher_update(void); void launcher_open_file(const char* path); +int launcher_register_app(const app_t* app); + #endif diff --git a/apps/notepad/notepad.c b/apps/notepad/notepad.c index c5a8188..8c4f0cf 100644 --- a/apps/notepad/notepad.c +++ b/apps/notepad/notepad.c @@ -1,14 +1,15 @@ // apps/notepad/notepad.c -#include "notepad.h" -#include "title_bar.h" -#include "taskbar.h" -#include "graphics.h" +#include "app.h" +#include "api.h" #include "font.h" -#include "kstring.h" -#include "fs.h" -#include "timer.h" #include "keyboard.h" +#include "title_bar.h" +#include "taskbar.h" + +// --- api pointer --- + +static const vigil_api_t* api = 0; // --- settings --- @@ -71,11 +72,11 @@ static char wanted[NOTEPAD_MAX_ROWS][NOTEPAD_MAX_COLS]; static void compute_layout(void) { uint32_t used = NOTEPAD_TOP + NOTEPAD_BOTTOM; uint32_t band_height = 0; - if (gfx_screen_height() > used) { - band_height = gfx_screen_height() - used; + if (api->gfx_screen_height() > used) { + band_height = api->gfx_screen_height() - used; } - text_cols = (int) (gfx_screen_width() / FONT_WIDTH); + text_cols = (int) (api->gfx_screen_width() / FONT_WIDTH); text_rows = (int) (band_height / FONT_HEIGHT); if (text_cols < 1) { @@ -181,7 +182,7 @@ static void update_cursor_position(void) { // --- drawing --- static void paint_cursor_bar(gfx_color_t color) { - gfx_fill_rect( + api->gfx_fill_rect( cell_x(cursor_col), cell_y(cursor_row) + (FONT_HEIGHT - CURSOR_BAR_HEIGHT), FONT_WIDTH, @@ -193,7 +194,7 @@ static void paint_cursor_bar(gfx_color_t color) { static void show_cursor(void) { cursor_blink_on = 1; paint_cursor_bar(NOTE_FG); - last_blink_tick = timer_get_ticks(); + last_blink_tick = api->timer_get_ticks(); } static void hide_cursor(void) { @@ -201,7 +202,7 @@ static void hide_cursor(void) { paint_cursor_bar(NOTE_BG); if (cursor_index < length && text[cursor_index] != '\n') { - gfx_draw_char(cell_x(cursor_col), cell_y(cursor_row), text[cursor_index], NOTE_FG); + api->gfx_draw_char(cell_x(cursor_col), cell_y(cursor_row), text[cursor_index], NOTE_FG); } } @@ -215,7 +216,7 @@ static void append_text(char* line, int* pos, const char* piece) { static void draw_status(void) { uint32_t y = cell_y(text_rows - STATUS_ROWS); - gfx_fill_rect(0, y, gfx_screen_width(), FONT_HEIGHT, STATUS_BG); + api->gfx_fill_rect(0, y, api->gfx_screen_width(), FONT_HEIGHT, STATUS_BG); char line[STATUS_LINE_MAX]; char number[12]; @@ -225,21 +226,21 @@ static void draw_status(void) { append_text(line, &pos, file_path); append_text(line, &pos, " | Ctrl+S: save | "); - kuitoa((uint32_t) length, number); + api->kuitoa((uint32_t) length, number); append_text(line, &pos, number); append_text(line, &pos, " / "); - kuitoa(NOTEPAD_MAX_BYTES, number); + api->kuitoa(NOTEPAD_MAX_BYTES, number); append_text(line, &pos, number); append_text(line, &pos, " bytes | "); append_text(line, &pos, status_note); - gfx_draw_string(STATUS_TEXT_X, y, line, NOTE_FG); + api->gfx_draw_string(STATUS_TEXT_X, y, line, NOTE_FG); } static void draw_cell(int col, int row, char c) { - gfx_draw_char_bg(cell_x(col), cell_y(row), c, NOTE_FG, NOTE_BG); + api->gfx_draw_char_bg(cell_x(col), cell_y(row), c, NOTE_FG, NOTE_BG); } static void reset_shown(void) { @@ -282,9 +283,9 @@ static void refresh_text(void) { } static void paint_screen(void) { - gfx_fill_rect( + api->gfx_fill_rect( 0, NOTEPAD_TOP, - gfx_screen_width(), (uint32_t) text_rows * FONT_HEIGHT, + api->gfx_screen_width(), (uint32_t) text_rows * FONT_HEIGHT, NOTE_BG ); @@ -309,12 +310,12 @@ static void set_file_path(const char* path) { static int file_still_exists(void) { fs_info_t info; - return fs_stat(file_path, &info) == FS_OK; + return api->fs_stat(file_path, &info) == FS_OK; } static int load_file(const char* path) { uint32_t size = 0; - int result = fs_read_file(path, (uint8_t*) incoming, NOTEPAD_MAX_BYTES, &size); + int result = api->fs_read_file(path, (uint8_t*) incoming, NOTEPAD_MAX_BYTES, &size); if (result == FS_ERR_NOT_FOUND) { length = 0; @@ -363,7 +364,7 @@ static void save_note(void) { } recreate_armed = 0; - int result = fs_write_file(file_path, (const uint8_t*) text, (uint32_t) length); + int result = api->fs_write_file(file_path, (const uint8_t*) text, (uint32_t) length); if (result == FS_OK) { status_note = "saved"; @@ -527,9 +528,38 @@ static void move_down(void) { } } -// --- pub funcs (the app_t slots) --- +// --- opening a specific file --- + +static int open_file(const char* path) { + if (dirty) { + status_note = "unsaved changes - press Ctrl+S, then try again"; + draw_status(); + return 0; + } + + if (!load_file(path)) { + draw_status(); + return 0; + } + + set_file_path(path); + dirty = 0; + save_allowed = 1; + recreate_armed = 0; + + cursor_index = length; + paint_screen(); + desired_col = cursor_col; + return 1; +} + +static void notepad_open_file(const char* path) { + open_file(path); +} -void notepad_start(void) { +// --- the app_t slots --- + +static void notepad_start(void) { compute_layout(); set_file_path(NOTEPAD_DEFAULT_FILE); dirty = 0; @@ -545,7 +575,7 @@ void notepad_start(void) { desired_col = cursor_col; } -void notepad_redraw(void) { +static void notepad_redraw(void) { compute_layout(); if (file_on_disk && !file_still_exists()) { @@ -555,30 +585,7 @@ void notepad_redraw(void) { paint_screen(); } -int notepad_open(const char* path) { - if (dirty) { - status_note = "unsaved changes - press Ctrl+S, then try again"; - draw_status(); - return 0; - } - - if (!load_file(path)) { - draw_status(); - return 0; - } - - set_file_path(path); - dirty = 0; - save_allowed = 1; - recreate_armed = 0; - - cursor_index = length; - paint_screen(); - desired_col = cursor_col; - return 1; -} - -void notepad_handle_char(char c) { +static void notepad_handle_char(char c) { if (c == KEY_CTRL_S) { save_note(); } else if (c == '\b') { @@ -606,7 +613,7 @@ void notepad_handle_char(char c) { // ignore any other input } -void notepad_handle_click(int32_t x, int32_t y) { +static void notepad_handle_click(int32_t x, int32_t y) { int col = (int) (x / FONT_WIDTH); int row = (int) ((y - NOTEPAD_TOP) / FONT_HEIGHT); @@ -617,8 +624,8 @@ void notepad_handle_click(int32_t x, int32_t y) { move_cursor(index_at(row, col), 0); } -void notepad_update_cursor(void) { - uint32_t frequency = timer_get_frequency(); +static void notepad_update_cursor(void) { + uint32_t frequency = api->timer_get_frequency(); if (frequency == 0) { return; } @@ -628,7 +635,7 @@ void notepad_update_cursor(void) { blink_interval_ticks = 1; } - uint32_t now = timer_get_ticks(); + uint32_t now = api->timer_get_ticks(); if (now - last_blink_tick < blink_interval_ticks) { return; } @@ -640,3 +647,21 @@ void notepad_update_cursor(void) { } last_blink_tick = now; } + +// --- the entry point the loader calls --- + +int app_entry(const vigil_api_t* kernel_api, app_t* out_app) { + if (kernel_api->version != VIGIL_API_VERSION || kernel_api->struct_size < sizeof(vigil_api_t)) { + return 1; + } + api = kernel_api; + + out_app->name = "Notepad"; + out_app->start = notepad_start; + out_app->redraw = notepad_redraw; + out_app->on_key = notepad_handle_char; + out_app->on_tick = notepad_update_cursor; + out_app->on_click = notepad_handle_click; + out_app->on_open_file = notepad_open_file; + return 0; +} diff --git a/apps/notepad/notepad.h b/apps/notepad/notepad.h deleted file mode 100644 index 8e52202..0000000 --- a/apps/notepad/notepad.h +++ /dev/null @@ -1,17 +0,0 @@ -// apps/notepad/notepad.h - -#ifndef NOTEPAD_H -#define NOTEPAD_H -#include - -void notepad_start(void); -void notepad_redraw(void); - -int notepad_open(const char* path); - -void notepad_handle_char(char c); -void notepad_handle_click(int32_t x, int32_t y); - -void notepad_update_cursor(void); - -#endif diff --git a/apps/sdk/app.ld b/apps/sdk/app.ld new file mode 100644 index 0000000..e50916c --- /dev/null +++ b/apps/sdk/app.ld @@ -0,0 +1,41 @@ +/* apps/sdk/app.ld + linker script for loadable VIGIL apps + Build with: ld -T app.ld -Ttext= ... */ + +ENTRY(app_entry) + +SECTIONS +{ + .text : { + __app_start = .; + + /* the 24 byte vapp header, written by linker */ + LONG(0x50504156) /* magic: bytes V A P P */ + LONG(1) /* header format version */ + LONG(__app_start) /* address app was linked at */ + LONG(__image_end - __app_start) /* bytes stored in the file */ + LONG(__memory_end - __app_start) /* bytes needed in ram */ + LONG(app_entry - __app_start) /* where app entry lives */ + + *(.text .text.*) + } + + .rodata : { *(.rodata .rodata.*) } + + .data : { + *(.data .data.*) + . = ALIGN(4); + } + + __image_end = .; + + .bss : { + *(.bss .bss.*) + *(COMMON) + . = ALIGN(4); + } + + __memory_end = .; + + /DISCARD/ : { *(.eh_frame) *(.comment) *(.note*) } +} diff --git a/apps/shell/shell.c b/apps/shell/shell.c index 9a3e2f6..ee622d8 100644 --- a/apps/shell/shell.c +++ b/apps/shell/shell.c @@ -10,6 +10,8 @@ #include "timer.h" #include "heap.h" #include "launcher.h" +#include "api.h" +#include "loader.h" #define INPUT_BUFFER_SIZE 128 #define HISTORY_SIZE 8 @@ -130,7 +132,9 @@ static void execute_command(char* line) { terminal_print(" edit : Open a file in Notepad\n"); terminal_print(" folder : Create a folder\n"); terminal_print(" rename : Rename a file or folder\n"); - terminal_print(" files [folder]: Show what is in a folder\n\n"); + terminal_print(" files [folder]: Show what is in a folder\n"); + terminal_print(" api: Show info about the app API table\n"); + terminal_print(" loadapp : Load an app file from disk\n\n"); return; } @@ -321,6 +325,32 @@ static void execute_command(char* line) { } return; } + + if (kstrcmp(command, "api") == 0) { + const vigil_api_t* api = api_get(); + + kprintf("API version: %d, table size: %d bytes\n", api->version, api->struct_size); + kprintf("kstrlen(\"vigil\") via table: %d\n", api->kstrlen("vigil")); + kprintf("timer ticks via table: %d\n", api->timer_get_ticks()); + return; + } + + if (kstrcmp(command, "loadapp") == 0) { + if (kstrcmp(args, "") == 0) { + terminal_print("Usage: loadapp \n"); + return; + } + + int result = loader_load(args); + if (result == LOADER_OK) { + terminal_print("App loaded - find it on the home screen\n"); + } else { + terminal_print("Load failed: "); + terminal_print(loader_error_text(result)); + terminal_print("\n"); + } + return; + } terminal_print("Unknown command: "); terminal_print(command); diff --git a/boot/linker.ld b/boot/linker.ld index 5a93e87..a5d7b99 100644 --- a/boot/linker.ld +++ b/boot/linker.ld @@ -16,7 +16,6 @@ SECTIONS build/irq.o(.text) build/irq_asm.o(.text) build/keyboard.o(.text) - build/shell.o(.text) build/kstring.o(.text) build/kprintf.o(.text) build/ata.o(.text) @@ -30,13 +29,12 @@ SECTIONS build/button.o(.text) build/title_bar.o(.text) build/taskbar.o(.text) - build/launcher.o(.text) - build/notepad.o(.text) build/menu.o(.text) - build/files.o(.text) build/prompt.o(.text) - build/calc.o(.text) - build/calculator.o(.text) + build/vigil_api.o(.text) + build/loader.o(.text) + build/launcher.o(.text) + build/shell.o(.text) } .rodata : { @@ -51,7 +49,6 @@ SECTIONS build/irq.o(.rodata) build/irq_asm.o(.rodata) build/keyboard.o(.rodata) - build/shell.o(.rodata) build/kstring.o(.rodata) build/kprintf.o(.rodata) build/ata.o(.rodata) @@ -65,13 +62,12 @@ SECTIONS build/button.o(.rodata) build/title_bar.o(.rodata) build/taskbar.o(.rodata) - build/launcher.o(.rodata) - build/notepad.o(.rodata) build/menu.o(.rodata) - build/files.o(.rodata) build/prompt.o(.rodata) - build/calc.o(.rodata) - build/calculator.o(.rodata) + build/vigil_api.o(.rodata) + build/loader.o(.rodata) + build/launcher.o(.rodata) + build/shell.o(.rodata) } .data : { @@ -86,7 +82,6 @@ SECTIONS build/irq.o(.data) build/irq_asm.o(.data) build/keyboard.o(.data) - build/shell.o(.data) build/kstring.o(.data) build/kprintf.o(.data) build/ata.o(.data) @@ -100,13 +95,12 @@ SECTIONS build/button.o(.data) build/title_bar.o(.data) build/taskbar.o(.data) - build/launcher.o(.data) - build/notepad.o(.data) build/menu.o(.data) - build/files.o(.data) build/prompt.o(.data) - build/calc.o(.data) - build/calculator.o(.data) + build/vigil_api.o(.data) + build/loader.o(.data) + build/launcher.o(.data) + build/shell.o(.data) } .bss : { @@ -122,7 +116,6 @@ SECTIONS build/irq.o(.bss) build/irq_asm.o(.bss) build/keyboard.o(.bss) - build/shell.o(.bss) build/kstring.o(.bss) build/kprintf.o(.bss) build/ata.o(.bss) @@ -136,13 +129,12 @@ SECTIONS build/button.o(.bss) build/title_bar.o(.bss) build/taskbar.o(.bss) - build/launcher.o(.bss) - build/notepad.o(.bss) build/menu.o(.bss) - build/files.o(.bss) build/prompt.o(.bss) - build/calc.o(.bss) - build/calculator.o(.bss) + build/vigil_api.o(.bss) + build/loader.o(.bss) + build/launcher.o(.bss) + build/shell.o(.bss) __bss_end = .; } } diff --git a/kernel/vigil/api.c b/kernel/vigil/api.c new file mode 100644 index 0000000..7346951 --- /dev/null +++ b/kernel/vigil/api.c @@ -0,0 +1,66 @@ +// kernel/vigil/api.c + +#include "api.h" +#include "graphics.h" +#include "mouse.h" +#include "button.h" +#include "kstring.h" +#include "fs.h" +#include "timer.h" +#include "heap.h" +#include "menu.h" +#include "prompt.h" +#include "launcher.h" + +// The table itself which is filled in at compile time +// +// "const" puts the table in rodata, and because its built by the +// compiler theres no setup code to run so nothing can forget to +// initialize it +static const vigil_api_t api = { + .version = VIGIL_API_VERSION, + .struct_size = sizeof(vigil_api_t), + + .gfx_clear = gfx_clear, + .gfx_put_pixel = gfx_put_pixel, + .gfx_get_pixel = gfx_get_pixel, + .gfx_draw_char = gfx_draw_char, + .gfx_draw_char_bg = gfx_draw_char_bg, + .gfx_draw_string = gfx_draw_string, + .gfx_fill_rect = gfx_fill_rect, + .gfx_draw_rect_outline = gfx_draw_rect_outline, + .gfx_screen_width = gfx_screen_width, + .gfx_screen_height = gfx_screen_height, + + .mouse_hide_cursor = mouse_hide_cursor, + + .button_draw = button_draw, + .button_find_at = button_find_at, + + .kstrlen = kstrlen, + .kstrcmp = kstrcmp, + .kuitoa = kuitoa, + .kitoa = kitoa, + + .fs_write_file = fs_write_file, + .fs_read_file = fs_read_file, + .fs_delete_file = fs_delete_file, + .fs_make_folder = fs_make_folder, + .fs_rename = fs_rename, + .fs_stat = fs_stat, + .fs_list_dir = fs_list_dir, + + .timer_get_ticks = timer_get_ticks, + .timer_get_frequency = timer_get_frequency, + + .kmalloc = kmalloc, + .kfree = kfree, + + .menu_open = menu_open, + .prompt_open = prompt_open, + .launcher_open_file = launcher_open_file, +}; + +const vigil_api_t* api_get(void) { + return &api; +} diff --git a/kernel/vigil/api.h b/kernel/vigil/api.h new file mode 100644 index 0000000..56077af --- /dev/null +++ b/kernel/vigil/api.h @@ -0,0 +1,91 @@ +// kernel/vigil/api.h +// +// The "kernel API table": a list of pointers to kernel functions that +// loaded apps can call. +// +// A loaded app is compiled separately from kernel, so it doesnt know +// where kernel functions are in memory (bc their addresses change every +// build) Instead the kernel hands app a pointer to this table and the +// app calls everything through it, e.g. +// api->gfx_fill_rect(10, 10, 50, 50, color); +// +// (Windows and Linux solve the same problem with system calls) + +#ifndef VIGIL_API_H +#define VIGIL_API_H + +#include +#include +#include "graphics.h" +#include "button.h" +#include "fs.h" +#include "menu.h" +#include "prompt.h" +#include "launcher.h" + +// bumped whenever the table changes such that old apps cant gracefully handle +#define VIGIL_API_VERSION 1 + +// RULE FOR FUTURE: only ever add new entries at the END of this struct, as +// apps built against older versions expect every existing entry to stay in +// the same position and moving one would make them call the wrong function +typedef struct { + uint32_t version; // VIGIL_API_VERSION + uint32_t struct_size; // sizeof(vigil_api_t); lets an app check the table is big enough + + // --- graphics --- + void (*gfx_clear)(gfx_color_t color); + void (*gfx_put_pixel)(uint32_t x, uint32_t y, gfx_color_t color); + gfx_color_t (*gfx_get_pixel)(uint32_t x, uint32_t y); + void (*gfx_draw_char)(uint32_t x, uint32_t y, char c, gfx_color_t color); + void (*gfx_draw_char_bg)(uint32_t x, uint32_t y, char c, gfx_color_t fg, gfx_color_t bg); + void (*gfx_draw_string)(uint32_t x, uint32_t y, const char* str, gfx_color_t color); + void (*gfx_fill_rect)(uint32_t x, uint32_t y, uint32_t width, uint32_t height, gfx_color_t color); + void (*gfx_draw_rect_outline)(uint32_t x, uint32_t y, uint32_t width, uint32_t height, gfx_color_t color); + uint32_t (*gfx_screen_width)(void); + uint32_t (*gfx_screen_height)(void); + + // --- mouse --- + void (*mouse_hide_cursor)(void); + + // --- buttons --- + void (*button_draw)(const button_t* button); + int (*button_find_at)(const button_t* buttons, int count, int32_t px, int32_t py); + + // --- strings --- + uint32_t (*kstrlen)(const char* str); + int (*kstrcmp)(const char* a, const char* b); + void (*kuitoa)(uint32_t value, char* buffer); + void (*kitoa)(int32_t value, char* buffer); + + // --- filesystem --- + int (*fs_write_file)(const char* path, const uint8_t* data, uint32_t size); + int (*fs_read_file)(const char* path, uint8_t* buffer, uint32_t buffer_size, uint32_t* out_size); + int (*fs_delete_file)(const char* path); + int (*fs_make_folder)(const char* path); + int (*fs_rename)(const char* path, const char* new_name); + int (*fs_stat)(const char* path, fs_info_t* out); + int (*fs_list_dir)(const char* path, fs_info_t out[FS_MAX_FILES]); + + // --- timer --- + uint32_t (*timer_get_ticks)(void); + uint32_t (*timer_get_frequency)(void); + + // --- heap --- + void* (*kmalloc)(size_t size); + void (*kfree)(void* ptr); + + // --- menu (right-click popup) --- + void (*menu_open)(int32_t x, int32_t y, const char* const* labels, int count); + + // --- prompt (name-entry box) --- + void (*prompt_open)(const char* title, const char* initial_text, int max_length, const char* blocked_chars); + + // --- launcher --- + void (*launcher_open_file)(const char* path); +} vigil_api_t; + +// returns the shared table +const vigil_api_t* api_get(void); + +#endif diff --git a/kernel/vigil/app_format.h b/kernel/vigil/app_format.h new file mode 100644 index 0000000..0cbd727 --- /dev/null +++ b/kernel/vigil/app_format.h @@ -0,0 +1,37 @@ +// kernel/vigil/app_format.h + +// What a loadable VIGIL app file ('vapp') looks like, and where in ram +// apps are allowed to live + +#ifndef VIGIL_APP_FORMAT_H +#define VIGIL_APP_FORMAT_H +#include + +// the first 4 bytes of every app file spell "VAPP" in ascii +// (V=0x56 A=0x41 P=0x50 P=0x50) +#define VAPP_MAGIC 0x50504156 +#define VAPP_FORMAT_VERSION 1 + +// --- RAM slots --- + +// each loaded app gets a fixed size block of RAM (a "slot") an app is +// built for ONE specific slot address, so no address patching is needed +// The heap is 0x200000-0x2fffff, so slots start just above that +// slot 0: 0x400000 slot 1: 0x440000 slot 2: 0x480000 slot 3: 0x4c0000 +// slot 4: 0x500000 slot 5: 0x540000 slot 6: 0x580000 slot 7: 0x5c0000 +#define LOADER_SLOTS_BASE 0x400000 +#define LOADER_SLOT_SIZE 0x40000 // 256 KB per app +#define LOADER_SLOT_COUNT 8 + +// the 24 bytes at the very start of an app file, the linker writes this +// (see apps/sdk/app.ld); apps never fill it in themselves +typedef struct { + uint32_t magic; // must be VAPP_MAGIC + uint32_t format_version; // must be VAPP_FORMAT_VERSION + uint32_t load_address; // the address the app was built to run at + uint32_t file_size; // bytes in the file (header included) + uint32_t memory_size; // bytes needed in RAM: file + zeroed .bss area + uint32_t entry_offset; // distance from the start to app_entry() +} app_header_t; + +#endif diff --git a/kernel/vigil/loader.c b/kernel/vigil/loader.c new file mode 100644 index 0000000..09edaa8 --- /dev/null +++ b/kernel/vigil/loader.c @@ -0,0 +1,188 @@ +// kernel/vigil/loader.c + +#include "loader.h" +#include "app_format.h" +#include "api.h" +#include "app.h" +#include "fs.h" +#include "heap.h" +#include "kstring.h" +#include "launcher.h" + +typedef int (*app_entry_fn)(const vigil_api_t* api, app_t* out_app); +static int slot_used[LOADER_SLOT_COUNT]; + +// --- slots --- + +static uint32_t slot_address(int slot) { + return LOADER_SLOTS_BASE + (uint32_t) slot * LOADER_SLOT_SIZE; +} + +static int slot_for_address(uint32_t address) { + for (int i = 0; i < LOADER_SLOT_COUNT; i++) { + if (slot_address(i) == address) { + return i; + } + } + return -1; +} + +// --- checking the file --- + +static int check_header(const app_header_t* header, uint32_t file_size, int* slot_out) { + if (header->magic != VAPP_MAGIC) { + return LOADER_ERR_BAD_MAGIC; + } + if (header->format_version != VAPP_FORMAT_VERSION) { + return LOADER_ERR_BAD_VERSION; + } + + int slot = slot_for_address(header->load_address); + if (slot < 0) { + return LOADER_ERR_BAD_LAYOUT; + } + if (header->file_size != file_size) { + return LOADER_ERR_BAD_LAYOUT; + } + if (header->memory_size < header->file_size || header->memory_size > LOADER_SLOT_SIZE) { + return LOADER_ERR_BAD_LAYOUT; + } + if (header->entry_offset < sizeof(app_header_t) || header->entry_offset >= header->file_size) { + return LOADER_ERR_BAD_LAYOUT; + } + if (slot_used[slot]) { + return LOADER_ERR_SLOT_BUSY; + } + + *slot_out = slot; + return LOADER_OK; +} + +// --- placing app in memory --- + +static void copy_into_slot(uint32_t address, const uint8_t* file, uint32_t file_size, uint32_t memory_size) { + uint8_t* dest = (uint8_t*) address; + + for (uint32_t i = 0; i < file_size; i++) { + dest[i] = file[i]; + } + for (uint32_t i = file_size; i < memory_size; i++) { + dest[i] = 0; + } +} + +static void clear_app(app_t* app) { + uint8_t* bytes = (uint8_t*) app; + for (uint32_t i = 0; i < sizeof(app_t); i++) { + bytes[i] = 0; + } +} + +// --- public funcs --- + +int loader_load(const char* path) { + fs_info_t info; + if (fs_stat(path, &info) != FS_OK || info.is_dir) { + return LOADER_ERR_READ; + } + + uint32_t size = info.size_bytes; + if (size < sizeof(app_header_t)) { + return LOADER_ERR_BAD_MAGIC; + } + if (size > LOADER_SLOT_SIZE) { + return LOADER_ERR_TOO_BIG; + } + + uint8_t* temp = (uint8_t*) kmalloc(size); + if (temp == 0) { + return LOADER_ERR_NO_MEMORY; + } + + uint32_t read_size = 0; + int result = fs_read_file(path, temp, size, &read_size); + if (result != FS_OK || read_size != size) { + kfree(temp); + return LOADER_ERR_READ; + } + + int slot = 0; + const app_header_t* header = (const app_header_t*) temp; + result = check_header(header, size, &slot); + if (result != LOADER_OK) { + kfree(temp); + return result; + } + + uint32_t address = slot_address(slot); + uint32_t memory_size = header->memory_size; + uint32_t entry_offset = header->entry_offset; + + copy_into_slot(address, temp, size, memory_size); + kfree(temp); + + app_t app; + clear_app(&app); + slot_used[slot] = 1; + + app_entry_fn entry = (app_entry_fn) (address + entry_offset); + if (entry(api_get(), &app) != 0 || app.name == 0 || app.start == 0) { + slot_used[slot] = 0; + return LOADER_ERR_ENTRY_FAILED; + } + + if (launcher_register_app(&app) < 0) { + slot_used[slot] = 0; + return LOADER_ERR_LAUNCHER_FULL; + } + + return LOADER_OK; +} + +static int join_path(const char* folder, const char* name, char* out) { + uint32_t needed = kstrlen(folder) + 1 + kstrlen(name); + if (needed >= FS_MAX_PATH) return 0; + + int pos = 0; + for (int i = 0; folder[i] != '\0'; i++) { + out[pos++] = folder[i]; + } + out[pos++] = '/'; + for (int i = 0; name[i] != '\0'; i++) { + out[pos++] = name[i]; + } + out[pos] = '\0'; + return 1; +} + +int loader_load_folder(const char* folder) { + fs_info_t entries[FS_MAX_FILES]; + + int count = fs_list_dir(folder, entries); + if (count < 0) return 0; + + int loaded = 0; + for (int i = 0; i < count; i++) { + if (entries[i].is_dir) continue; + char path[FS_MAX_PATH]; + if (!join_path(folder, entries[i].name, path)) continue; + if (loader_load(path) == LOADER_OK) loaded++; + } + return loaded; +} + +const char* loader_error_text(int code) { + switch (code) { + case LOADER_OK: return "ok"; + case LOADER_ERR_READ: return "cannot find or read that file"; + case LOADER_ERR_TOO_BIG: return "file is bigger than one app slot (256 KB)"; + case LOADER_ERR_BAD_MAGIC: return "not a VIGIL app file"; + case LOADER_ERR_BAD_VERSION: return "app was built for a different loader version"; + case LOADER_ERR_BAD_LAYOUT: return "app header is inconsistent (wrong slot address or sizes)"; + case LOADER_ERR_SLOT_BUSY: return "that app slot is already in use"; + case LOADER_ERR_NO_MEMORY: return "out of heap memory"; + case LOADER_ERR_ENTRY_FAILED: return "the app refused to start"; + case LOADER_ERR_LAUNCHER_FULL: return "the launcher has no free app slots"; + default: return "unknown error"; + } +} diff --git a/kernel/vigil/loader.h b/kernel/vigil/loader.h new file mode 100644 index 0000000..2b96bfe --- /dev/null +++ b/kernel/vigil/loader.h @@ -0,0 +1,28 @@ +// kernel/vigil/loader.h + +#ifndef VIGIL_LOADER_H +#define VIGIL_LOADER_H + +// folder (on the VIGIL disk) that is scanned for apps at boot +#define LOADER_APP_FOLDER "apps" + +// --- result codes (0 = success, everything else is a failure) --- + +#define LOADER_OK 0 +#define LOADER_ERR_READ -1 // could not find or read the file +#define LOADER_ERR_TOO_BIG -2 // larger than one slot +#define LOADER_ERR_BAD_MAGIC -3 // not a VAPP file +#define LOADER_ERR_BAD_VERSION -4 // made for a different loader version +#define LOADER_ERR_BAD_LAYOUT -5 // header numbers dont add up +#define LOADER_ERR_SLOT_BUSY -6 // another app already sits in that slot +#define LOADER_ERR_NO_MEMORY -7 // heap could not provide a temp buffer +#define LOADER_ERR_ENTRY_FAILED -8 // the apps app_entry() refused to start +#define LOADER_ERR_LAUNCHER_FULL -9 // no free place in the launchers list + +int loader_load(const char* path); + +int loader_load_folder(const char* folder); + +const char* loader_error_text(int code); + +#endif diff --git a/scripts/build.bat b/scripts/build.bat index 16a958b..f7148bd 100644 --- a/scripts/build.bat +++ b/scripts/build.bat @@ -10,7 +10,7 @@ if not exist "build" ( echo. ) -set CFLAGS=-ffreestanding -Ikernel/cpu -Ikernel/drivers -Iapps/shell -Ikernel/lib -Ikernel/vigil -Ikernel/fs -Ikernel/mem -Ikernel/ui -Iapps/launcher -Iapps/notepad -Iapps/files -Iapps/calculator +set CFLAGS=-ffreestanding -Ikernel/cpu -Ikernel/drivers -Iapps/shell -Ikernel/lib -Ikernel/vigil -Ikernel/fs -Ikernel/mem -Ikernel/ui -Iapps/launcher :: kernel objs @@ -126,6 +126,16 @@ echo Compiling memory.c... i686-elf-gcc %CFLAGS% -c kernel/vigil/memory.c -o build/vigil_memory.o if errorlevel 1 goto :error +:: app loader + +echo Compiling api.c... +i686-elf-gcc %CFLAGS% -c kernel/vigil/api.c -o build/vigil_api.o +if errorlevel 1 goto :error + +echo Compiling loader.c... +i686-elf-gcc %CFLAGS% -c kernel/vigil/loader.c -o build/loader.o +if errorlevel 1 goto :error + echo. :: UI elements @@ -163,28 +173,57 @@ echo Compiling Shell... i686-elf-gcc %CFLAGS% -c apps/shell/shell.c -o build/shell.o if errorlevel 1 goto :error -echo Compiling Notepad... -i686-elf-gcc %CFLAGS% -c apps/notepad/notepad.c -o build/notepad.o +echo. + +:: loadable apps (built separately from kernel then installed on disk) + +set APP_CFLAGS=-ffreestanding -fno-asynchronous-unwind-tables -Iapps/launcher -Ikernel/vigil -Ikernel/ui -Ikernel/drivers -Ikernel/fs -Ikernel/lib -Ikernel/mem + +echo Building app: hello (slot 0 = 0x400000)... +i686-elf-gcc %APP_CFLAGS% -c apps/hello/hello.c -o build/hello.o +if errorlevel 1 goto :error +i686-elf-ld -T apps/sdk/app.ld -Ttext=0x400000 -o build/hello.elf build/hello.o +if errorlevel 1 goto :error +i686-elf-objcopy -O binary build/hello.elf build/hello.vapp if errorlevel 1 goto :error -echo Compiling Files... -i686-elf-gcc %CFLAGS% -c apps/files/files.c -o build/files.o +echo Building app: calculator (slot 1 = 0x440000)... +i686-elf-gcc %APP_CFLAGS% -Iapps/calculator -c apps/calculator/calc.c -o build/calc_app.o +if errorlevel 1 goto :error +i686-elf-gcc %APP_CFLAGS% -Iapps/calculator -c apps/calculator/calculator.c -o build/calculator_app.o +if errorlevel 1 goto :error +i686-elf-ld -T apps/sdk/app.ld -Ttext=0x440000 -o build/calculator.elf build/calculator_app.o build/calc_app.o +if errorlevel 1 goto :error +i686-elf-objcopy -O binary build/calculator.elf build/calculator.vapp if errorlevel 1 goto :error -echo Compiling Calculator... -i686-elf-gcc %CFLAGS% -c apps/calculator/calc.c -o build/calc.o -i686-elf-gcc %CFLAGS% -c apps/calculator/calculator.c -o build/calculator.o +echo Building app: files (slot 2 = 0x480000)... +i686-elf-gcc %APP_CFLAGS% -c apps/files/files.c -o build/files_app.o +if errorlevel 1 goto :error +i686-elf-ld -T apps/sdk/app.ld -Ttext=0x480000 -o build/files.elf build/files_app.o +if errorlevel 1 goto :error +i686-elf-objcopy -O binary build/files.elf build/files.vapp +if errorlevel 1 goto :error + +echo Building app: notepad (slot 3 = 0x4c0000)... +i686-elf-gcc %APP_CFLAGS% -c apps/notepad/notepad.c -o build/notepad_app.o +if errorlevel 1 goto :error +i686-elf-ld -T apps/sdk/app.ld -Ttext=0x4c0000 -o build/notepad.elf build/notepad_app.o +if errorlevel 1 goto :error +i686-elf-objcopy -O binary build/notepad.elf build/notepad.vapp if errorlevel 1 goto :error +echo. + +:: link build files using linker script + echo. echo Building img build... echo ==================================== echo. -:: link build files using linker script - echo Linking kernel objects... -i686-elf-ld -T boot/linker.ld -o build/kernel_full.elf build/stage2.o build/kernel.o build/terminal.o build/idt.o build/isr.o build/isr_asm.o build/idt_load.o build/pic.o build/irq.o build/irq_asm.o build/keyboard.o build/kstring.o build/kprintf.o build/shell.o build/ata.o build/vigil_memory.o build/fs.o build/timer.o build/heap.o build/font.o build/graphics.o build/mouse.o build/button.o build/title_bar.o build/taskbar.o build/launcher.o build/notepad.o build/menu.o build/files.o build/prompt.o build/calc.o build/calculator.o +i686-elf-ld -T boot/linker.ld -o build/kernel_full.elf build/stage2.o build/kernel.o build/terminal.o build/idt.o build/isr.o build/isr_asm.o build/idt_load.o build/pic.o build/irq.o build/irq_asm.o build/keyboard.o build/kstring.o build/kprintf.o build/shell.o build/ata.o build/vigil_memory.o build/fs.o build/timer.o build/heap.o build/font.o build/graphics.o build/mouse.o build/button.o build/title_bar.o build/taskbar.o build/launcher.o build/menu.o build/prompt.o build/vigil_api.o build/loader.o if errorlevel 1 goto :error echo. @@ -245,6 +284,22 @@ if not exist "dist\storage.img" ( echo Building disk image... copy /b build\boot.bin+build\kernel_full.bin+build\padding.bin dist\vigil.img >nul +echo. + +:: install apps onto disk + +echo Installing apps onto storage disk... +python tools/install_app.py dist/storage.img build/hello.vapp apps/hello +if errorlevel 1 goto :error +python tools/install_app.py dist/storage.img build/calculator.vapp apps/calculator +if errorlevel 1 goto :error +python tools/install_app.py dist/storage.img build/files.vapp apps/files +if errorlevel 1 goto :error +python tools/install_app.py dist/storage.img build/notepad.vapp apps/notepad +if errorlevel 1 goto :error +echo. + +:: successful build echo Build Success^^! Check dist\vigil.img for output diff --git a/scripts/run.bat b/scripts/run.bat index 65ddf6a..5640f37 100644 --- a/scripts/run.bat +++ b/scripts/run.bat @@ -15,10 +15,10 @@ if not exist dist\storage.img ( if "%~1"=="--nat" ( echo Booting VIGIL in QEMU using native terminal... qemu-system-x86_64 -drive file=dist\vigil.img,format=raw,if=ide,index=0 -drive file=dist\storage.img,format=raw,if=ide,index=1 -no-reboot -no-shutdown -nographic -serial mon:stdio -) else if "%~1"=="--sdl" ( - echo Booting VIGIL in QEMU with SDL display mode... - qemu-system-x86_64 -drive file=dist\vigil.img,format=raw,if=ide,index=0 -drive file=dist\storage.img,format=raw,if=ide,index=1 -no-reboot -no-shutdown -display sdl +) else if "%~1"=="--no-sdl" ( + echo Booting VIGIL in QEMU without SDL display mode... + qemu-system-x86_64 -drive file=dist\vigil.img,format=raw,if=ide,index=0 -drive file=dist\storage.img,format=raw,if=ide,index=1 -no-reboot -no-shutdown ) else ( echo Booting VIGIL in QEMU... - qemu-system-x86_64 -drive file=dist\vigil.img,format=raw,if=ide,index=0 -drive file=dist\storage.img,format=raw,if=ide,index=1 -no-reboot -no-shutdown + qemu-system-x86_64 -drive file=dist\vigil.img,format=raw,if=ide,index=0 -drive file=dist\storage.img,format=raw,if=ide,index=1 -no-reboot -no-shutdown -display sdl ) diff --git a/tools/install_app.py b/tools/install_app.py new file mode 100644 index 0000000..34083c4 --- /dev/null +++ b/tools/install_app.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +""" +tools/install_app.py + +Copies a file from PC into VIGILs disk image (dist/storage.img) as a +normal VIGIL file, creating any missing folders on the way. + +It does what VIGILs filesystem code (kernel/fs/fs.c) does by hand, so +the two must agree on the layout. If fs.c is ever changed, change this too + +Usage: + python tools/install_app.py +Example: + python tools/install_app.py dist/storage.img build/hello.vapp apps/hello + +NOTE!!: +Close QEMU first: it keeps the image file open while it is running. +""" + +import struct +import sys +from collections.abc import Sequence +from typing import BinaryIO, NoReturn, TypedDict + +# --- disk layout --- + +SECTOR_SIZE = 512 +TABLE_LBA = 1 # the file table starts at sector 1 +TABLE_SECTORS = 2 # -> and is 2 sectors (1024 bytes) long +DATA_START_LBA = 100 # file contents are stored from sector 100 on +MAGIC = 0x46535632 # marks a disk that already has a file table +ROOT = 0xFF # "parent" value meaning "toplevel folder" +MAX_FILES = 32 +MAX_NAME_LEN = 16 # 15 characters + a terminating zero byte + +# One table entry is packed with no padding: +# name[16] | start_lba (4 bytes) | size_bytes (4) | used (1) | is_dir (1) | parent (1) +# '<' means littleendian (the byte order of x86) with no padding +ENTRY_FORMAT = '<16sIIBBB' + + +class Entry(TypedDict): + name: str + start_lba: int + size: int + used: int + is_dir: int + parent: int + + +# --- reading and writing the table --- + +def empty_entry() -> Entry: + return {'name': '', 'start_lba': 0, 'size': 0, 'used': 0, 'is_dir': 0, 'parent': ROOT} + + +def read_table(image: BinaryIO) -> list[Entry]: + image.seek(TABLE_LBA * SECTOR_SIZE) + raw = image.read(TABLE_SECTORS * SECTOR_SIZE) + + magic = struct.unpack_from('= 4 else 0 + if magic != MAGIC: + return [empty_entry() for _ in range(MAX_FILES)] + + entries: list[Entry] = [] + entry_size = struct.calcsize(ENTRY_FORMAT) + for i in range(MAX_FILES): + name, start, size, used, is_dir, parent = struct.unpack_from(ENTRY_FORMAT, raw, 4 + i * entry_size) + entries.append({ + 'name': name.split(b'\0')[0].decode('ascii', errors='replace'), + 'start_lba': start, + 'size': size, + 'used': used, + 'is_dir': is_dir, + 'parent': parent, + }) + return entries + + +def write_table(image: BinaryIO, entries: Sequence[Entry]) -> None: + raw = struct.pack(' int | None: + for i, e in enumerate(entries): + if e['used'] and e['parent'] == parent and e['name'] == name: + return i + return None + + +def find_free_slot(entries: Sequence[Entry]) -> int | None: + for i, e in enumerate(entries): + if not e['used']: + return i + return None + + +def sectors_needed(size: int) -> int: + return (size + SECTOR_SIZE - 1) // SECTOR_SIZE + + +def find_free_space(entries: Sequence[Entry], sectors: int, skip_index: int | None) -> int: + """the first gap between existing files big enough to hold""" + ranges: list[tuple[int, int]] = [] + for i, e in enumerate(entries): + if e['used'] and not e['is_dir'] and i != skip_index: + ranges.append((e['start_lba'], e['start_lba'] + sectors_needed(e['size']))) + ranges.sort() + + cursor = DATA_START_LBA + for start, end in ranges: + if start > cursor and start - cursor >= sectors: + return cursor + if end > cursor: + cursor = end + return cursor + + +# --- the install --- + +def fail(message: str) -> NoReturn: + print('install_app: ' + message, file=sys.stderr) + sys.exit(1) + +def image_size(image: BinaryIO) -> int: + image.seek(0, 2) + return image.tell() + +def install(image_path: str, pc_file: str, vigil_path: str) -> None: + parts = [p for p in vigil_path.split('/') if p] + if not parts: + fail('empty path inside VIGIL') + for p in parts: + if len(p) >= MAX_NAME_LEN or p in ('.', '..'): + fail("bad name '%s' (1-15 characters)" % p) + + try: + with open(pc_file, 'rb') as f: + data = f.read() + except OSError as err: + fail('cannot read %s: %s' % (pc_file, err)) + + try: + image = open(image_path, 'r+b') # r+b = read AND write, binary + except OSError as err: + fail('cannot open %s: %s (run the build first?)' % (image_path, err)) + + with image: + entries = read_table(image) + + # walk down the folders, creating any that are missing + parent = ROOT + for folder in parts[:-1]: + index = find_child(entries, parent, folder) + if index is None: + index = find_free_slot(entries) + if index is None: + fail('the VIGIL file table is full (32 items)') + entries[index] = {'name': folder, 'start_lba': 0, 'size': 0, + 'used': 1, 'is_dir': 1, 'parent': parent} + elif not entries[index]['is_dir']: + fail("'%s' is a file, not a folder" % folder) + parent = index + + leaf = parts[-1] + existing = find_child(entries, parent, leaf) + if existing is not None and entries[existing]['is_dir']: + fail("'%s' is a folder" % leaf) + + index = existing if existing is not None else find_free_slot(entries) + if index is None: + fail('the VIGIL file table is full (32 items)') + + sectors = sectors_needed(len(data)) + start = find_free_space(entries, sectors, existing) + + if (start + sectors) * SECTOR_SIZE > image_size(image): + fail('the disk image is too small for this file') + + image.seek(start * SECTOR_SIZE) + image.write(data.ljust(sectors * SECTOR_SIZE, b'\0')) + + entries[index] = {'name': leaf, 'start_lba': start, 'size': len(data), + 'used': 1, 'is_dir': 0, 'parent': parent} + write_table(image, entries) + + print('installed %s -> %s (%d bytes)' % (pc_file, vigil_path, len(data))) + + +if __name__ == "__main__": + if len(sys.argv) != 4: + fail('usage: install_app.py ') + install(sys.argv[1], sys.argv[2], sys.argv[3]) diff --git a/tools/test_install_app.py b/tools/test_install_app.py new file mode 100644 index 0000000..562d101 --- /dev/null +++ b/tools/test_install_app.py @@ -0,0 +1,113 @@ +import contextlib +import io +import sys +import tempfile +import unittest +from pathlib import Path + +import install_app + + +class InstallAppTests(unittest.TestCase): + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(self.temp_dir.cleanup) + self.directory = Path(self.temp_dir.name) + self.image_path = self.directory / "storage.img" + self.source_path = self.directory / "app.vapp" + + def create_image(self, sectors=200): + self.image_path.write_bytes(b"\0" * (sectors * install_app.SECTOR_SIZE)) + + def run_install(self, vigil_path): + with contextlib.redirect_stdout(io.StringIO()): + install_app.install(str(self.image_path), str(self.source_path), vigil_path) + + def test_installs_file_and_creates_nested_folders(self): + data = bytes(range(256)) * 3 + self.create_image() + self.source_path.write_bytes(data) + + self.run_install("apps/demo") + + with self.image_path.open("rb") as image: + entries = install_app.read_table(image) + + apps_index = install_app.find_child(entries, install_app.ROOT, "apps") + if apps_index is None: + self.fail("apps folder was not installed") + demo_index = install_app.find_child(entries, apps_index, "demo") + if demo_index is None: + self.fail("app was not installed in the apps folder") + + demo = entries[demo_index] + self.assertEqual(demo["size"], len(data)) + with self.image_path.open("rb") as image: + image.seek(demo["start_lba"] * install_app.SECTOR_SIZE) + installed = image.read(install_app.sectors_needed(len(data)) * install_app.SECTOR_SIZE) + self.assertEqual(installed, data.ljust(len(installed), b"\0")) + + def test_replaces_existing_file(self): + self.create_image() + self.source_path.write_bytes(b"old app") + self.run_install("apps/demo") + + updated = b"updated app contents" + self.source_path.write_bytes(updated) + self.run_install("apps/demo") + + with self.image_path.open("rb") as image: + entries = install_app.read_table(image) + apps_index = install_app.find_child(entries, install_app.ROOT, "apps") + if apps_index is None: + self.fail("apps folder was not installed") + demo_index = install_app.find_child(entries, apps_index, "demo") + if demo_index is None: + self.fail("app was not installed in the apps folder") + image.seek(entries[demo_index]["start_lba"] * install_app.SECTOR_SIZE) + self.assertEqual(image.read(len(updated)), updated) + + self.assertEqual( + sum(entry["used"] and entry["name"] == "demo" for entry in entries), + 1, + ) + + def test_rejects_parent_traversal_without_changing_image(self): + self.create_image() + self.source_path.write_bytes(b"app") + original_image = self.image_path.read_bytes() + + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + self.run_install("apps/../outside") + + self.assertEqual(self.image_path.read_bytes(), original_image) + + def test_fails_when_file_table_is_full(self): + self.create_image() + self.source_path.write_bytes(b"app") + entries: list[install_app.Entry] = [ + { + "name": f"dir{index}", + "start_lba": 0, + "size": 0, + "used": 1, + "is_dir": 1, + "parent": install_app.ROOT, + } + for index in range(install_app.MAX_FILES) + ] + with self.image_path.open("r+b") as image: + install_app.write_table(image, entries) + + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + self.run_install("apps/demo") + + def test_fails_when_disk_image_has_no_room_for_file(self): + self.create_image(sectors=install_app.DATA_START_LBA) + self.source_path.write_bytes(b"app") + + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + self.run_install("apps/demo") + +if __name__ == "__main__": + unittest.main()